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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
dcos/shakedown | shakedown/dcos/task.py | wait_for_task | def wait_for_task(service, task, timeout_sec=120):
"""Waits for a task which was launched to be launched"""
return time_wait(lambda: task_predicate(service, task), timeout_seconds=timeout_sec) | python | def wait_for_task(service, task, timeout_sec=120):
"""Waits for a task which was launched to be launched"""
return time_wait(lambda: task_predicate(service, task), timeout_seconds=timeout_sec) | [
"def",
"wait_for_task",
"(",
"service",
",",
"task",
",",
"timeout_sec",
"=",
"120",
")",
":",
"return",
"time_wait",
"(",
"lambda",
":",
"task_predicate",
"(",
"service",
",",
"task",
")",
",",
"timeout_seconds",
"=",
"timeout_sec",
")"
] | Waits for a task which was launched to be launched | [
"Waits",
"for",
"a",
"task",
"which",
"was",
"launched",
"to",
"be",
"launched"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/task.py#L118-L120 | train | 39,500 |
dcos/shakedown | shakedown/dcos/task.py | wait_for_task_property | def wait_for_task_property(service, task, prop, timeout_sec=120):
"""Waits for a task to have the specified property"""
return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec) | python | def wait_for_task_property(service, task, prop, timeout_sec=120):
"""Waits for a task to have the specified property"""
return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec) | [
"def",
"wait_for_task_property",
"(",
"service",
",",
"task",
",",
"prop",
",",
"timeout_sec",
"=",
"120",
")",
":",
"return",
"time_wait",
"(",
"lambda",
":",
"task_property_present_predicate",
"(",
"service",
",",
"task",
",",
"prop",
")",
",",
"timeout_seco... | Waits for a task to have the specified property | [
"Waits",
"for",
"a",
"task",
"to",
"have",
"the",
"specified",
"property"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/task.py#L123-L125 | train | 39,501 |
dcos/shakedown | shakedown/dcos/file.py | copy_file | def copy_file(
host,
file_path,
remote_path='.',
username=None,
key_path=None,
action='put'
):
""" Copy a file via SCP, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param file_path: the local path to the file to be copied
:type file_path: str
:param remote_path: the remote path to copy the file to
:type remote_path: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key to use for SSH authentication
:type key_path: str
:return: True if successful, False otherwise
:rtype: bool
"""
if not username:
username = shakedown.cli.ssh_user
if not key_path:
key_path = shakedown.cli.ssh_key_file
key = validate_key(key_path)
transport = get_transport(host, username, key)
transport = start_transport(transport, username, key)
if transport.is_authenticated():
start = time.time()
channel = scp.SCPClient(transport)
if action == 'get':
print("\n{}scp {}:{} {}\n".format(shakedown.cli.helpers.fchr('>>'), host, remote_path, file_path))
channel.get(remote_path, file_path)
else:
print("\n{}scp {} {}:{}\n".format(shakedown.cli.helpers.fchr('>>'), file_path, host, remote_path))
channel.put(file_path, remote_path)
print("{} bytes copied in {} seconds.".format(str(os.path.getsize(file_path)), str(round(time.time() - start, 2))))
try_close(channel)
try_close(transport)
return True
else:
print("error: unable to authenticate {}@{} with key {}".format(username, host, key_path))
return False | python | def copy_file(
host,
file_path,
remote_path='.',
username=None,
key_path=None,
action='put'
):
""" Copy a file via SCP, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param file_path: the local path to the file to be copied
:type file_path: str
:param remote_path: the remote path to copy the file to
:type remote_path: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key to use for SSH authentication
:type key_path: str
:return: True if successful, False otherwise
:rtype: bool
"""
if not username:
username = shakedown.cli.ssh_user
if not key_path:
key_path = shakedown.cli.ssh_key_file
key = validate_key(key_path)
transport = get_transport(host, username, key)
transport = start_transport(transport, username, key)
if transport.is_authenticated():
start = time.time()
channel = scp.SCPClient(transport)
if action == 'get':
print("\n{}scp {}:{} {}\n".format(shakedown.cli.helpers.fchr('>>'), host, remote_path, file_path))
channel.get(remote_path, file_path)
else:
print("\n{}scp {} {}:{}\n".format(shakedown.cli.helpers.fchr('>>'), file_path, host, remote_path))
channel.put(file_path, remote_path)
print("{} bytes copied in {} seconds.".format(str(os.path.getsize(file_path)), str(round(time.time() - start, 2))))
try_close(channel)
try_close(transport)
return True
else:
print("error: unable to authenticate {}@{} with key {}".format(username, host, key_path))
return False | [
"def",
"copy_file",
"(",
"host",
",",
"file_path",
",",
"remote_path",
"=",
"'.'",
",",
"username",
"=",
"None",
",",
"key_path",
"=",
"None",
",",
"action",
"=",
"'put'",
")",
":",
"if",
"not",
"username",
":",
"username",
"=",
"shakedown",
".",
"cli"... | Copy a file via SCP, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param file_path: the local path to the file to be copied
:type file_path: str
:param remote_path: the remote path to copy the file to
:type remote_path: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key to use for SSH authentication
:type key_path: str
:return: True if successful, False otherwise
:rtype: bool | [
"Copy",
"a",
"file",
"via",
"SCP",
"proxied",
"through",
"the",
"mesos",
"master"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/file.py#L10-L66 | train | 39,502 |
dcos/shakedown | shakedown/dcos/cluster.py | __metadata_helper | def __metadata_helper(json_path):
""" Returns json for specific cluster metadata. Important to realize that
this was introduced in dcos-1.9. Clusters prior to 1.9 and missing metadata
will return None
"""
url = shakedown.dcos_url_path('dcos-metadata/{}'.format(json_path))
try:
response = dcos.http.request('get', url)
if response.status_code == 200:
return response.json()
except:
pass
return None | python | def __metadata_helper(json_path):
""" Returns json for specific cluster metadata. Important to realize that
this was introduced in dcos-1.9. Clusters prior to 1.9 and missing metadata
will return None
"""
url = shakedown.dcos_url_path('dcos-metadata/{}'.format(json_path))
try:
response = dcos.http.request('get', url)
if response.status_code == 200:
return response.json()
except:
pass
return None | [
"def",
"__metadata_helper",
"(",
"json_path",
")",
":",
"url",
"=",
"shakedown",
".",
"dcos_url_path",
"(",
"'dcos-metadata/{}'",
".",
"format",
"(",
"json_path",
")",
")",
"try",
":",
"response",
"=",
"dcos",
".",
"http",
".",
"request",
"(",
"'get'",
","... | Returns json for specific cluster metadata. Important to realize that
this was introduced in dcos-1.9. Clusters prior to 1.9 and missing metadata
will return None | [
"Returns",
"json",
"for",
"specific",
"cluster",
"metadata",
".",
"Important",
"to",
"realize",
"that",
"this",
"was",
"introduced",
"in",
"dcos",
"-",
"1",
".",
"9",
".",
"Clusters",
"prior",
"to",
"1",
".",
"9",
"and",
"missing",
"metadata",
"will",
"r... | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/cluster.py#L93-L107 | train | 39,503 |
openstax/cnx-easybake | cnxeasybake/oven.py | log_decl_method | def log_decl_method(func):
"""Decorate do_declartion methods for debug logging."""
from functools import wraps
@wraps(func)
def with_logging(*args, **kwargs):
self = args[0]
decl = args[2]
log(DEBUG, u" {}: {} {}".format(
self.state['current_step'], decl.name,
serialize(decl.value).strip()).encode('utf-8'))
return func(*args, **kwargs)
return with_logging | python | def log_decl_method(func):
"""Decorate do_declartion methods for debug logging."""
from functools import wraps
@wraps(func)
def with_logging(*args, **kwargs):
self = args[0]
decl = args[2]
log(DEBUG, u" {}: {} {}".format(
self.state['current_step'], decl.name,
serialize(decl.value).strip()).encode('utf-8'))
return func(*args, **kwargs)
return with_logging | [
"def",
"log_decl_method",
"(",
"func",
")",
":",
"from",
"functools",
"import",
"wraps",
"@",
"wraps",
"(",
"func",
")",
"def",
"with_logging",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"decl",
"=",
"a... | Decorate do_declartion methods for debug logging. | [
"Decorate",
"do_declartion",
"methods",
"for",
"debug",
"logging",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L59-L71 | train | 39,504 |
openstax/cnx-easybake | cnxeasybake/oven.py | css_to_func | def css_to_func(css, flags, css_namespaces, lang):
"""Convert a css selector to an xpath, supporting pseudo elements."""
from cssselect import parse, HTMLTranslator
from cssselect.parser import FunctionalPseudoElement
# FIXME HACK need lessc to support functional-pseudo-selectors instead
# of marking as strings and stripping " here.
if not (css):
return None
sel = parse(css.strip('" '))[0]
xpath = HTMLTranslator().selector_to_xpath(sel)
first_letter = False
if sel.pseudo_element is not None:
if type(sel.pseudo_element) == FunctionalPseudoElement:
if sel.pseudo_element.name in ('attr', 'first-letter'):
xpath += '/@' + sel.pseudo_element.arguments[0].value
if sel.pseudo_element.name == 'first-letter':
first_letter = True
elif isinstance(sel.pseudo_element, type(u'')):
if sel.pseudo_element == 'first-letter':
first_letter = True
xp = etree.XPath(xpath, namespaces=css_namespaces)
def toupper(u):
"""Use icu library for locale sensitive uppercasing (python2)."""
loc = Locale(lang) if lang else Locale()
return UnicodeString(u).toUpper(loc).encode('utf-8').decode('utf-8')
def func(elem):
res = xp(elem)
if res:
if etree.iselement(res[0]):
res_str = etree.tostring(res[0], encoding='unicode',
method="text")
else:
res_str = res[0]
if first_letter:
if res_str:
if flags and 'nocase' in flags:
return toupper(res_str[0])
else:
return res_str[0]
else:
return res_str
else:
if flags and 'nocase' in flags:
return toupper(res_str)
else:
return res_str
return func | python | def css_to_func(css, flags, css_namespaces, lang):
"""Convert a css selector to an xpath, supporting pseudo elements."""
from cssselect import parse, HTMLTranslator
from cssselect.parser import FunctionalPseudoElement
# FIXME HACK need lessc to support functional-pseudo-selectors instead
# of marking as strings and stripping " here.
if not (css):
return None
sel = parse(css.strip('" '))[0]
xpath = HTMLTranslator().selector_to_xpath(sel)
first_letter = False
if sel.pseudo_element is not None:
if type(sel.pseudo_element) == FunctionalPseudoElement:
if sel.pseudo_element.name in ('attr', 'first-letter'):
xpath += '/@' + sel.pseudo_element.arguments[0].value
if sel.pseudo_element.name == 'first-letter':
first_letter = True
elif isinstance(sel.pseudo_element, type(u'')):
if sel.pseudo_element == 'first-letter':
first_letter = True
xp = etree.XPath(xpath, namespaces=css_namespaces)
def toupper(u):
"""Use icu library for locale sensitive uppercasing (python2)."""
loc = Locale(lang) if lang else Locale()
return UnicodeString(u).toUpper(loc).encode('utf-8').decode('utf-8')
def func(elem):
res = xp(elem)
if res:
if etree.iselement(res[0]):
res_str = etree.tostring(res[0], encoding='unicode',
method="text")
else:
res_str = res[0]
if first_letter:
if res_str:
if flags and 'nocase' in flags:
return toupper(res_str[0])
else:
return res_str[0]
else:
return res_str
else:
if flags and 'nocase' in flags:
return toupper(res_str)
else:
return res_str
return func | [
"def",
"css_to_func",
"(",
"css",
",",
"flags",
",",
"css_namespaces",
",",
"lang",
")",
":",
"from",
"cssselect",
"import",
"parse",
",",
"HTMLTranslator",
"from",
"cssselect",
".",
"parser",
"import",
"FunctionalPseudoElement",
"# FIXME HACK need lessc to support f... | Convert a css selector to an xpath, supporting pseudo elements. | [
"Convert",
"a",
"css",
"selector",
"to",
"an",
"xpath",
"supporting",
"pseudo",
"elements",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1335-L1387 | train | 39,505 |
openstax/cnx-easybake | cnxeasybake/oven.py | append_string | def append_string(t, string):
"""Append a string to a node, as text or tail of last child."""
node = t.tree
if string:
if len(node) == 0:
if node.text is not None:
node.text += string
else:
node.text = string
else: # Get last child
child = list(node)[-1]
if child.tail is not None:
child.tail += string
else:
child.tail = string | python | def append_string(t, string):
"""Append a string to a node, as text or tail of last child."""
node = t.tree
if string:
if len(node) == 0:
if node.text is not None:
node.text += string
else:
node.text = string
else: # Get last child
child = list(node)[-1]
if child.tail is not None:
child.tail += string
else:
child.tail = string | [
"def",
"append_string",
"(",
"t",
",",
"string",
")",
":",
"node",
"=",
"t",
".",
"tree",
"if",
"string",
":",
"if",
"len",
"(",
"node",
")",
"==",
"0",
":",
"if",
"node",
".",
"text",
"is",
"not",
"None",
":",
"node",
".",
"text",
"+=",
"strin... | Append a string to a node, as text or tail of last child. | [
"Append",
"a",
"string",
"to",
"a",
"node",
"as",
"text",
"or",
"tail",
"of",
"last",
"child",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1390-L1404 | train | 39,506 |
openstax/cnx-easybake | cnxeasybake/oven.py | prepend_string | def prepend_string(t, string):
"""Prepend a string to a target node as text."""
node = t.tree
if node.text is not None:
node.text += string
else:
node.text = string | python | def prepend_string(t, string):
"""Prepend a string to a target node as text."""
node = t.tree
if node.text is not None:
node.text += string
else:
node.text = string | [
"def",
"prepend_string",
"(",
"t",
",",
"string",
")",
":",
"node",
"=",
"t",
".",
"tree",
"if",
"node",
".",
"text",
"is",
"not",
"None",
":",
"node",
".",
"text",
"+=",
"string",
"else",
":",
"node",
".",
"text",
"=",
"string"
] | Prepend a string to a target node as text. | [
"Prepend",
"a",
"string",
"to",
"a",
"target",
"node",
"as",
"text",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1407-L1413 | train | 39,507 |
openstax/cnx-easybake | cnxeasybake/oven.py | grouped_insert | def grouped_insert(t, value):
"""Insert value into the target tree 't' with correct grouping."""
collator = Collator.createInstance(Locale(t.lang) if t.lang else Locale())
if value.tail is not None:
val_prev = value.getprevious()
if val_prev is not None:
val_prev.tail = (val_prev.tail or '') + value.tail
else:
val_parent = value.getparent()
if val_parent is not None:
val_parent.text = (val_parent.text or '') + value.tail
value.tail = None
if t.isgroup and t.sort(value) is not None:
if t.groupby:
for child in t.tree:
if child.get('class') == 'group-by':
# child[0] is the label span
order = collator.compare(
t.groupby(child[1]) or '', t.groupby(value) or '')
if order == 0:
c_target = Target(child, sort=t.sort, lang=t.lang)
insert_group(value, c_target)
break
elif order > 0:
group = create_group(t.groupby(value))
group.append(value)
child.addprevious(group)
break
else:
group = create_group(t.groupby(value))
group.append(value)
t.tree.append(group)
else:
insert_group(value, t)
elif t.sort and t.sort(value) is not None:
insert_sort(value, t)
elif t.location == 'inside':
for child in t.tree:
value.append(child)
value.text = t.tree.text
t.tree.text = None
t.tree.append(value)
elif t.location == 'outside':
value.tail = t.tree.tail
t.tree.tail = None
target_parent_descendants = (
[n.getparent() for n in t.parent.iterdescendants() if n == t.tree])
try:
parent = target_parent_descendants[0]
parent.insert(parent.index(t.tree), value)
value.append(t.tree)
except IndexError as e:
logger.error('Target of outside has been moved or deleted')
raise e
elif t.location == 'before':
value.tail = t.tree.text
t.tree.text = None
t.tree.insert(0, value)
else:
t.tree.append(value) | python | def grouped_insert(t, value):
"""Insert value into the target tree 't' with correct grouping."""
collator = Collator.createInstance(Locale(t.lang) if t.lang else Locale())
if value.tail is not None:
val_prev = value.getprevious()
if val_prev is not None:
val_prev.tail = (val_prev.tail or '') + value.tail
else:
val_parent = value.getparent()
if val_parent is not None:
val_parent.text = (val_parent.text or '') + value.tail
value.tail = None
if t.isgroup and t.sort(value) is not None:
if t.groupby:
for child in t.tree:
if child.get('class') == 'group-by':
# child[0] is the label span
order = collator.compare(
t.groupby(child[1]) or '', t.groupby(value) or '')
if order == 0:
c_target = Target(child, sort=t.sort, lang=t.lang)
insert_group(value, c_target)
break
elif order > 0:
group = create_group(t.groupby(value))
group.append(value)
child.addprevious(group)
break
else:
group = create_group(t.groupby(value))
group.append(value)
t.tree.append(group)
else:
insert_group(value, t)
elif t.sort and t.sort(value) is not None:
insert_sort(value, t)
elif t.location == 'inside':
for child in t.tree:
value.append(child)
value.text = t.tree.text
t.tree.text = None
t.tree.append(value)
elif t.location == 'outside':
value.tail = t.tree.tail
t.tree.tail = None
target_parent_descendants = (
[n.getparent() for n in t.parent.iterdescendants() if n == t.tree])
try:
parent = target_parent_descendants[0]
parent.insert(parent.index(t.tree), value)
value.append(t.tree)
except IndexError as e:
logger.error('Target of outside has been moved or deleted')
raise e
elif t.location == 'before':
value.tail = t.tree.text
t.tree.text = None
t.tree.insert(0, value)
else:
t.tree.append(value) | [
"def",
"grouped_insert",
"(",
"t",
",",
"value",
")",
":",
"collator",
"=",
"Collator",
".",
"createInstance",
"(",
"Locale",
"(",
"t",
".",
"lang",
")",
"if",
"t",
".",
"lang",
"else",
"Locale",
"(",
")",
")",
"if",
"value",
".",
"tail",
"is",
"no... | Insert value into the target tree 't' with correct grouping. | [
"Insert",
"value",
"into",
"the",
"target",
"tree",
"t",
"with",
"correct",
"grouping",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1416-L1479 | train | 39,508 |
openstax/cnx-easybake | cnxeasybake/oven.py | insert_sort | def insert_sort(node, target):
"""Insert node into sorted position in target tree.
Uses sort function and language from target"""
sort = target.sort
lang = target.lang
collator = Collator.createInstance(Locale(lang) if lang else Locale())
for child in target.tree:
if collator.compare(sort(child) or '', sort(node) or '') > 0:
child.addprevious(node)
break
else:
target.tree.append(node) | python | def insert_sort(node, target):
"""Insert node into sorted position in target tree.
Uses sort function and language from target"""
sort = target.sort
lang = target.lang
collator = Collator.createInstance(Locale(lang) if lang else Locale())
for child in target.tree:
if collator.compare(sort(child) or '', sort(node) or '') > 0:
child.addprevious(node)
break
else:
target.tree.append(node) | [
"def",
"insert_sort",
"(",
"node",
",",
"target",
")",
":",
"sort",
"=",
"target",
".",
"sort",
"lang",
"=",
"target",
".",
"lang",
"collator",
"=",
"Collator",
".",
"createInstance",
"(",
"Locale",
"(",
"lang",
")",
"if",
"lang",
"else",
"Locale",
"("... | Insert node into sorted position in target tree.
Uses sort function and language from target | [
"Insert",
"node",
"into",
"sorted",
"position",
"in",
"target",
"tree",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1482-L1494 | train | 39,509 |
openstax/cnx-easybake | cnxeasybake/oven.py | insert_group | def insert_group(node, target):
"""Insert node into in target tree, in appropriate group.
Uses group and lang from target function. This assumes the node and
target share a structure of a first child that determines the grouping,
and a second child that will be accumulated in the group.
"""
group = target.sort
lang = target.lang
collator = Collator.createInstance(Locale(lang) if lang else Locale())
for child in target.tree:
order = collator.compare(group(child) or '', group(node) or '')
if order == 0:
for nodechild in node[1:]:
child.append(nodechild)
break
elif order > 0:
child.addprevious(node)
break
else:
target.tree.append(node) | python | def insert_group(node, target):
"""Insert node into in target tree, in appropriate group.
Uses group and lang from target function. This assumes the node and
target share a structure of a first child that determines the grouping,
and a second child that will be accumulated in the group.
"""
group = target.sort
lang = target.lang
collator = Collator.createInstance(Locale(lang) if lang else Locale())
for child in target.tree:
order = collator.compare(group(child) or '', group(node) or '')
if order == 0:
for nodechild in node[1:]:
child.append(nodechild)
break
elif order > 0:
child.addprevious(node)
break
else:
target.tree.append(node) | [
"def",
"insert_group",
"(",
"node",
",",
"target",
")",
":",
"group",
"=",
"target",
".",
"sort",
"lang",
"=",
"target",
".",
"lang",
"collator",
"=",
"Collator",
".",
"createInstance",
"(",
"Locale",
"(",
"lang",
")",
"if",
"lang",
"else",
"Locale",
"... | Insert node into in target tree, in appropriate group.
Uses group and lang from target function. This assumes the node and
target share a structure of a first child that determines the grouping,
and a second child that will be accumulated in the group. | [
"Insert",
"node",
"into",
"in",
"target",
"tree",
"in",
"appropriate",
"group",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1497-L1518 | train | 39,510 |
openstax/cnx-easybake | cnxeasybake/oven.py | create_group | def create_group(value):
"""Create the group wrapper node."""
node = etree.Element('div', attrib={'class': 'group-by'})
span = etree.Element('span', attrib={'class': 'group-label'})
span.text = value
node.append(span)
return node | python | def create_group(value):
"""Create the group wrapper node."""
node = etree.Element('div', attrib={'class': 'group-by'})
span = etree.Element('span', attrib={'class': 'group-label'})
span.text = value
node.append(span)
return node | [
"def",
"create_group",
"(",
"value",
")",
":",
"node",
"=",
"etree",
".",
"Element",
"(",
"'div'",
",",
"attrib",
"=",
"{",
"'class'",
":",
"'group-by'",
"}",
")",
"span",
"=",
"etree",
".",
"Element",
"(",
"'span'",
",",
"attrib",
"=",
"{",
"'class'... | Create the group wrapper node. | [
"Create",
"the",
"group",
"wrapper",
"node",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1521-L1527 | train | 39,511 |
openstax/cnx-easybake | cnxeasybake/oven.py | _extract_sel_info | def _extract_sel_info(sel):
"""Recurse down parsed tree, return pseudo class info"""
from cssselect2.parser import (CombinedSelector, CompoundSelector,
PseudoClassSelector,
FunctionalPseudoClassSelector)
steps = []
extras = []
if isinstance(sel, CombinedSelector):
lstep, lextras = _extract_sel_info(sel.left)
rstep, rextras = _extract_sel_info(sel.right)
steps = lstep + rstep
extras = lextras + rextras
elif isinstance(sel, CompoundSelector):
for ssel in sel.simple_selectors:
s, e = _extract_sel_info(ssel)
steps.extend(s)
extras.extend(e)
elif isinstance(sel, FunctionalPseudoClassSelector):
if sel.name == 'pass':
steps.append(serialize(sel.arguments).strip('"\''))
elif isinstance(sel, PseudoClassSelector):
if sel.name == 'deferred':
extras.append('deferred')
return (steps, extras) | python | def _extract_sel_info(sel):
"""Recurse down parsed tree, return pseudo class info"""
from cssselect2.parser import (CombinedSelector, CompoundSelector,
PseudoClassSelector,
FunctionalPseudoClassSelector)
steps = []
extras = []
if isinstance(sel, CombinedSelector):
lstep, lextras = _extract_sel_info(sel.left)
rstep, rextras = _extract_sel_info(sel.right)
steps = lstep + rstep
extras = lextras + rextras
elif isinstance(sel, CompoundSelector):
for ssel in sel.simple_selectors:
s, e = _extract_sel_info(ssel)
steps.extend(s)
extras.extend(e)
elif isinstance(sel, FunctionalPseudoClassSelector):
if sel.name == 'pass':
steps.append(serialize(sel.arguments).strip('"\''))
elif isinstance(sel, PseudoClassSelector):
if sel.name == 'deferred':
extras.append('deferred')
return (steps, extras) | [
"def",
"_extract_sel_info",
"(",
"sel",
")",
":",
"from",
"cssselect2",
".",
"parser",
"import",
"(",
"CombinedSelector",
",",
"CompoundSelector",
",",
"PseudoClassSelector",
",",
"FunctionalPseudoClassSelector",
")",
"steps",
"=",
"[",
"]",
"extras",
"=",
"[",
... | Recurse down parsed tree, return pseudo class info | [
"Recurse",
"down",
"parsed",
"tree",
"return",
"pseudo",
"class",
"info"
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1530-L1553 | train | 39,512 |
openstax/cnx-easybake | cnxeasybake/oven.py | _to_roman | def _to_roman(num):
"""Convert integer to roman numerals."""
roman_numeral_map = (
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1)
)
if not (0 < num < 5000):
log(WARN, 'Number out of range for roman (must be 1..4999)')
return str(num)
result = ''
for numeral, integer in roman_numeral_map:
while num >= integer:
result += numeral
num -= integer
return result | python | def _to_roman(num):
"""Convert integer to roman numerals."""
roman_numeral_map = (
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1)
)
if not (0 < num < 5000):
log(WARN, 'Number out of range for roman (must be 1..4999)')
return str(num)
result = ''
for numeral, integer in roman_numeral_map:
while num >= integer:
result += numeral
num -= integer
return result | [
"def",
"_to_roman",
"(",
"num",
")",
":",
"roman_numeral_map",
"=",
"(",
"(",
"'M'",
",",
"1000",
")",
",",
"(",
"'CM'",
",",
"900",
")",
",",
"(",
"'D'",
",",
"500",
")",
",",
"(",
"'CD'",
",",
"400",
")",
",",
"(",
"'C'",
",",
"100",
")",
... | Convert integer to roman numerals. | [
"Convert",
"integer",
"to",
"roman",
"numerals",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1570-L1595 | train | 39,513 |
openstax/cnx-easybake | cnxeasybake/oven.py | copy_w_id_suffix | def copy_w_id_suffix(elem, suffix="_copy"):
"""Make a deep copy of the provided tree, altering ids."""
mycopy = deepcopy(elem)
for id_elem in mycopy.xpath('//*[@id]'):
id_elem.set('id', id_elem.get('id') + suffix)
return mycopy | python | def copy_w_id_suffix(elem, suffix="_copy"):
"""Make a deep copy of the provided tree, altering ids."""
mycopy = deepcopy(elem)
for id_elem in mycopy.xpath('//*[@id]'):
id_elem.set('id', id_elem.get('id') + suffix)
return mycopy | [
"def",
"copy_w_id_suffix",
"(",
"elem",
",",
"suffix",
"=",
"\"_copy\"",
")",
":",
"mycopy",
"=",
"deepcopy",
"(",
"elem",
")",
"for",
"id_elem",
"in",
"mycopy",
".",
"xpath",
"(",
"'//*[@id]'",
")",
":",
"id_elem",
".",
"set",
"(",
"'id'",
",",
"id_el... | Make a deep copy of the provided tree, altering ids. | [
"Make",
"a",
"deep",
"copy",
"of",
"the",
"provided",
"tree",
"altering",
"ids",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1598-L1603 | train | 39,514 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.generate_id | def generate_id(self):
"""Generate a fresh id"""
if self.use_repeatable_ids:
self.repeatable_id_counter += 1
return 'autobaked-{}'.format(self.repeatable_id_counter)
else:
return str(uuid4()) | python | def generate_id(self):
"""Generate a fresh id"""
if self.use_repeatable_ids:
self.repeatable_id_counter += 1
return 'autobaked-{}'.format(self.repeatable_id_counter)
else:
return str(uuid4()) | [
"def",
"generate_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"use_repeatable_ids",
":",
"self",
".",
"repeatable_id_counter",
"+=",
"1",
"return",
"'autobaked-{}'",
".",
"format",
"(",
"self",
".",
"repeatable_id_counter",
")",
"else",
":",
"return",
"str",... | Generate a fresh id | [
"Generate",
"a",
"fresh",
"id"
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L152-L158 | train | 39,515 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.clear_state | def clear_state(self):
"""Clear the recipe state."""
self.state = {}
self.state['steps'] = []
self.state['current_step'] = None
self.state['scope'] = []
self.state['counters'] = {}
self.state['strings'] = {}
for step in self.matchers:
self.state[step] = {}
self.state[step]['pending'] = {}
self.state[step]['actions'] = []
self.state[step]['counters'] = {}
self.state[step]['strings'] = {}
# FIXME rather than boolean should ref HTML tree
self.state[step]['recipe'] = False | python | def clear_state(self):
"""Clear the recipe state."""
self.state = {}
self.state['steps'] = []
self.state['current_step'] = None
self.state['scope'] = []
self.state['counters'] = {}
self.state['strings'] = {}
for step in self.matchers:
self.state[step] = {}
self.state[step]['pending'] = {}
self.state[step]['actions'] = []
self.state[step]['counters'] = {}
self.state[step]['strings'] = {}
# FIXME rather than boolean should ref HTML tree
self.state[step]['recipe'] = False | [
"def",
"clear_state",
"(",
"self",
")",
":",
"self",
".",
"state",
"=",
"{",
"}",
"self",
".",
"state",
"[",
"'steps'",
"]",
"=",
"[",
"]",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"=",
"None",
"self",
".",
"state",
"[",
"'scope'",
"]",
... | Clear the recipe state. | [
"Clear",
"the",
"recipe",
"state",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L160-L175 | train | 39,516 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.record_coverage_zero | def record_coverage_zero(self, rule, offset):
"""Add entry to coverage saying this selector was parsed"""
self.coverage_lines.append('DA:{},0'.format(rule.source_line + offset)) | python | def record_coverage_zero(self, rule, offset):
"""Add entry to coverage saying this selector was parsed"""
self.coverage_lines.append('DA:{},0'.format(rule.source_line + offset)) | [
"def",
"record_coverage_zero",
"(",
"self",
",",
"rule",
",",
"offset",
")",
":",
"self",
".",
"coverage_lines",
".",
"append",
"(",
"'DA:{},0'",
".",
"format",
"(",
"rule",
".",
"source_line",
"+",
"offset",
")",
")"
] | Add entry to coverage saying this selector was parsed | [
"Add",
"entry",
"to",
"coverage",
"saying",
"this",
"selector",
"was",
"parsed"
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L384-L386 | train | 39,517 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.record_coverage | def record_coverage(self, rule):
"""Add entry to coverage saying this selector was matched"""
log(DEBUG, u'Rule ({}): {}'.format(*rule).encode('utf-8'))
self.coverage_lines.append('DA:{},1'.format(rule[0])) | python | def record_coverage(self, rule):
"""Add entry to coverage saying this selector was matched"""
log(DEBUG, u'Rule ({}): {}'.format(*rule).encode('utf-8'))
self.coverage_lines.append('DA:{},1'.format(rule[0])) | [
"def",
"record_coverage",
"(",
"self",
",",
"rule",
")",
":",
"log",
"(",
"DEBUG",
",",
"u'Rule ({}): {}'",
".",
"format",
"(",
"*",
"rule",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"self",
".",
"coverage_lines",
".",
"append",
"(",
"'DA:{},1'",
"... | Add entry to coverage saying this selector was matched | [
"Add",
"entry",
"to",
"coverage",
"saying",
"this",
"selector",
"was",
"matched"
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L388-L391 | train | 39,518 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.push_target_elem | def push_target_elem(self, element, pseudo=None):
"""Place target element onto action stack."""
actions = self.state[self.state['current_step']]['actions']
if len(actions) > 0 and actions[-1][0] == 'target':
actions.pop()
actions.append(('target', Target(element.etree_element,
pseudo, element.parent.etree_element
))) | python | def push_target_elem(self, element, pseudo=None):
"""Place target element onto action stack."""
actions = self.state[self.state['current_step']]['actions']
if len(actions) > 0 and actions[-1][0] == 'target':
actions.pop()
actions.append(('target', Target(element.etree_element,
pseudo, element.parent.etree_element
))) | [
"def",
"push_target_elem",
"(",
"self",
",",
"element",
",",
"pseudo",
"=",
"None",
")",
":",
"actions",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"]",
"[",
"'actions'",
"]",
"if",
"len",
"(",
"actions",
")",
"... | Place target element onto action stack. | [
"Place",
"target",
"element",
"onto",
"action",
"stack",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L580-L587 | train | 39,519 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.push_pending_elem | def push_pending_elem(self, element, pseudo):
"""Create and place pending target element onto stack."""
self.push_target_elem(element, pseudo)
elem = etree.Element('div')
actions = self.state[self.state['current_step']]['actions']
actions.append(('move', elem))
actions.append(('target', Target(elem))) | python | def push_pending_elem(self, element, pseudo):
"""Create and place pending target element onto stack."""
self.push_target_elem(element, pseudo)
elem = etree.Element('div')
actions = self.state[self.state['current_step']]['actions']
actions.append(('move', elem))
actions.append(('target', Target(elem))) | [
"def",
"push_pending_elem",
"(",
"self",
",",
"element",
",",
"pseudo",
")",
":",
"self",
".",
"push_target_elem",
"(",
"element",
",",
"pseudo",
")",
"elem",
"=",
"etree",
".",
"Element",
"(",
"'div'",
")",
"actions",
"=",
"self",
".",
"state",
"[",
"... | Create and place pending target element onto stack. | [
"Create",
"and",
"place",
"pending",
"target",
"element",
"onto",
"stack",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L589-L595 | train | 39,520 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.pop_pending_if_empty | def pop_pending_if_empty(self, element):
"""Remove empty wrapper element."""
actions = self.state[self.state['current_step']]['actions']
elem = self.current_target().tree
if actions[-1][0] == ('target') and actions[-1][1].tree == elem:
actions.pop()
actions.pop()
actions.pop() | python | def pop_pending_if_empty(self, element):
"""Remove empty wrapper element."""
actions = self.state[self.state['current_step']]['actions']
elem = self.current_target().tree
if actions[-1][0] == ('target') and actions[-1][1].tree == elem:
actions.pop()
actions.pop()
actions.pop() | [
"def",
"pop_pending_if_empty",
"(",
"self",
",",
"element",
")",
":",
"actions",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"]",
"[",
"'actions'",
"]",
"elem",
"=",
"self",
".",
"current_target",
"(",
")",
".",
"t... | Remove empty wrapper element. | [
"Remove",
"empty",
"wrapper",
"element",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L597-L604 | train | 39,521 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.current_target | def current_target(self):
"""Return current target."""
actions = self.state[self.state['current_step']]['actions']
for action, value in reversed(actions):
if action == 'target':
return value | python | def current_target(self):
"""Return current target."""
actions = self.state[self.state['current_step']]['actions']
for action, value in reversed(actions):
if action == 'target':
return value | [
"def",
"current_target",
"(",
"self",
")",
":",
"actions",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"]",
"[",
"'actions'",
"]",
"for",
"action",
",",
"value",
"in",
"reversed",
"(",
"actions",
")",
":",
"if",
... | Return current target. | [
"Return",
"current",
"target",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L606-L611 | train | 39,522 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.find_method | def find_method(self, decl):
"""Find class method to call for declaration based on name."""
name = decl.name
method = None
try:
method = getattr(self, u'do_{}'.format(
(name).replace('-', '_')))
except AttributeError:
if name.startswith('data-'):
method = getattr(self, 'do_data_any')
elif name.startswith('attr-'):
method = getattr(self, 'do_attr_any')
else:
log(WARN, u'Missing method {}'.format(
(name).replace('-', '_')).encode('utf-8'))
if method:
self.record_coverage_line(decl.source_line)
return method
else:
return lambda x, y, z: None | python | def find_method(self, decl):
"""Find class method to call for declaration based on name."""
name = decl.name
method = None
try:
method = getattr(self, u'do_{}'.format(
(name).replace('-', '_')))
except AttributeError:
if name.startswith('data-'):
method = getattr(self, 'do_data_any')
elif name.startswith('attr-'):
method = getattr(self, 'do_attr_any')
else:
log(WARN, u'Missing method {}'.format(
(name).replace('-', '_')).encode('utf-8'))
if method:
self.record_coverage_line(decl.source_line)
return method
else:
return lambda x, y, z: None | [
"def",
"find_method",
"(",
"self",
",",
"decl",
")",
":",
"name",
"=",
"decl",
".",
"name",
"method",
"=",
"None",
"try",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"u'do_{}'",
".",
"format",
"(",
"(",
"name",
")",
".",
"replace",
"(",
"'-'",... | Find class method to call for declaration based on name. | [
"Find",
"class",
"method",
"to",
"call",
"for",
"declaration",
"based",
"on",
"name",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L614-L633 | train | 39,523 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.lookup | def lookup(self, vtype, vname, target_id=None):
"""Return value of vname from the variable store vtype.
Valid vtypes are `strings` 'counters', and `pending`. If the value
is not found in the current steps store, earlier steps will be
checked. If not found, '', 0, or (None, None) is returned.
"""
nullvals = {'strings': '', 'counters': 0, 'pending': (None, None)}
nullval = nullvals[vtype]
vstyle = None
if vtype == 'counters':
if len(vname) > 1:
vname, vstyle = vname
else:
vname = vname[0]
if target_id is not None:
try:
state = self.state[vtype][target_id]
steps = self.state[vtype][target_id].keys()
except KeyError:
log(WARN, u'Bad ID target lookup {}'.format(
target_id).encode('utf-8'))
return nullval
else:
state = self.state
steps = self.state['scope']
for step in steps:
if vname in state[step][vtype]:
if vtype == 'pending':
return(state[step][vtype][vname], step)
else:
val = state[step][vtype][vname]
if vstyle is not None:
return self.counter_style(val, vstyle)
return val
else:
return nullval | python | def lookup(self, vtype, vname, target_id=None):
"""Return value of vname from the variable store vtype.
Valid vtypes are `strings` 'counters', and `pending`. If the value
is not found in the current steps store, earlier steps will be
checked. If not found, '', 0, or (None, None) is returned.
"""
nullvals = {'strings': '', 'counters': 0, 'pending': (None, None)}
nullval = nullvals[vtype]
vstyle = None
if vtype == 'counters':
if len(vname) > 1:
vname, vstyle = vname
else:
vname = vname[0]
if target_id is not None:
try:
state = self.state[vtype][target_id]
steps = self.state[vtype][target_id].keys()
except KeyError:
log(WARN, u'Bad ID target lookup {}'.format(
target_id).encode('utf-8'))
return nullval
else:
state = self.state
steps = self.state['scope']
for step in steps:
if vname in state[step][vtype]:
if vtype == 'pending':
return(state[step][vtype][vname], step)
else:
val = state[step][vtype][vname]
if vstyle is not None:
return self.counter_style(val, vstyle)
return val
else:
return nullval | [
"def",
"lookup",
"(",
"self",
",",
"vtype",
",",
"vname",
",",
"target_id",
"=",
"None",
")",
":",
"nullvals",
"=",
"{",
"'strings'",
":",
"''",
",",
"'counters'",
":",
"0",
",",
"'pending'",
":",
"(",
"None",
",",
"None",
")",
"}",
"nullval",
"=",... | Return value of vname from the variable store vtype.
Valid vtypes are `strings` 'counters', and `pending`. If the value
is not found in the current steps store, earlier steps will be
checked. If not found, '', 0, or (None, None) is returned. | [
"Return",
"value",
"of",
"vname",
"from",
"the",
"variable",
"store",
"vtype",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L635-L675 | train | 39,524 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.counter_style | def counter_style(self, val, style):
"""Return counter value in given style."""
if style == 'decimal-leading-zero':
if val < 10:
valstr = "0{}".format(val)
else:
valstr = str(val)
elif style == 'lower-roman':
valstr = _to_roman(val).lower()
elif style == 'upper-roman':
valstr = _to_roman(val)
elif style == 'lower-latin' or style == 'lower-alpha':
if 1 <= val <= 26:
valstr = chr(val + 96)
else:
log(WARN, 'Counter out of range for latin (must be 1...26)')
valstr = str(val)
elif style == 'upper-latin' or style == 'upper-alpha':
if 1 <= val <= 26:
valstr = chr(val + 64)
else:
log(WARN, 'Counter out of range for latin (must be 1...26)')
valstr = str(val)
elif style == 'decimal':
valstr = str(val)
else:
log(WARN, u"ERROR: Counter numbering not supported for"
u" list type {}. Using decimal.".format(
style).encode('utf-8'))
valstr = str(val)
return valstr | python | def counter_style(self, val, style):
"""Return counter value in given style."""
if style == 'decimal-leading-zero':
if val < 10:
valstr = "0{}".format(val)
else:
valstr = str(val)
elif style == 'lower-roman':
valstr = _to_roman(val).lower()
elif style == 'upper-roman':
valstr = _to_roman(val)
elif style == 'lower-latin' or style == 'lower-alpha':
if 1 <= val <= 26:
valstr = chr(val + 96)
else:
log(WARN, 'Counter out of range for latin (must be 1...26)')
valstr = str(val)
elif style == 'upper-latin' or style == 'upper-alpha':
if 1 <= val <= 26:
valstr = chr(val + 64)
else:
log(WARN, 'Counter out of range for latin (must be 1...26)')
valstr = str(val)
elif style == 'decimal':
valstr = str(val)
else:
log(WARN, u"ERROR: Counter numbering not supported for"
u" list type {}. Using decimal.".format(
style).encode('utf-8'))
valstr = str(val)
return valstr | [
"def",
"counter_style",
"(",
"self",
",",
"val",
",",
"style",
")",
":",
"if",
"style",
"==",
"'decimal-leading-zero'",
":",
"if",
"val",
"<",
"10",
":",
"valstr",
"=",
"\"0{}\"",
".",
"format",
"(",
"val",
")",
"else",
":",
"valstr",
"=",
"str",
"("... | Return counter value in given style. | [
"Return",
"counter",
"value",
"in",
"given",
"style",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L677-L707 | train | 39,525 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_counter_reset | def do_counter_reset(self, element, decl, pseudo):
"""Clear specified counters."""
step = self.state[self.state['current_step']]
counter_name = ''
for term in decl.value:
if type(term) is ast.WhitespaceToken:
continue
elif type(term) is ast.IdentToken:
if counter_name:
step['counters'][counter_name] = 0
counter_name = term.value
elif type(term) is ast.LiteralToken:
if counter_name:
step['counters'][counter_name] = 0
counter_name = ''
elif type(term) is ast.NumberToken:
if counter_name:
step['counters'][counter_name] = int(term.value)
counter_name = ''
else:
log(WARN, u"Unrecognized counter-reset term {}"
.format(type(term)).encode('utf-8'))
if counter_name:
step['counters'][counter_name] = 0 | python | def do_counter_reset(self, element, decl, pseudo):
"""Clear specified counters."""
step = self.state[self.state['current_step']]
counter_name = ''
for term in decl.value:
if type(term) is ast.WhitespaceToken:
continue
elif type(term) is ast.IdentToken:
if counter_name:
step['counters'][counter_name] = 0
counter_name = term.value
elif type(term) is ast.LiteralToken:
if counter_name:
step['counters'][counter_name] = 0
counter_name = ''
elif type(term) is ast.NumberToken:
if counter_name:
step['counters'][counter_name] = int(term.value)
counter_name = ''
else:
log(WARN, u"Unrecognized counter-reset term {}"
.format(type(term)).encode('utf-8'))
if counter_name:
step['counters'][counter_name] = 0 | [
"def",
"do_counter_reset",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"step",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"]",
"counter_name",
"=",
"''",
"for",
"term",
"in",
"decl",
".",
... | Clear specified counters. | [
"Clear",
"specified",
"counters",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L936-L963 | train | 39,526 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_node_set | def do_node_set(self, element, decl, pseudo):
"""Implement node-set declaration."""
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
_, valstep = self.lookup('pending', target)
if not valstep:
step['pending'][target] = [('nodeset', elem)]
else:
self.state[valstep]['pending'][target] = [('nodeset', elem)] | python | def do_node_set(self, element, decl, pseudo):
"""Implement node-set declaration."""
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
_, valstep = self.lookup('pending', target)
if not valstep:
step['pending'][target] = [('nodeset', elem)]
else:
self.state[valstep]['pending'][target] = [('nodeset', elem)] | [
"def",
"do_node_set",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"target",
"=",
"serialize",
"(",
"decl",
".",
"value",
")",
".",
"strip",
"(",
")",
"step",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'curren... | Implement node-set declaration. | [
"Implement",
"node",
"-",
"set",
"declaration",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1008-L1017 | train | 39,527 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_move_to | def do_move_to(self, element, decl, pseudo):
"""Implement move-to declaration."""
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
# Find if the current node already has a move, and remove it.
actions = step['actions']
for pos, action in enumerate(reversed(actions)):
if action[0] == 'move' and action[1] == elem:
target_index = - pos - 1
actions[target_index:] = actions[target_index+1:]
break
_, valstep = self.lookup('pending', target)
if not valstep:
step['pending'][target] = [('move', elem)]
else:
self.state[valstep]['pending'][target].append(('move', elem)) | python | def do_move_to(self, element, decl, pseudo):
"""Implement move-to declaration."""
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
# Find if the current node already has a move, and remove it.
actions = step['actions']
for pos, action in enumerate(reversed(actions)):
if action[0] == 'move' and action[1] == elem:
target_index = - pos - 1
actions[target_index:] = actions[target_index+1:]
break
_, valstep = self.lookup('pending', target)
if not valstep:
step['pending'][target] = [('move', elem)]
else:
self.state[valstep]['pending'][target].append(('move', elem)) | [
"def",
"do_move_to",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"target",
"=",
"serialize",
"(",
"decl",
".",
"value",
")",
".",
"strip",
"(",
")",
"step",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current... | Implement move-to declaration. | [
"Implement",
"move",
"-",
"to",
"declaration",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1032-L1050 | train | 39,528 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_container | def do_container(self, element, decl, pseudo):
"""Implement setting tag for new wrapper element."""
value = serialize(decl.value).strip()
if '|' in value:
namespace, tag = value.split('|', 1)
try:
namespace = self.css_namespaces[namespace]
except KeyError:
log(WARN, u'undefined namespace prefix: {}'.format(
namespace).encode('utf-8'))
value = tag
else:
value = etree.QName(namespace, tag)
step = self.state[self.state['current_step']]
actions = step['actions']
actions.append(('tag', value)) | python | def do_container(self, element, decl, pseudo):
"""Implement setting tag for new wrapper element."""
value = serialize(decl.value).strip()
if '|' in value:
namespace, tag = value.split('|', 1)
try:
namespace = self.css_namespaces[namespace]
except KeyError:
log(WARN, u'undefined namespace prefix: {}'.format(
namespace).encode('utf-8'))
value = tag
else:
value = etree.QName(namespace, tag)
step = self.state[self.state['current_step']]
actions = step['actions']
actions.append(('tag', value)) | [
"def",
"do_container",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"value",
"=",
"serialize",
"(",
"decl",
".",
"value",
")",
".",
"strip",
"(",
")",
"if",
"'|'",
"in",
"value",
":",
"namespace",
",",
"tag",
"=",
"value",
"."... | Implement setting tag for new wrapper element. | [
"Implement",
"setting",
"tag",
"for",
"new",
"wrapper",
"element",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1053-L1071 | train | 39,529 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_class | def do_class(self, element, decl, pseudo):
"""Implement class declaration - pre-match."""
step = self.state[self.state['current_step']]
actions = step['actions']
strval = self.eval_string_value(element, decl.value)
actions.append(('attrib', ('class', strval))) | python | def do_class(self, element, decl, pseudo):
"""Implement class declaration - pre-match."""
step = self.state[self.state['current_step']]
actions = step['actions']
strval = self.eval_string_value(element, decl.value)
actions.append(('attrib', ('class', strval))) | [
"def",
"do_class",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"step",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"]",
"actions",
"=",
"step",
"[",
"'actions'",
"]",
"strval",
"=",
"self",... | Implement class declaration - pre-match. | [
"Implement",
"class",
"declaration",
"-",
"pre",
"-",
"match",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1074-L1079 | train | 39,530 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_attr_any | def do_attr_any(self, element, decl, pseudo):
"""Implement generic attribute setting."""
step = self.state[self.state['current_step']]
actions = step['actions']
strval = self.eval_string_value(element, decl.value)
actions.append(('attrib', (decl.name[5:], strval))) | python | def do_attr_any(self, element, decl, pseudo):
"""Implement generic attribute setting."""
step = self.state[self.state['current_step']]
actions = step['actions']
strval = self.eval_string_value(element, decl.value)
actions.append(('attrib', (decl.name[5:], strval))) | [
"def",
"do_attr_any",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"step",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"]",
"actions",
"=",
"step",
"[",
"'actions'",
"]",
"strval",
"=",
"sel... | Implement generic attribute setting. | [
"Implement",
"generic",
"attribute",
"setting",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1082-L1087 | train | 39,531 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_group_by | def do_group_by(self, element, decl, pseudo):
"""Implement group-by declaration - pre-match."""
sort_css = groupby_css = flags = ''
if ',' in decl.value:
if decl.value.count(',') == 2:
sort_css, groupby_css, flags = \
map(serialize, split(decl.value, ','))
else:
sort_css, groupby_css = map(serialize, split(decl.value, ','))
else:
sort_css = serialize(decl.value)
if groupby_css.strip() == 'nocase':
flags = groupby_css
groupby_css = ''
sort = css_to_func(sort_css, flags,
self.css_namespaces, self.state['lang'])
groupby = css_to_func(groupby_css, flags,
self.css_namespaces, self.state['lang'])
step = self.state[self.state['current_step']]
target = self.current_target()
target.sort = sort
target.lang = self.state['lang']
target.isgroup = True
target.groupby = groupby
# Find current target, set its sort/grouping as well
for pos, action in \
enumerate(reversed(step['actions'])):
if action[0] == 'target' and \
action[1].tree == element.etree_element:
action[1].sort = sort
action[1].isgroup = True
action[1].groupby = groupby
break | python | def do_group_by(self, element, decl, pseudo):
"""Implement group-by declaration - pre-match."""
sort_css = groupby_css = flags = ''
if ',' in decl.value:
if decl.value.count(',') == 2:
sort_css, groupby_css, flags = \
map(serialize, split(decl.value, ','))
else:
sort_css, groupby_css = map(serialize, split(decl.value, ','))
else:
sort_css = serialize(decl.value)
if groupby_css.strip() == 'nocase':
flags = groupby_css
groupby_css = ''
sort = css_to_func(sort_css, flags,
self.css_namespaces, self.state['lang'])
groupby = css_to_func(groupby_css, flags,
self.css_namespaces, self.state['lang'])
step = self.state[self.state['current_step']]
target = self.current_target()
target.sort = sort
target.lang = self.state['lang']
target.isgroup = True
target.groupby = groupby
# Find current target, set its sort/grouping as well
for pos, action in \
enumerate(reversed(step['actions'])):
if action[0] == 'target' and \
action[1].tree == element.etree_element:
action[1].sort = sort
action[1].isgroup = True
action[1].groupby = groupby
break | [
"def",
"do_group_by",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"sort_css",
"=",
"groupby_css",
"=",
"flags",
"=",
"''",
"if",
"','",
"in",
"decl",
".",
"value",
":",
"if",
"decl",
".",
"value",
".",
"count",
"(",
"','",
")... | Implement group-by declaration - pre-match. | [
"Implement",
"group",
"-",
"by",
"declaration",
"-",
"pre",
"-",
"match",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1250-L1283 | train | 39,532 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_sort_by | def do_sort_by(self, element, decl, pseudo):
"""Implement sort-by declaration - pre-match."""
if ',' in decl.value:
css, flags = split(decl.value, ',')
else:
css = decl.value
flags = None
sort = css_to_func(serialize(css), serialize(flags or ''),
self.css_namespaces, self.state['lang'])
step = self.state[self.state['current_step']]
target = self.current_target()
target.sort = sort
target.lang = self.state['lang']
target.isgroup = False
target.groupby = None
# Find current target, set its sort as well
for pos, action in \
enumerate(reversed(step['actions'])):
if action[0] == 'target' and \
action[1].tree == element.etree_element:
action[1].sort = sort
action[1].isgroup = False
action[1].groupby = None
break | python | def do_sort_by(self, element, decl, pseudo):
"""Implement sort-by declaration - pre-match."""
if ',' in decl.value:
css, flags = split(decl.value, ',')
else:
css = decl.value
flags = None
sort = css_to_func(serialize(css), serialize(flags or ''),
self.css_namespaces, self.state['lang'])
step = self.state[self.state['current_step']]
target = self.current_target()
target.sort = sort
target.lang = self.state['lang']
target.isgroup = False
target.groupby = None
# Find current target, set its sort as well
for pos, action in \
enumerate(reversed(step['actions'])):
if action[0] == 'target' and \
action[1].tree == element.etree_element:
action[1].sort = sort
action[1].isgroup = False
action[1].groupby = None
break | [
"def",
"do_sort_by",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"if",
"','",
"in",
"decl",
".",
"value",
":",
"css",
",",
"flags",
"=",
"split",
"(",
"decl",
".",
"value",
",",
"','",
")",
"else",
":",
"css",
"=",
"decl",
... | Implement sort-by declaration - pre-match. | [
"Implement",
"sort",
"-",
"by",
"declaration",
"-",
"pre",
"-",
"match",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1286-L1310 | train | 39,533 |
openstax/cnx-easybake | cnxeasybake/oven.py | Oven.do_pass | def do_pass(self, element, decl, pseudo):
"""No longer valid way to set processing pass."""
log(WARN, u"Old-style pass as declaration not allowed.{}"
.format(decl.value).encpde('utf-8')) | python | def do_pass(self, element, decl, pseudo):
"""No longer valid way to set processing pass."""
log(WARN, u"Old-style pass as declaration not allowed.{}"
.format(decl.value).encpde('utf-8')) | [
"def",
"do_pass",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"log",
"(",
"WARN",
",",
"u\"Old-style pass as declaration not allowed.{}\"",
".",
"format",
"(",
"decl",
".",
"value",
")",
".",
"encpde",
"(",
"'utf-8'",
")",
")"
] | No longer valid way to set processing pass. | [
"No",
"longer",
"valid",
"way",
"to",
"set",
"processing",
"pass",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1313-L1316 | train | 39,534 |
dcos/shakedown | shakedown/dcos/command.py | connection_cache | def connection_cache(func: callable):
"""Connection cache for SSH sessions. This is to prevent opening a
new, expensive connection on every command run."""
cache = dict()
lock = RLock()
@wraps(func)
def func_wrapper(host: str, username: str, *args, **kwargs):
key = "{h}-{u}".format(h=host, u=username)
if key in cache:
# connection exists, check if it is still valid before
# returning it.
conn = cache[key]
if conn and conn.is_active() and conn.is_authenticated():
return conn
else:
# try to close a bad connection and remove it from
# the cache.
if conn:
try_close(conn)
del cache[key]
# key is not in the cache, so try to recreate it
# it may have been removed just above.
if key not in cache:
conn = func(host, username, *args, **kwargs)
if conn is not None:
cache[key] = conn
return conn
# not sure how to reach this point, but just in case.
return None
def get_cache() -> dict:
return cache
def purge(key: str=None):
with lock:
if key is None:
conns = [(k, v) for k, v in cache.items()]
elif key in cache:
conns = ((key, cache[key]), )
else:
conns = list()
for k, v in conns:
try_close(v)
del cache[k]
func_wrapper.get_cache = get_cache
func_wrapper.purge = purge
return func_wrapper | python | def connection_cache(func: callable):
"""Connection cache for SSH sessions. This is to prevent opening a
new, expensive connection on every command run."""
cache = dict()
lock = RLock()
@wraps(func)
def func_wrapper(host: str, username: str, *args, **kwargs):
key = "{h}-{u}".format(h=host, u=username)
if key in cache:
# connection exists, check if it is still valid before
# returning it.
conn = cache[key]
if conn and conn.is_active() and conn.is_authenticated():
return conn
else:
# try to close a bad connection and remove it from
# the cache.
if conn:
try_close(conn)
del cache[key]
# key is not in the cache, so try to recreate it
# it may have been removed just above.
if key not in cache:
conn = func(host, username, *args, **kwargs)
if conn is not None:
cache[key] = conn
return conn
# not sure how to reach this point, but just in case.
return None
def get_cache() -> dict:
return cache
def purge(key: str=None):
with lock:
if key is None:
conns = [(k, v) for k, v in cache.items()]
elif key in cache:
conns = ((key, cache[key]), )
else:
conns = list()
for k, v in conns:
try_close(v)
del cache[k]
func_wrapper.get_cache = get_cache
func_wrapper.purge = purge
return func_wrapper | [
"def",
"connection_cache",
"(",
"func",
":",
"callable",
")",
":",
"cache",
"=",
"dict",
"(",
")",
"lock",
"=",
"RLock",
"(",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"host",
":",
"str",
",",
"username",
":",
"str",
",",
"*"... | Connection cache for SSH sessions. This is to prevent opening a
new, expensive connection on every command run. | [
"Connection",
"cache",
"for",
"SSH",
"sessions",
".",
"This",
"is",
"to",
"prevent",
"opening",
"a",
"new",
"expensive",
"connection",
"on",
"every",
"command",
"run",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/command.py#L15-L66 | train | 39,535 |
dcos/shakedown | shakedown/dcos/command.py | _get_connection | def _get_connection(host, username: str, key_path: str) \
-> paramiko.Transport or None:
"""Return an authenticated SSH connection.
:param host: host or IP of the machine
:type host: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key for SSH auth
:type key_path: str
:return: SSH connection
:rtype: paramiko.Transport or None
"""
if not username:
username = shakedown.cli.ssh_user
if not key_path:
key_path = shakedown.cli.ssh_key_file
key = validate_key(key_path)
transport = get_transport(host, username, key)
if transport:
transport = start_transport(transport, username, key)
if transport.is_authenticated():
return transport
else:
print("error: unable to authenticate {}@{} with key {}".format(username, host, key_path))
else:
print("error: unable to connect to {}".format(host))
return None | python | def _get_connection(host, username: str, key_path: str) \
-> paramiko.Transport or None:
"""Return an authenticated SSH connection.
:param host: host or IP of the machine
:type host: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key for SSH auth
:type key_path: str
:return: SSH connection
:rtype: paramiko.Transport or None
"""
if not username:
username = shakedown.cli.ssh_user
if not key_path:
key_path = shakedown.cli.ssh_key_file
key = validate_key(key_path)
transport = get_transport(host, username, key)
if transport:
transport = start_transport(transport, username, key)
if transport.is_authenticated():
return transport
else:
print("error: unable to authenticate {}@{} with key {}".format(username, host, key_path))
else:
print("error: unable to connect to {}".format(host))
return None | [
"def",
"_get_connection",
"(",
"host",
",",
"username",
":",
"str",
",",
"key_path",
":",
"str",
")",
"->",
"paramiko",
".",
"Transport",
"or",
"None",
":",
"if",
"not",
"username",
":",
"username",
"=",
"shakedown",
".",
"cli",
".",
"ssh_user",
"if",
... | Return an authenticated SSH connection.
:param host: host or IP of the machine
:type host: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key for SSH auth
:type key_path: str
:return: SSH connection
:rtype: paramiko.Transport or None | [
"Return",
"an",
"authenticated",
"SSH",
"connection",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/command.py#L70-L99 | train | 39,536 |
dcos/shakedown | shakedown/dcos/command.py | run_command | def run_command(
host,
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command via SSH, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param command: the command to execute
:type command: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key to use for SSH authentication
:type key_path: str
:return: True if successful, False otherwise
:rtype: bool
:return: Output of command
:rtype: string
"""
with HostSession(host, username, key_path, noisy) as s:
if noisy:
print("\n{}{} $ {}\n".format(shakedown.fchr('>>'), host, command))
s.run(command)
ec, output = s.get_result()
return ec == 0, output | python | def run_command(
host,
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command via SSH, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param command: the command to execute
:type command: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key to use for SSH authentication
:type key_path: str
:return: True if successful, False otherwise
:rtype: bool
:return: Output of command
:rtype: string
"""
with HostSession(host, username, key_path, noisy) as s:
if noisy:
print("\n{}{} $ {}\n".format(shakedown.fchr('>>'), host, command))
s.run(command)
ec, output = s.get_result()
return ec == 0, output | [
"def",
"run_command",
"(",
"host",
",",
"command",
",",
"username",
"=",
"None",
",",
"key_path",
"=",
"None",
",",
"noisy",
"=",
"True",
")",
":",
"with",
"HostSession",
"(",
"host",
",",
"username",
",",
"key_path",
",",
"noisy",
")",
"as",
"s",
":... | Run a command via SSH, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param command: the command to execute
:type command: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key to use for SSH authentication
:type key_path: str
:return: True if successful, False otherwise
:rtype: bool
:return: Output of command
:rtype: string | [
"Run",
"a",
"command",
"via",
"SSH",
"proxied",
"through",
"the",
"mesos",
"master"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/command.py#L102-L131 | train | 39,537 |
dcos/shakedown | shakedown/dcos/command.py | run_command_on_master | def run_command_on_master(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Mesos master
"""
return run_command(shakedown.master_ip(), command, username, key_path, noisy) | python | def run_command_on_master(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Mesos master
"""
return run_command(shakedown.master_ip(), command, username, key_path, noisy) | [
"def",
"run_command_on_master",
"(",
"command",
",",
"username",
"=",
"None",
",",
"key_path",
"=",
"None",
",",
"noisy",
"=",
"True",
")",
":",
"return",
"run_command",
"(",
"shakedown",
".",
"master_ip",
"(",
")",
",",
"command",
",",
"username",
",",
... | Run a command on the Mesos master | [
"Run",
"a",
"command",
"on",
"the",
"Mesos",
"master"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/command.py#L134-L143 | train | 39,538 |
dcos/shakedown | shakedown/dcos/command.py | run_command_on_leader | def run_command_on_leader(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Mesos leader. Important for Multi-Master.
"""
return run_command(shakedown.master_leader_ip(), command, username, key_path, noisy) | python | def run_command_on_leader(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Mesos leader. Important for Multi-Master.
"""
return run_command(shakedown.master_leader_ip(), command, username, key_path, noisy) | [
"def",
"run_command_on_leader",
"(",
"command",
",",
"username",
"=",
"None",
",",
"key_path",
"=",
"None",
",",
"noisy",
"=",
"True",
")",
":",
"return",
"run_command",
"(",
"shakedown",
".",
"master_leader_ip",
"(",
")",
",",
"command",
",",
"username",
... | Run a command on the Mesos leader. Important for Multi-Master. | [
"Run",
"a",
"command",
"on",
"the",
"Mesos",
"leader",
".",
"Important",
"for",
"Multi",
"-",
"Master",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/command.py#L146-L155 | train | 39,539 |
dcos/shakedown | shakedown/dcos/command.py | run_command_on_marathon_leader | def run_command_on_marathon_leader(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Marathon leader
"""
return run_command(shakedown.marathon_leader_ip(), command, username, key_path, noisy) | python | def run_command_on_marathon_leader(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Marathon leader
"""
return run_command(shakedown.marathon_leader_ip(), command, username, key_path, noisy) | [
"def",
"run_command_on_marathon_leader",
"(",
"command",
",",
"username",
"=",
"None",
",",
"key_path",
"=",
"None",
",",
"noisy",
"=",
"True",
")",
":",
"return",
"run_command",
"(",
"shakedown",
".",
"marathon_leader_ip",
"(",
")",
",",
"command",
",",
"us... | Run a command on the Marathon leader | [
"Run",
"a",
"command",
"on",
"the",
"Marathon",
"leader"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/command.py#L158-L167 | train | 39,540 |
dcos/shakedown | shakedown/dcos/command.py | run_command_on_agent | def run_command_on_agent(
host,
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on a Mesos agent, proxied through the master
"""
return run_command(host, command, username, key_path, noisy) | python | def run_command_on_agent(
host,
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on a Mesos agent, proxied through the master
"""
return run_command(host, command, username, key_path, noisy) | [
"def",
"run_command_on_agent",
"(",
"host",
",",
"command",
",",
"username",
"=",
"None",
",",
"key_path",
"=",
"None",
",",
"noisy",
"=",
"True",
")",
":",
"return",
"run_command",
"(",
"host",
",",
"command",
",",
"username",
",",
"key_path",
",",
"noi... | Run a command on a Mesos agent, proxied through the master | [
"Run",
"a",
"command",
"on",
"a",
"Mesos",
"agent",
"proxied",
"through",
"the",
"master"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/command.py#L170-L180 | train | 39,541 |
dcos/shakedown | shakedown/dcos/master.py | get_all_masters | def get_all_masters():
""" Returns the json object that represents each of the masters.
"""
masters = []
for master in __master_zk_nodes_keys():
master_zk_str = get_zk_node_data(master)['str']
masters.append(json.loads(master_zk_str))
return masters | python | def get_all_masters():
""" Returns the json object that represents each of the masters.
"""
masters = []
for master in __master_zk_nodes_keys():
master_zk_str = get_zk_node_data(master)['str']
masters.append(json.loads(master_zk_str))
return masters | [
"def",
"get_all_masters",
"(",
")",
":",
"masters",
"=",
"[",
"]",
"for",
"master",
"in",
"__master_zk_nodes_keys",
"(",
")",
":",
"master_zk_str",
"=",
"get_zk_node_data",
"(",
"master",
")",
"[",
"'str'",
"]",
"masters",
".",
"append",
"(",
"json",
".",
... | Returns the json object that represents each of the masters. | [
"Returns",
"the",
"json",
"object",
"that",
"represents",
"each",
"of",
"the",
"masters",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/master.py#L93-L101 | train | 39,542 |
dcos/shakedown | shakedown/dcos/agent.py | get_public_agents_public_ip | def get_public_agents_public_ip():
"""Provides a list public IPs for public agents in the cluster"""
public_ip_list = []
agents = get_public_agents()
for agent in agents:
status, public_ip = shakedown.run_command_on_agent(agent, "/opt/mesosphere/bin/detect_ip_public")
public_ip_list.append(public_ip)
return public_ip_list | python | def get_public_agents_public_ip():
"""Provides a list public IPs for public agents in the cluster"""
public_ip_list = []
agents = get_public_agents()
for agent in agents:
status, public_ip = shakedown.run_command_on_agent(agent, "/opt/mesosphere/bin/detect_ip_public")
public_ip_list.append(public_ip)
return public_ip_list | [
"def",
"get_public_agents_public_ip",
"(",
")",
":",
"public_ip_list",
"=",
"[",
"]",
"agents",
"=",
"get_public_agents",
"(",
")",
"for",
"agent",
"in",
"agents",
":",
"status",
",",
"public_ip",
"=",
"shakedown",
".",
"run_command_on_agent",
"(",
"agent",
",... | Provides a list public IPs for public agents in the cluster | [
"Provides",
"a",
"list",
"public",
"IPs",
"for",
"public",
"agents",
"in",
"the",
"cluster"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/agent.py#L11-L19 | train | 39,543 |
dcos/shakedown | shakedown/dcos/agent.py | partition_agent | def partition_agent(host):
""" Partition a node from all network traffic except for SSH and loopback
:param hostname: host or IP of the machine to partition from the cluster
"""
network.save_iptables(host)
network.flush_all_rules(host)
network.allow_all_traffic(host)
network.run_iptables(host, ALLOW_SSH)
network.run_iptables(host, ALLOW_PING)
network.run_iptables(host, DISALLOW_MESOS)
network.run_iptables(host, DISALLOW_INPUT) | python | def partition_agent(host):
""" Partition a node from all network traffic except for SSH and loopback
:param hostname: host or IP of the machine to partition from the cluster
"""
network.save_iptables(host)
network.flush_all_rules(host)
network.allow_all_traffic(host)
network.run_iptables(host, ALLOW_SSH)
network.run_iptables(host, ALLOW_PING)
network.run_iptables(host, DISALLOW_MESOS)
network.run_iptables(host, DISALLOW_INPUT) | [
"def",
"partition_agent",
"(",
"host",
")",
":",
"network",
".",
"save_iptables",
"(",
"host",
")",
"network",
".",
"flush_all_rules",
"(",
"host",
")",
"network",
".",
"allow_all_traffic",
"(",
"host",
")",
"network",
".",
"run_iptables",
"(",
"host",
",",
... | Partition a node from all network traffic except for SSH and loopback
:param hostname: host or IP of the machine to partition from the cluster | [
"Partition",
"a",
"node",
"from",
"all",
"network",
"traffic",
"except",
"for",
"SSH",
"and",
"loopback"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/agent.py#L78-L90 | train | 39,544 |
dcos/shakedown | shakedown/dcos/agent.py | kill_process_on_host | def kill_process_on_host(
hostname,
pattern
):
""" Kill the process matching pattern at ip
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pattern: a regular expression matching the name of the process to kill
"""
status, stdout = run_command_on_agent(hostname, "ps aux | grep -v grep | grep '{}'".format(pattern))
pids = [p.strip().split()[1] for p in stdout.splitlines()]
for pid in pids:
status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
if status:
print("Killed pid: {}".format(pid))
else:
print("Unable to killed pid: {}".format(pid)) | python | def kill_process_on_host(
hostname,
pattern
):
""" Kill the process matching pattern at ip
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pattern: a regular expression matching the name of the process to kill
"""
status, stdout = run_command_on_agent(hostname, "ps aux | grep -v grep | grep '{}'".format(pattern))
pids = [p.strip().split()[1] for p in stdout.splitlines()]
for pid in pids:
status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
if status:
print("Killed pid: {}".format(pid))
else:
print("Unable to killed pid: {}".format(pid)) | [
"def",
"kill_process_on_host",
"(",
"hostname",
",",
"pattern",
")",
":",
"status",
",",
"stdout",
"=",
"run_command_on_agent",
"(",
"hostname",
",",
"\"ps aux | grep -v grep | grep '{}'\"",
".",
"format",
"(",
"pattern",
")",
")",
"pids",
"=",
"[",
"p",
".",
... | Kill the process matching pattern at ip
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pattern: a regular expression matching the name of the process to kill | [
"Kill",
"the",
"process",
"matching",
"pattern",
"at",
"ip"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/agent.py#L113-L131 | train | 39,545 |
dcos/shakedown | shakedown/dcos/agent.py | kill_process_from_pid_file_on_host | def kill_process_from_pid_file_on_host(hostname, pid_file='app.pid'):
""" Retrieves the PID of a process from a pid file on host and kills it.
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pid_file: pid file to use holding the pid number to kill
"""
status, pid = run_command_on_agent(hostname, 'cat {}'.format(pid_file))
status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
if status:
print("Killed pid: {}".format(pid))
run_command_on_agent(hostname, 'rm {}'.format(pid_file))
else:
print("Unable to killed pid: {}".format(pid)) | python | def kill_process_from_pid_file_on_host(hostname, pid_file='app.pid'):
""" Retrieves the PID of a process from a pid file on host and kills it.
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pid_file: pid file to use holding the pid number to kill
"""
status, pid = run_command_on_agent(hostname, 'cat {}'.format(pid_file))
status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
if status:
print("Killed pid: {}".format(pid))
run_command_on_agent(hostname, 'rm {}'.format(pid_file))
else:
print("Unable to killed pid: {}".format(pid)) | [
"def",
"kill_process_from_pid_file_on_host",
"(",
"hostname",
",",
"pid_file",
"=",
"'app.pid'",
")",
":",
"status",
",",
"pid",
"=",
"run_command_on_agent",
"(",
"hostname",
",",
"'cat {}'",
".",
"format",
"(",
"pid_file",
")",
")",
"status",
",",
"stdout",
"... | Retrieves the PID of a process from a pid file on host and kills it.
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pid_file: pid file to use holding the pid number to kill | [
"Retrieves",
"the",
"PID",
"of",
"a",
"process",
"from",
"a",
"pid",
"file",
"on",
"host",
"and",
"kills",
"it",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/agent.py#L134-L146 | train | 39,546 |
dcos/shakedown | shakedown/dcos/spinner.py | wait_for | def wait_for(
predicate,
timeout_seconds=120,
sleep_seconds=1,
ignore_exceptions=True,
inverse_predicate=False,
noisy=False,
required_consecutive_success_count=1):
""" waits or spins for a predicate, returning the result.
Predicate is a function that returns a truthy or falsy value.
An exception in the function will be returned.
A timeout will throw a TimeoutExpired Exception.
"""
count = 0
start_time = time_module.time()
timeout = Deadline.create_deadline(timeout_seconds)
while True:
try:
result = predicate()
except Exception as e:
if ignore_exceptions:
if noisy:
logger.exception("Ignoring error during wait.")
else:
count = 0
raise # preserve original stack
else:
if (not inverse_predicate and result) or (inverse_predicate and not result):
count = count + 1
if count >= required_consecutive_success_count:
return result
if timeout.is_expired():
funname = __stringify_predicate(predicate)
raise TimeoutExpired(timeout_seconds, funname)
if noisy:
header = '{}[{}/{}]'.format(
shakedown.cli.helpers.fchr('>>'),
pretty_duration(time_module.time() - start_time),
pretty_duration(timeout_seconds)
)
if required_consecutive_success_count > 1:
header = '{} [{} of {} times]'.format(
header,
count,
required_consecutive_success_count)
print('{} spinning...'.format(header))
time_module.sleep(sleep_seconds) | python | def wait_for(
predicate,
timeout_seconds=120,
sleep_seconds=1,
ignore_exceptions=True,
inverse_predicate=False,
noisy=False,
required_consecutive_success_count=1):
""" waits or spins for a predicate, returning the result.
Predicate is a function that returns a truthy or falsy value.
An exception in the function will be returned.
A timeout will throw a TimeoutExpired Exception.
"""
count = 0
start_time = time_module.time()
timeout = Deadline.create_deadline(timeout_seconds)
while True:
try:
result = predicate()
except Exception as e:
if ignore_exceptions:
if noisy:
logger.exception("Ignoring error during wait.")
else:
count = 0
raise # preserve original stack
else:
if (not inverse_predicate and result) or (inverse_predicate and not result):
count = count + 1
if count >= required_consecutive_success_count:
return result
if timeout.is_expired():
funname = __stringify_predicate(predicate)
raise TimeoutExpired(timeout_seconds, funname)
if noisy:
header = '{}[{}/{}]'.format(
shakedown.cli.helpers.fchr('>>'),
pretty_duration(time_module.time() - start_time),
pretty_duration(timeout_seconds)
)
if required_consecutive_success_count > 1:
header = '{} [{} of {} times]'.format(
header,
count,
required_consecutive_success_count)
print('{} spinning...'.format(header))
time_module.sleep(sleep_seconds) | [
"def",
"wait_for",
"(",
"predicate",
",",
"timeout_seconds",
"=",
"120",
",",
"sleep_seconds",
"=",
"1",
",",
"ignore_exceptions",
"=",
"True",
",",
"inverse_predicate",
"=",
"False",
",",
"noisy",
"=",
"False",
",",
"required_consecutive_success_count",
"=",
"1... | waits or spins for a predicate, returning the result.
Predicate is a function that returns a truthy or falsy value.
An exception in the function will be returned.
A timeout will throw a TimeoutExpired Exception. | [
"waits",
"or",
"spins",
"for",
"a",
"predicate",
"returning",
"the",
"result",
".",
"Predicate",
"is",
"a",
"function",
"that",
"returns",
"a",
"truthy",
"or",
"falsy",
"value",
".",
"An",
"exception",
"in",
"the",
"function",
"will",
"be",
"returned",
"."... | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/spinner.py#L12-L60 | train | 39,547 |
dcos/shakedown | shakedown/dcos/spinner.py | __stringify_predicate | def __stringify_predicate(predicate):
""" Reflection of function name and parameters of the predicate being used.
"""
funname = getsource(predicate).strip().split(' ')[2].rstrip(',')
params = 'None'
# if args dig in the stack
if '()' not in funname:
stack = getouterframes(currentframe())
for frame in range(0, len(stack)):
if funname in str(stack[frame]):
_, _, _, params = getargvalues(stack[frame][0])
return "function: {} params: {}".format(funname, params) | python | def __stringify_predicate(predicate):
""" Reflection of function name and parameters of the predicate being used.
"""
funname = getsource(predicate).strip().split(' ')[2].rstrip(',')
params = 'None'
# if args dig in the stack
if '()' not in funname:
stack = getouterframes(currentframe())
for frame in range(0, len(stack)):
if funname in str(stack[frame]):
_, _, _, params = getargvalues(stack[frame][0])
return "function: {} params: {}".format(funname, params) | [
"def",
"__stringify_predicate",
"(",
"predicate",
")",
":",
"funname",
"=",
"getsource",
"(",
"predicate",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"[",
"2",
"]",
".",
"rstrip",
"(",
"','",
")",
"params",
"=",
"'None'",
"# if args di... | Reflection of function name and parameters of the predicate being used. | [
"Reflection",
"of",
"function",
"name",
"and",
"parameters",
"of",
"the",
"predicate",
"being",
"used",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/spinner.py#L63-L76 | train | 39,548 |
dcos/shakedown | shakedown/dcos/spinner.py | time_wait | def time_wait(
predicate,
timeout_seconds=120,
sleep_seconds=1,
ignore_exceptions=True,
inverse_predicate=False,
noisy=True,
required_consecutive_success_count=1):
""" waits or spins for a predicate and returns the time of the wait.
An exception in the function will be returned.
A timeout will throw a TimeoutExpired Exception.
"""
start = time_module.time()
wait_for(predicate, timeout_seconds, sleep_seconds, ignore_exceptions, inverse_predicate, noisy, required_consecutive_success_count)
return elapse_time(start) | python | def time_wait(
predicate,
timeout_seconds=120,
sleep_seconds=1,
ignore_exceptions=True,
inverse_predicate=False,
noisy=True,
required_consecutive_success_count=1):
""" waits or spins for a predicate and returns the time of the wait.
An exception in the function will be returned.
A timeout will throw a TimeoutExpired Exception.
"""
start = time_module.time()
wait_for(predicate, timeout_seconds, sleep_seconds, ignore_exceptions, inverse_predicate, noisy, required_consecutive_success_count)
return elapse_time(start) | [
"def",
"time_wait",
"(",
"predicate",
",",
"timeout_seconds",
"=",
"120",
",",
"sleep_seconds",
"=",
"1",
",",
"ignore_exceptions",
"=",
"True",
",",
"inverse_predicate",
"=",
"False",
",",
"noisy",
"=",
"True",
",",
"required_consecutive_success_count",
"=",
"1... | waits or spins for a predicate and returns the time of the wait.
An exception in the function will be returned.
A timeout will throw a TimeoutExpired Exception. | [
"waits",
"or",
"spins",
"for",
"a",
"predicate",
"and",
"returns",
"the",
"time",
"of",
"the",
"wait",
".",
"An",
"exception",
"in",
"the",
"function",
"will",
"be",
"returned",
".",
"A",
"timeout",
"will",
"throw",
"a",
"TimeoutExpired",
"Exception",
"."
... | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/spinner.py#L79-L94 | train | 39,549 |
dcos/shakedown | shakedown/dcos/spinner.py | wait_while_exceptions | def wait_while_exceptions(
predicate,
timeout_seconds=120,
sleep_seconds=1,
noisy=False):
""" waits for a predicate, ignoring exceptions, returning the result.
Predicate is a function.
Exceptions will trigger the sleep and retry; any non-exception result
will be returned.
A timeout will throw a TimeoutExpired Exception.
"""
start_time = time_module.time()
timeout = Deadline.create_deadline(timeout_seconds)
while True:
try:
result = predicate()
return result
except Exception as e:
if noisy:
logger.exception("Ignoring error during wait.")
if timeout.is_expired():
funname = __stringify_predicate(predicate)
raise TimeoutExpired(timeout_seconds, funname)
if noisy:
header = '{}[{}/{}]'.format(
shakedown.cli.helpers.fchr('>>'),
pretty_duration(time_module.time() - start_time),
pretty_duration(timeout_seconds)
)
print('{} spinning...'.format(header))
time_module.sleep(sleep_seconds) | python | def wait_while_exceptions(
predicate,
timeout_seconds=120,
sleep_seconds=1,
noisy=False):
""" waits for a predicate, ignoring exceptions, returning the result.
Predicate is a function.
Exceptions will trigger the sleep and retry; any non-exception result
will be returned.
A timeout will throw a TimeoutExpired Exception.
"""
start_time = time_module.time()
timeout = Deadline.create_deadline(timeout_seconds)
while True:
try:
result = predicate()
return result
except Exception as e:
if noisy:
logger.exception("Ignoring error during wait.")
if timeout.is_expired():
funname = __stringify_predicate(predicate)
raise TimeoutExpired(timeout_seconds, funname)
if noisy:
header = '{}[{}/{}]'.format(
shakedown.cli.helpers.fchr('>>'),
pretty_duration(time_module.time() - start_time),
pretty_duration(timeout_seconds)
)
print('{} spinning...'.format(header))
time_module.sleep(sleep_seconds) | [
"def",
"wait_while_exceptions",
"(",
"predicate",
",",
"timeout_seconds",
"=",
"120",
",",
"sleep_seconds",
"=",
"1",
",",
"noisy",
"=",
"False",
")",
":",
"start_time",
"=",
"time_module",
".",
"time",
"(",
")",
"timeout",
"=",
"Deadline",
".",
"create_dead... | waits for a predicate, ignoring exceptions, returning the result.
Predicate is a function.
Exceptions will trigger the sleep and retry; any non-exception result
will be returned.
A timeout will throw a TimeoutExpired Exception. | [
"waits",
"for",
"a",
"predicate",
"ignoring",
"exceptions",
"returning",
"the",
"result",
".",
"Predicate",
"is",
"a",
"function",
".",
"Exceptions",
"will",
"trigger",
"the",
"sleep",
"and",
"retry",
";",
"any",
"non",
"-",
"exception",
"result",
"will",
"b... | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/spinner.py#L97-L128 | train | 39,550 |
dcos/shakedown | shakedown/dcos/spinner.py | elapse_time | def elapse_time(start, end=None, precision=3):
""" Simple time calculation utility. Given a start time, it will provide an elapse time.
"""
if end is None:
end = time_module.time()
return round(end-start, precision) | python | def elapse_time(start, end=None, precision=3):
""" Simple time calculation utility. Given a start time, it will provide an elapse time.
"""
if end is None:
end = time_module.time()
return round(end-start, precision) | [
"def",
"elapse_time",
"(",
"start",
",",
"end",
"=",
"None",
",",
"precision",
"=",
"3",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"time_module",
".",
"time",
"(",
")",
"return",
"round",
"(",
"end",
"-",
"start",
",",
"precision",
")"
... | Simple time calculation utility. Given a start time, it will provide an elapse time. | [
"Simple",
"time",
"calculation",
"utility",
".",
"Given",
"a",
"start",
"time",
"it",
"will",
"provide",
"an",
"elapse",
"time",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/spinner.py#L131-L136 | train | 39,551 |
dcos/shakedown | shakedown/cli/helpers.py | set_config_defaults | def set_config_defaults(args):
""" Set configuration defaults
:param args: a dict of arguments
:type args: dict
:return: a dict of arguments
:rtype: dict
"""
defaults = {
'fail': 'fast',
'stdout': 'fail'
}
for key in defaults:
if not args[key]:
args[key] = defaults[key]
return args | python | def set_config_defaults(args):
""" Set configuration defaults
:param args: a dict of arguments
:type args: dict
:return: a dict of arguments
:rtype: dict
"""
defaults = {
'fail': 'fast',
'stdout': 'fail'
}
for key in defaults:
if not args[key]:
args[key] = defaults[key]
return args | [
"def",
"set_config_defaults",
"(",
"args",
")",
":",
"defaults",
"=",
"{",
"'fail'",
":",
"'fast'",
",",
"'stdout'",
":",
"'fail'",
"}",
"for",
"key",
"in",
"defaults",
":",
"if",
"not",
"args",
"[",
"key",
"]",
":",
"args",
"[",
"key",
"]",
"=",
"... | Set configuration defaults
:param args: a dict of arguments
:type args: dict
:return: a dict of arguments
:rtype: dict | [
"Set",
"configuration",
"defaults"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/cli/helpers.py#L35-L54 | train | 39,552 |
dcos/shakedown | shakedown/cli/helpers.py | banner | def banner():
""" Display a product banner
:return: a delightful Mesosphere logo rendered in unicode
:rtype: str
"""
banner_dict = {
'a0': click.style(chr(9601), fg='magenta'),
'a1': click.style(chr(9601), fg='magenta', bold=True),
'b0': click.style(chr(9616), fg='magenta'),
'c0': click.style(chr(9626), fg='magenta'),
'c1': click.style(chr(9626), fg='magenta', bold=True),
'd0': click.style(chr(9622), fg='magenta'),
'd1': click.style(chr(9622), fg='magenta', bold=True),
'e0': click.style(chr(9623), fg='magenta'),
'e1': click.style(chr(9623), fg='magenta', bold=True),
'f0': click.style(chr(9630), fg='magenta'),
'f1': click.style(chr(9630), fg='magenta', bold=True),
'g1': click.style(chr(9612), fg='magenta', bold=True),
'h0': click.style(chr(9624), fg='magenta'),
'h1': click.style(chr(9624), fg='magenta', bold=True),
'i0': click.style(chr(9629), fg='magenta'),
'i1': click.style(chr(9629), fg='magenta', bold=True),
'j0': click.style(fchr('>>'), fg='magenta'),
'k0': click.style(chr(9473), fg='magenta'),
'l0': click.style('_', fg='magenta'),
'l1': click.style('_', fg='magenta', bold=True),
'v0': click.style('mesosphere', fg='magenta'),
'x1': click.style('shakedown', fg='magenta', bold=True),
'y0': click.style('v' + shakedown.VERSION, fg='magenta'),
'z0': chr(32)
}
banner_map = [
" %(z0)s%(z0)s%(l0)s%(l0)s%(l1)s%(l0)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s",
" %(z0)s%(b0)s%(z0)s%(c0)s%(z0)s%(d0)s%(z0)s%(z0)s%(z0)s%(z0)s%(e1)s%(z0)s%(f1)s%(z0)s%(g1)s",
" %(z0)s%(b0)s%(z0)s%(z0)s%(c0)s%(z0)s%(h0)s%(e0)s%(d1)s%(i1)s%(z0)s%(f1)s%(z0)s%(z0)s%(g1)s%(z0)s%(j0)s%(v0)s %(x1)s %(y0)s",
" %(z0)s%(b0)s%(z0)s%(z0)s%(f0)s%(c0)s%(i0)s%(z0)s%(z0)s%(h1)s%(f1)s%(c1)s%(z0)s%(z0)s%(g1)s%(z0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(z0)s%(k0)s%(k0)s%(z0)s%(z0)s%(k0)s",
" %(z0)s%(i0)s%(f0)s%(h0)s%(z0)s%(z0)s%(c0)s%(z0)s%(z0)s%(f0)s%(z0)s%(z0)s%(i1)s%(c1)s%(h1)s",
" %(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(c0)s%(f0)s",
]
if 'TERM' in os.environ and os.environ['TERM'] in ('velocity', 'xterm', 'xterm-256color', 'xterm-color'):
return echo("\n".join(banner_map) % banner_dict)
else:
return echo(fchr('>>') + 'mesosphere shakedown v' + shakedown.VERSION, b=True) | python | def banner():
""" Display a product banner
:return: a delightful Mesosphere logo rendered in unicode
:rtype: str
"""
banner_dict = {
'a0': click.style(chr(9601), fg='magenta'),
'a1': click.style(chr(9601), fg='magenta', bold=True),
'b0': click.style(chr(9616), fg='magenta'),
'c0': click.style(chr(9626), fg='magenta'),
'c1': click.style(chr(9626), fg='magenta', bold=True),
'd0': click.style(chr(9622), fg='magenta'),
'd1': click.style(chr(9622), fg='magenta', bold=True),
'e0': click.style(chr(9623), fg='magenta'),
'e1': click.style(chr(9623), fg='magenta', bold=True),
'f0': click.style(chr(9630), fg='magenta'),
'f1': click.style(chr(9630), fg='magenta', bold=True),
'g1': click.style(chr(9612), fg='magenta', bold=True),
'h0': click.style(chr(9624), fg='magenta'),
'h1': click.style(chr(9624), fg='magenta', bold=True),
'i0': click.style(chr(9629), fg='magenta'),
'i1': click.style(chr(9629), fg='magenta', bold=True),
'j0': click.style(fchr('>>'), fg='magenta'),
'k0': click.style(chr(9473), fg='magenta'),
'l0': click.style('_', fg='magenta'),
'l1': click.style('_', fg='magenta', bold=True),
'v0': click.style('mesosphere', fg='magenta'),
'x1': click.style('shakedown', fg='magenta', bold=True),
'y0': click.style('v' + shakedown.VERSION, fg='magenta'),
'z0': chr(32)
}
banner_map = [
" %(z0)s%(z0)s%(l0)s%(l0)s%(l1)s%(l0)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s",
" %(z0)s%(b0)s%(z0)s%(c0)s%(z0)s%(d0)s%(z0)s%(z0)s%(z0)s%(z0)s%(e1)s%(z0)s%(f1)s%(z0)s%(g1)s",
" %(z0)s%(b0)s%(z0)s%(z0)s%(c0)s%(z0)s%(h0)s%(e0)s%(d1)s%(i1)s%(z0)s%(f1)s%(z0)s%(z0)s%(g1)s%(z0)s%(j0)s%(v0)s %(x1)s %(y0)s",
" %(z0)s%(b0)s%(z0)s%(z0)s%(f0)s%(c0)s%(i0)s%(z0)s%(z0)s%(h1)s%(f1)s%(c1)s%(z0)s%(z0)s%(g1)s%(z0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(z0)s%(k0)s%(k0)s%(z0)s%(z0)s%(k0)s",
" %(z0)s%(i0)s%(f0)s%(h0)s%(z0)s%(z0)s%(c0)s%(z0)s%(z0)s%(f0)s%(z0)s%(z0)s%(i1)s%(c1)s%(h1)s",
" %(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(c0)s%(f0)s",
]
if 'TERM' in os.environ and os.environ['TERM'] in ('velocity', 'xterm', 'xterm-256color', 'xterm-color'):
return echo("\n".join(banner_map) % banner_dict)
else:
return echo(fchr('>>') + 'mesosphere shakedown v' + shakedown.VERSION, b=True) | [
"def",
"banner",
"(",
")",
":",
"banner_dict",
"=",
"{",
"'a0'",
":",
"click",
".",
"style",
"(",
"chr",
"(",
"9601",
")",
",",
"fg",
"=",
"'magenta'",
")",
",",
"'a1'",
":",
"click",
".",
"style",
"(",
"chr",
"(",
"9601",
")",
",",
"fg",
"=",
... | Display a product banner
:return: a delightful Mesosphere logo rendered in unicode
:rtype: str | [
"Display",
"a",
"product",
"banner"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/cli/helpers.py#L75-L121 | train | 39,553 |
dcos/shakedown | shakedown/cli/helpers.py | decorate | def decorate(text, style):
""" Console decoration style definitions
:param text: the text string to decorate
:type text: str
:param style: the style used to decorate the string
:type style: str
:return: a decorated string
:rtype: str
"""
return {
'step-maj': click.style("\n" + '> ' + text, fg='yellow', bold=True),
'step-min': click.style(' - ' + text + ' ', bold=True),
'item-maj': click.style(' - ' + text + ' '),
'item-min': click.style(' - ' + text + ' '),
'quote-head-fail': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='red'),
'quote-head-pass': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='green'),
'quote-head-skip': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='yellow'),
'quote-fail': re.sub('^', click.style(chr(9482) + ' ', fg='red'), text, flags=re.M),
'quote-pass': re.sub('^', click.style(chr(9482) + ' ', fg='green'), text, flags=re.M),
'quote-skip': re.sub('^', click.style(chr(9482) + ' ', fg='yellow'), text, flags=re.M),
'fail': click.style(text + ' ', fg='red'),
'pass': click.style(text + ' ', fg='green'),
'skip': click.style(text + ' ', fg='yellow')
}.get(style, '') | python | def decorate(text, style):
""" Console decoration style definitions
:param text: the text string to decorate
:type text: str
:param style: the style used to decorate the string
:type style: str
:return: a decorated string
:rtype: str
"""
return {
'step-maj': click.style("\n" + '> ' + text, fg='yellow', bold=True),
'step-min': click.style(' - ' + text + ' ', bold=True),
'item-maj': click.style(' - ' + text + ' '),
'item-min': click.style(' - ' + text + ' '),
'quote-head-fail': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='red'),
'quote-head-pass': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='green'),
'quote-head-skip': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='yellow'),
'quote-fail': re.sub('^', click.style(chr(9482) + ' ', fg='red'), text, flags=re.M),
'quote-pass': re.sub('^', click.style(chr(9482) + ' ', fg='green'), text, flags=re.M),
'quote-skip': re.sub('^', click.style(chr(9482) + ' ', fg='yellow'), text, flags=re.M),
'fail': click.style(text + ' ', fg='red'),
'pass': click.style(text + ' ', fg='green'),
'skip': click.style(text + ' ', fg='yellow')
}.get(style, '') | [
"def",
"decorate",
"(",
"text",
",",
"style",
")",
":",
"return",
"{",
"'step-maj'",
":",
"click",
".",
"style",
"(",
"\"\\n\"",
"+",
"'> '",
"+",
"text",
",",
"fg",
"=",
"'yellow'",
",",
"bold",
"=",
"True",
")",
",",
"'step-min'",
":",
"click",
"... | Console decoration style definitions
:param text: the text string to decorate
:type text: str
:param style: the style used to decorate the string
:type style: str
:return: a decorated string
:rtype: str | [
"Console",
"decoration",
"style",
"definitions"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/cli/helpers.py#L124-L150 | train | 39,554 |
dcos/shakedown | shakedown/cli/helpers.py | echo | def echo(text, **kwargs):
""" Print results to the console
:param text: the text string to print
:type text: str
:return: a string
:rtype: str
"""
if shakedown.cli.quiet:
return
if not 'n' in kwargs:
kwargs['n'] = True
if 'd' in kwargs:
text = decorate(text, kwargs['d'])
if 'TERM' in os.environ and os.environ['TERM'] == 'velocity':
if text:
print(text, end="", flush=True)
if kwargs.get('n'):
print()
else:
click.echo(text, nl=kwargs.get('n')) | python | def echo(text, **kwargs):
""" Print results to the console
:param text: the text string to print
:type text: str
:return: a string
:rtype: str
"""
if shakedown.cli.quiet:
return
if not 'n' in kwargs:
kwargs['n'] = True
if 'd' in kwargs:
text = decorate(text, kwargs['d'])
if 'TERM' in os.environ and os.environ['TERM'] == 'velocity':
if text:
print(text, end="", flush=True)
if kwargs.get('n'):
print()
else:
click.echo(text, nl=kwargs.get('n')) | [
"def",
"echo",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"shakedown",
".",
"cli",
".",
"quiet",
":",
"return",
"if",
"not",
"'n'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'n'",
"]",
"=",
"True",
"if",
"'d'",
"in",
"kwargs",
":",
"text",
... | Print results to the console
:param text: the text string to print
:type text: str
:return: a string
:rtype: str | [
"Print",
"results",
"to",
"the",
"console"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/cli/helpers.py#L153-L178 | train | 39,555 |
dcos/shakedown | shakedown/dcos/security.py | add_user | def add_user(uid, password, desc=None):
""" Adds user to the DCOS Enterprise. If not description
is provided the uid will be used for the description.
:param uid: user id
:type uid: str
:param password: password
:type password: str
:param desc: description of user
:type desc: str
"""
try:
desc = uid if desc is None else desc
user_object = {"description": desc, "password": password}
acl_url = urljoin(_acl_url(), 'users/{}'.format(uid))
r = http.put(acl_url, json=user_object)
assert r.status_code == 201
except DCOSHTTPException as e:
# already exists
if e.response.status_code != 409:
raise | python | def add_user(uid, password, desc=None):
""" Adds user to the DCOS Enterprise. If not description
is provided the uid will be used for the description.
:param uid: user id
:type uid: str
:param password: password
:type password: str
:param desc: description of user
:type desc: str
"""
try:
desc = uid if desc is None else desc
user_object = {"description": desc, "password": password}
acl_url = urljoin(_acl_url(), 'users/{}'.format(uid))
r = http.put(acl_url, json=user_object)
assert r.status_code == 201
except DCOSHTTPException as e:
# already exists
if e.response.status_code != 409:
raise | [
"def",
"add_user",
"(",
"uid",
",",
"password",
",",
"desc",
"=",
"None",
")",
":",
"try",
":",
"desc",
"=",
"uid",
"if",
"desc",
"is",
"None",
"else",
"desc",
"user_object",
"=",
"{",
"\"description\"",
":",
"desc",
",",
"\"password\"",
":",
"password... | Adds user to the DCOS Enterprise. If not description
is provided the uid will be used for the description.
:param uid: user id
:type uid: str
:param password: password
:type password: str
:param desc: description of user
:type desc: str | [
"Adds",
"user",
"to",
"the",
"DCOS",
"Enterprise",
".",
"If",
"not",
"description",
"is",
"provided",
"the",
"uid",
"will",
"be",
"used",
"for",
"the",
"description",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L17-L37 | train | 39,556 |
dcos/shakedown | shakedown/dcos/security.py | get_user | def get_user(uid):
""" Returns a user from the DCOS Enterprise. It returns None if none exists.
:param uid: user id
:type uid: str
:return: User
:rtype: dict
"""
try:
acl_url = urljoin(_acl_url(), 'users/{}'.format(uid))
r = http.get(acl_url)
return r.json()
# assert r.status_code == 201
except DCOSHTTPException as e:
if e.response.status_code == 400:
return None
else:
raise | python | def get_user(uid):
""" Returns a user from the DCOS Enterprise. It returns None if none exists.
:param uid: user id
:type uid: str
:return: User
:rtype: dict
"""
try:
acl_url = urljoin(_acl_url(), 'users/{}'.format(uid))
r = http.get(acl_url)
return r.json()
# assert r.status_code == 201
except DCOSHTTPException as e:
if e.response.status_code == 400:
return None
else:
raise | [
"def",
"get_user",
"(",
"uid",
")",
":",
"try",
":",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
"'users/{}'",
".",
"format",
"(",
"uid",
")",
")",
"r",
"=",
"http",
".",
"get",
"(",
"acl_url",
")",
"return",
"r",
".",
"json",
"(",... | Returns a user from the DCOS Enterprise. It returns None if none exists.
:param uid: user id
:type uid: str
:return: User
:rtype: dict | [
"Returns",
"a",
"user",
"from",
"the",
"DCOS",
"Enterprise",
".",
"It",
"returns",
"None",
"if",
"none",
"exists",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L40-L57 | train | 39,557 |
dcos/shakedown | shakedown/dcos/security.py | remove_user | def remove_user(uid):
""" Removes a user from the DCOS Enterprise.
:param uid: user id
:type uid: str
"""
try:
acl_url = urljoin(_acl_url(), 'users/{}'.format(uid))
r = http.delete(acl_url)
assert r.status_code == 204
except DCOSHTTPException as e:
# doesn't exist
if e.response.status_code != 400:
raise | python | def remove_user(uid):
""" Removes a user from the DCOS Enterprise.
:param uid: user id
:type uid: str
"""
try:
acl_url = urljoin(_acl_url(), 'users/{}'.format(uid))
r = http.delete(acl_url)
assert r.status_code == 204
except DCOSHTTPException as e:
# doesn't exist
if e.response.status_code != 400:
raise | [
"def",
"remove_user",
"(",
"uid",
")",
":",
"try",
":",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
"'users/{}'",
".",
"format",
"(",
"uid",
")",
")",
"r",
"=",
"http",
".",
"delete",
"(",
"acl_url",
")",
"assert",
"r",
".",
"status_... | Removes a user from the DCOS Enterprise.
:param uid: user id
:type uid: str | [
"Removes",
"a",
"user",
"from",
"the",
"DCOS",
"Enterprise",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L60-L73 | train | 39,558 |
dcos/shakedown | shakedown/dcos/security.py | remove_user_permission | def remove_user_permission(rid, uid, action='full'):
""" Removes user permission on a given resource.
:param uid: user id
:type uid: str
:param rid: resource ID
:type rid: str
:param action: read, write, update, delete or full
:type action: str
"""
rid = rid.replace('/', '%252F')
try:
acl_url = urljoin(_acl_url(), 'acls/{}/users/{}/{}'.format(rid, uid, action))
r = http.delete(acl_url)
assert r.status_code == 204
except DCOSHTTPException as e:
if e.response.status_code != 400:
raise | python | def remove_user_permission(rid, uid, action='full'):
""" Removes user permission on a given resource.
:param uid: user id
:type uid: str
:param rid: resource ID
:type rid: str
:param action: read, write, update, delete or full
:type action: str
"""
rid = rid.replace('/', '%252F')
try:
acl_url = urljoin(_acl_url(), 'acls/{}/users/{}/{}'.format(rid, uid, action))
r = http.delete(acl_url)
assert r.status_code == 204
except DCOSHTTPException as e:
if e.response.status_code != 400:
raise | [
"def",
"remove_user_permission",
"(",
"rid",
",",
"uid",
",",
"action",
"=",
"'full'",
")",
":",
"rid",
"=",
"rid",
".",
"replace",
"(",
"'/'",
",",
"'%252F'",
")",
"try",
":",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
"'acls/{}/users/... | Removes user permission on a given resource.
:param uid: user id
:type uid: str
:param rid: resource ID
:type rid: str
:param action: read, write, update, delete or full
:type action: str | [
"Removes",
"user",
"permission",
"on",
"a",
"given",
"resource",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L117-L135 | train | 39,559 |
dcos/shakedown | shakedown/dcos/security.py | no_user | def no_user():
""" Provides a context with no logged in user.
"""
o_token = dcos_acs_token()
dcos.config.set_val('core.dcos_acs_token', '')
yield
dcos.config.set_val('core.dcos_acs_token', o_token) | python | def no_user():
""" Provides a context with no logged in user.
"""
o_token = dcos_acs_token()
dcos.config.set_val('core.dcos_acs_token', '')
yield
dcos.config.set_val('core.dcos_acs_token', o_token) | [
"def",
"no_user",
"(",
")",
":",
"o_token",
"=",
"dcos_acs_token",
"(",
")",
"dcos",
".",
"config",
".",
"set_val",
"(",
"'core.dcos_acs_token'",
",",
"''",
")",
"yield",
"dcos",
".",
"config",
".",
"set_val",
"(",
"'core.dcos_acs_token'",
",",
"o_token",
... | Provides a context with no logged in user. | [
"Provides",
"a",
"context",
"with",
"no",
"logged",
"in",
"user",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L139-L145 | train | 39,560 |
dcos/shakedown | shakedown/dcos/security.py | new_dcos_user | def new_dcos_user(user_id, password):
""" Provides a context with a newly created user.
"""
o_token = dcos_acs_token()
shakedown.add_user(user_id, password, user_id)
token = shakedown.authenticate(user_id, password)
dcos.config.set_val('core.dcos_acs_token', token)
yield
dcos.config.set_val('core.dcos_acs_token', o_token)
shakedown.remove_user(user_id) | python | def new_dcos_user(user_id, password):
""" Provides a context with a newly created user.
"""
o_token = dcos_acs_token()
shakedown.add_user(user_id, password, user_id)
token = shakedown.authenticate(user_id, password)
dcos.config.set_val('core.dcos_acs_token', token)
yield
dcos.config.set_val('core.dcos_acs_token', o_token)
shakedown.remove_user(user_id) | [
"def",
"new_dcos_user",
"(",
"user_id",
",",
"password",
")",
":",
"o_token",
"=",
"dcos_acs_token",
"(",
")",
"shakedown",
".",
"add_user",
"(",
"user_id",
",",
"password",
",",
"user_id",
")",
"token",
"=",
"shakedown",
".",
"authenticate",
"(",
"user_id",... | Provides a context with a newly created user. | [
"Provides",
"a",
"context",
"with",
"a",
"newly",
"created",
"user",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L149-L159 | train | 39,561 |
dcos/shakedown | shakedown/dcos/security.py | dcos_user | def dcos_user(user_id, password):
""" Provides a context with user otherthan super
"""
o_token = dcos_acs_token()
token = shakedown.authenticate(user_id, password)
dcos.config.set_val('core.dcos_acs_token', token)
yield
dcos.config.set_val('core.dcos_acs_token', o_token) | python | def dcos_user(user_id, password):
""" Provides a context with user otherthan super
"""
o_token = dcos_acs_token()
token = shakedown.authenticate(user_id, password)
dcos.config.set_val('core.dcos_acs_token', token)
yield
dcos.config.set_val('core.dcos_acs_token', o_token) | [
"def",
"dcos_user",
"(",
"user_id",
",",
"password",
")",
":",
"o_token",
"=",
"dcos_acs_token",
"(",
")",
"token",
"=",
"shakedown",
".",
"authenticate",
"(",
"user_id",
",",
"password",
")",
"dcos",
".",
"config",
".",
"set_val",
"(",
"'core.dcos_acs_token... | Provides a context with user otherthan super | [
"Provides",
"a",
"context",
"with",
"user",
"otherthan",
"super"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L163-L172 | train | 39,562 |
dcos/shakedown | shakedown/dcos/security.py | add_group | def add_group(id, description=None):
""" Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str
"""
if not description:
description = id
data = {
'description': description
}
acl_url = urljoin(_acl_url(), 'groups/{}'.format(id))
try:
r = http.put(acl_url, json=data)
assert r.status_code == 201
except DCOSHTTPException as e:
if e.response.status_code != 409:
raise | python | def add_group(id, description=None):
""" Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str
"""
if not description:
description = id
data = {
'description': description
}
acl_url = urljoin(_acl_url(), 'groups/{}'.format(id))
try:
r = http.put(acl_url, json=data)
assert r.status_code == 201
except DCOSHTTPException as e:
if e.response.status_code != 409:
raise | [
"def",
"add_group",
"(",
"id",
",",
"description",
"=",
"None",
")",
":",
"if",
"not",
"description",
":",
"description",
"=",
"id",
"data",
"=",
"{",
"'description'",
":",
"description",
"}",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
... | Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str | [
"Adds",
"group",
"to",
"the",
"DCOS",
"Enterprise",
".",
"If",
"not",
"description",
"is",
"provided",
"the",
"id",
"will",
"be",
"used",
"for",
"the",
"description",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L175-L196 | train | 39,563 |
dcos/shakedown | shakedown/dcos/security.py | get_group | def get_group(id):
""" Returns a group from the DCOS Enterprise. It returns None if none exists.
:param id: group id
:type id: str
:return: Group
:rtype: dict
"""
acl_url = urljoin(_acl_url(), 'groups/{}'.format(id))
try:
r = http.get(acl_url)
return r.json()
except DCOSHTTPException as e:
if e.response.status_code != 400:
raise | python | def get_group(id):
""" Returns a group from the DCOS Enterprise. It returns None if none exists.
:param id: group id
:type id: str
:return: Group
:rtype: dict
"""
acl_url = urljoin(_acl_url(), 'groups/{}'.format(id))
try:
r = http.get(acl_url)
return r.json()
except DCOSHTTPException as e:
if e.response.status_code != 400:
raise | [
"def",
"get_group",
"(",
"id",
")",
":",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
"'groups/{}'",
".",
"format",
"(",
"id",
")",
")",
"try",
":",
"r",
"=",
"http",
".",
"get",
"(",
"acl_url",
")",
"return",
"r",
".",
"json",
"(",... | Returns a group from the DCOS Enterprise. It returns None if none exists.
:param id: group id
:type id: str
:return: Group
:rtype: dict | [
"Returns",
"a",
"group",
"from",
"the",
"DCOS",
"Enterprise",
".",
"It",
"returns",
"None",
"if",
"none",
"exists",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L199-L213 | train | 39,564 |
dcos/shakedown | shakedown/dcos/security.py | remove_group | def remove_group(id):
""" Removes a group from the DCOS Enterprise. The group is
removed regardless of associated users.
:param id: group id
:type id: str
"""
acl_url = urljoin(_acl_url(), 'groups/{}'.format(id))
try:
r = http.delete(acl_url)
print(r.status_code)
except DCOSHTTPException as e:
if e.response.status_code != 400:
raise | python | def remove_group(id):
""" Removes a group from the DCOS Enterprise. The group is
removed regardless of associated users.
:param id: group id
:type id: str
"""
acl_url = urljoin(_acl_url(), 'groups/{}'.format(id))
try:
r = http.delete(acl_url)
print(r.status_code)
except DCOSHTTPException as e:
if e.response.status_code != 400:
raise | [
"def",
"remove_group",
"(",
"id",
")",
":",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
"'groups/{}'",
".",
"format",
"(",
"id",
")",
")",
"try",
":",
"r",
"=",
"http",
".",
"delete",
"(",
"acl_url",
")",
"print",
"(",
"r",
".",
"s... | Removes a group from the DCOS Enterprise. The group is
removed regardless of associated users.
:param id: group id
:type id: str | [
"Removes",
"a",
"group",
"from",
"the",
"DCOS",
"Enterprise",
".",
"The",
"group",
"is",
"removed",
"regardless",
"of",
"associated",
"users",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L216-L229 | train | 39,565 |
dcos/shakedown | shakedown/dcos/security.py | add_user_to_group | def add_user_to_group(uid, gid, exist_ok=True):
""" Adds a user to a group within DCOS Enterprise. The group and
user must exist.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
:param exist_ok: True if it is ok for the relationship to pre-exist.
:type exist_ok: bool
"""
acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))
try:
r = http.put(acl_url)
assert r.status_code == 204
except DCOSHTTPException as e:
if e.response.status_code == 409 and exist_ok:
pass
else:
raise | python | def add_user_to_group(uid, gid, exist_ok=True):
""" Adds a user to a group within DCOS Enterprise. The group and
user must exist.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
:param exist_ok: True if it is ok for the relationship to pre-exist.
:type exist_ok: bool
"""
acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))
try:
r = http.put(acl_url)
assert r.status_code == 204
except DCOSHTTPException as e:
if e.response.status_code == 409 and exist_ok:
pass
else:
raise | [
"def",
"add_user_to_group",
"(",
"uid",
",",
"gid",
",",
"exist_ok",
"=",
"True",
")",
":",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
"'groups/{}/users/{}'",
".",
"format",
"(",
"gid",
",",
"uid",
")",
")",
"try",
":",
"r",
"=",
"htt... | Adds a user to a group within DCOS Enterprise. The group and
user must exist.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
:param exist_ok: True if it is ok for the relationship to pre-exist.
:type exist_ok: bool | [
"Adds",
"a",
"user",
"to",
"a",
"group",
"within",
"DCOS",
"Enterprise",
".",
"The",
"group",
"and",
"user",
"must",
"exist",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L232-L251 | train | 39,566 |
dcos/shakedown | shakedown/dcos/security.py | remove_user_from_group | def remove_user_from_group(uid, gid):
""" Removes a user from a group within DCOS Enterprise.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
"""
acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))
try:
r = http.delete(acl_url)
assert r.status_code == 204
except dcos.errors.DCOSBadRequest:
pass | python | def remove_user_from_group(uid, gid):
""" Removes a user from a group within DCOS Enterprise.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
"""
acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))
try:
r = http.delete(acl_url)
assert r.status_code == 204
except dcos.errors.DCOSBadRequest:
pass | [
"def",
"remove_user_from_group",
"(",
"uid",
",",
"gid",
")",
":",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
"'groups/{}/users/{}'",
".",
"format",
"(",
"gid",
",",
"uid",
")",
")",
"try",
":",
"r",
"=",
"http",
".",
"delete",
"(",
"... | Removes a user from a group within DCOS Enterprise.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str | [
"Removes",
"a",
"user",
"from",
"a",
"group",
"within",
"DCOS",
"Enterprise",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L254-L267 | train | 39,567 |
openstax/cnx-easybake | cnxeasybake/scripts/main.py | easybake | def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None,
coverage_file=None, use_repeatable_ids=False):
"""Process the given HTML file stream with the css stream."""
html_doc = etree.parse(html_in)
oven = Oven(css_in, use_repeatable_ids)
oven.bake(html_doc, last_step)
# serialize out HTML
print(etree.tostring(html_doc, method="xml").decode('utf-8'),
file=html_out)
# generate CSS coverage_file file
if coverage_file:
print('SF:{}'.format(css_in.name), file=coverage_file)
print(oven.get_coverage_report(), file=coverage_file)
print('end_of_record', file=coverage_file) | python | def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None,
coverage_file=None, use_repeatable_ids=False):
"""Process the given HTML file stream with the css stream."""
html_doc = etree.parse(html_in)
oven = Oven(css_in, use_repeatable_ids)
oven.bake(html_doc, last_step)
# serialize out HTML
print(etree.tostring(html_doc, method="xml").decode('utf-8'),
file=html_out)
# generate CSS coverage_file file
if coverage_file:
print('SF:{}'.format(css_in.name), file=coverage_file)
print(oven.get_coverage_report(), file=coverage_file)
print('end_of_record', file=coverage_file) | [
"def",
"easybake",
"(",
"css_in",
",",
"html_in",
"=",
"sys",
".",
"stdin",
",",
"html_out",
"=",
"sys",
".",
"stdout",
",",
"last_step",
"=",
"None",
",",
"coverage_file",
"=",
"None",
",",
"use_repeatable_ids",
"=",
"False",
")",
":",
"html_doc",
"=",
... | Process the given HTML file stream with the css stream. | [
"Process",
"the",
"given",
"HTML",
"file",
"stream",
"with",
"the",
"css",
"stream",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/scripts/main.py#L15-L30 | train | 39,568 |
openstax/cnx-easybake | cnxeasybake/scripts/main.py | main | def main(argv=None):
"""Commandline script wrapping Baker."""
parser = argparse.ArgumentParser(description="Process raw HTML to baked"
" (embedded numbering and"
" collation)")
parser.add_argument('-v', '--version', action="version",
version=__version__, help='Report the library version')
parser.add_argument("css_rules",
type=argparse.FileType('rb'),
help="CSS3 ruleset stylesheet recipe")
parser.add_argument("html_in", nargs="?",
type=argparse.FileType('r'),
help="raw HTML file to bake (default stdin)",
default=sys.stdin)
parser.add_argument("html_out", nargs="?",
type=argparse.FileType('w'),
help="baked HTML file output (default stdout)",
default=sys.stdout)
parser.add_argument('-s', '--stop-at', action='store', metavar='<pass>',
help='Stop baking just before given pass name')
parser.add_argument('-d', '--debug', action='store_true',
help='Send debugging info to stderr')
parser.add_argument('-q', '--quiet', action='store_true',
help="Quiet all on stderr except errors")
parser.add_argument('-c', '--coverage-file', metavar='coverage.lcov',
type=FileTypeExt('w'),
help="output coverage file (lcov format). If "
"filename starts with '+', append coverage info.")
parser.add_argument('--use-repeatable-ids', action='store_true',
help="use repeatable id attributes instead of uuids "
"which is useful for diffing")
args = parser.parse_args(argv)
formatter = logging.Formatter('%(name)s %(levelname)s %(message)s')
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(formatter)
logger.addHandler(handler)
use_quiet_log = (args.quiet and logging.ERROR)
use_debug_log = (args.debug and logging.DEBUG)
# Debug option takes higher priority than quiet warnings option
logger.setLevel(use_debug_log or use_quiet_log or logging.WARNING)
try:
easybake(args.css_rules, args.html_in, args.html_out, args.stop_at,
args.coverage_file, args.use_repeatable_ids)
finally:
if args.css_rules:
args.css_rules.close()
if args.html_in:
args.html_in.close()
if args.html_out:
args.html_out.close()
if args.coverage_file:
args.coverage_file.close() | python | def main(argv=None):
"""Commandline script wrapping Baker."""
parser = argparse.ArgumentParser(description="Process raw HTML to baked"
" (embedded numbering and"
" collation)")
parser.add_argument('-v', '--version', action="version",
version=__version__, help='Report the library version')
parser.add_argument("css_rules",
type=argparse.FileType('rb'),
help="CSS3 ruleset stylesheet recipe")
parser.add_argument("html_in", nargs="?",
type=argparse.FileType('r'),
help="raw HTML file to bake (default stdin)",
default=sys.stdin)
parser.add_argument("html_out", nargs="?",
type=argparse.FileType('w'),
help="baked HTML file output (default stdout)",
default=sys.stdout)
parser.add_argument('-s', '--stop-at', action='store', metavar='<pass>',
help='Stop baking just before given pass name')
parser.add_argument('-d', '--debug', action='store_true',
help='Send debugging info to stderr')
parser.add_argument('-q', '--quiet', action='store_true',
help="Quiet all on stderr except errors")
parser.add_argument('-c', '--coverage-file', metavar='coverage.lcov',
type=FileTypeExt('w'),
help="output coverage file (lcov format). If "
"filename starts with '+', append coverage info.")
parser.add_argument('--use-repeatable-ids', action='store_true',
help="use repeatable id attributes instead of uuids "
"which is useful for diffing")
args = parser.parse_args(argv)
formatter = logging.Formatter('%(name)s %(levelname)s %(message)s')
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(formatter)
logger.addHandler(handler)
use_quiet_log = (args.quiet and logging.ERROR)
use_debug_log = (args.debug and logging.DEBUG)
# Debug option takes higher priority than quiet warnings option
logger.setLevel(use_debug_log or use_quiet_log or logging.WARNING)
try:
easybake(args.css_rules, args.html_in, args.html_out, args.stop_at,
args.coverage_file, args.use_repeatable_ids)
finally:
if args.css_rules:
args.css_rules.close()
if args.html_in:
args.html_in.close()
if args.html_out:
args.html_out.close()
if args.coverage_file:
args.coverage_file.close() | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Process raw HTML to baked\"",
"\" (embedded numbering and\"",
"\" collation)\"",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
... | Commandline script wrapping Baker. | [
"Commandline",
"script",
"wrapping",
"Baker",
"."
] | f8edf018fb7499f6f18af0145c326b93a737a782 | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/scripts/main.py#L44-L99 | train | 39,569 |
dcos/shakedown | shakedown/dcos/marathon.py | mom_version | def mom_version(name='marathon-user'):
"""Returns the version of marathon on marathon.
"""
if service_available_predicate(name):
with marathon_on_marathon(name):
return marathon_version()
else:
# We can either skip the corresponding test by returning False
# or raise an exception.
print('WARN: {} MoM not found. Version is None'.format(name))
return None | python | def mom_version(name='marathon-user'):
"""Returns the version of marathon on marathon.
"""
if service_available_predicate(name):
with marathon_on_marathon(name):
return marathon_version()
else:
# We can either skip the corresponding test by returning False
# or raise an exception.
print('WARN: {} MoM not found. Version is None'.format(name))
return None | [
"def",
"mom_version",
"(",
"name",
"=",
"'marathon-user'",
")",
":",
"if",
"service_available_predicate",
"(",
"name",
")",
":",
"with",
"marathon_on_marathon",
"(",
"name",
")",
":",
"return",
"marathon_version",
"(",
")",
"else",
":",
"# We can either skip the c... | Returns the version of marathon on marathon. | [
"Returns",
"the",
"version",
"of",
"marathon",
"on",
"marathon",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/marathon.py#L33-L43 | train | 39,570 |
dcos/shakedown | shakedown/dcos/helpers.py | get_transport | def get_transport(host, username, key):
""" Create a transport object
:param host: the hostname to connect to
:type host: str
:param username: SSH username
:type username: str
:param key: key object used for authentication
:type key: paramiko.RSAKey
:return: a transport object
:rtype: paramiko.Transport
"""
if host == shakedown.master_ip():
transport = paramiko.Transport(host)
else:
transport_master = paramiko.Transport(shakedown.master_ip())
transport_master = start_transport(transport_master, username, key)
if not transport_master.is_authenticated():
print("error: unable to authenticate {}@{} with key {}".format(username, shakedown.master_ip(), key))
return False
try:
channel = transport_master.open_channel('direct-tcpip', (host, 22), ('127.0.0.1', 0))
except paramiko.SSHException:
print("error: unable to connect to {}".format(host))
return False
transport = paramiko.Transport(channel)
return transport | python | def get_transport(host, username, key):
""" Create a transport object
:param host: the hostname to connect to
:type host: str
:param username: SSH username
:type username: str
:param key: key object used for authentication
:type key: paramiko.RSAKey
:return: a transport object
:rtype: paramiko.Transport
"""
if host == shakedown.master_ip():
transport = paramiko.Transport(host)
else:
transport_master = paramiko.Transport(shakedown.master_ip())
transport_master = start_transport(transport_master, username, key)
if not transport_master.is_authenticated():
print("error: unable to authenticate {}@{} with key {}".format(username, shakedown.master_ip(), key))
return False
try:
channel = transport_master.open_channel('direct-tcpip', (host, 22), ('127.0.0.1', 0))
except paramiko.SSHException:
print("error: unable to connect to {}".format(host))
return False
transport = paramiko.Transport(channel)
return transport | [
"def",
"get_transport",
"(",
"host",
",",
"username",
",",
"key",
")",
":",
"if",
"host",
"==",
"shakedown",
".",
"master_ip",
"(",
")",
":",
"transport",
"=",
"paramiko",
".",
"Transport",
"(",
"host",
")",
"else",
":",
"transport_master",
"=",
"paramik... | Create a transport object
:param host: the hostname to connect to
:type host: str
:param username: SSH username
:type username: str
:param key: key object used for authentication
:type key: paramiko.RSAKey
:return: a transport object
:rtype: paramiko.Transport | [
"Create",
"a",
"transport",
"object"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/helpers.py#L11-L43 | train | 39,571 |
dcos/shakedown | shakedown/dcos/helpers.py | start_transport | def start_transport(transport, username, key):
""" Begin a transport client and authenticate it
:param transport: the transport object to start
:type transport: paramiko.Transport
:param username: SSH username
:type username: str
:param key: key object used for authentication
:type key: paramiko.RSAKey
:return: the transport object passed
:rtype: paramiko.Transport
"""
transport.start_client()
agent = paramiko.agent.Agent()
keys = itertools.chain((key,) if key else (), agent.get_keys())
for test_key in keys:
try:
transport.auth_publickey(username, test_key)
break
except paramiko.AuthenticationException as e:
pass
else:
raise ValueError('No valid key supplied')
return transport | python | def start_transport(transport, username, key):
""" Begin a transport client and authenticate it
:param transport: the transport object to start
:type transport: paramiko.Transport
:param username: SSH username
:type username: str
:param key: key object used for authentication
:type key: paramiko.RSAKey
:return: the transport object passed
:rtype: paramiko.Transport
"""
transport.start_client()
agent = paramiko.agent.Agent()
keys = itertools.chain((key,) if key else (), agent.get_keys())
for test_key in keys:
try:
transport.auth_publickey(username, test_key)
break
except paramiko.AuthenticationException as e:
pass
else:
raise ValueError('No valid key supplied')
return transport | [
"def",
"start_transport",
"(",
"transport",
",",
"username",
",",
"key",
")",
":",
"transport",
".",
"start_client",
"(",
")",
"agent",
"=",
"paramiko",
".",
"agent",
".",
"Agent",
"(",
")",
"keys",
"=",
"itertools",
".",
"chain",
"(",
"(",
"key",
",",... | Begin a transport client and authenticate it
:param transport: the transport object to start
:type transport: paramiko.Transport
:param username: SSH username
:type username: str
:param key: key object used for authentication
:type key: paramiko.RSAKey
:return: the transport object passed
:rtype: paramiko.Transport | [
"Begin",
"a",
"transport",
"client",
"and",
"authenticate",
"it"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/helpers.py#L46-L73 | train | 39,572 |
dcos/shakedown | shakedown/dcos/helpers.py | validate_key | def validate_key(key_path):
""" Validate a key
:param key_path: path to a key to use for authentication
:type key_path: str
:return: key object used for authentication
:rtype: paramiko.RSAKey
"""
key_path = os.path.expanduser(key_path)
if not os.path.isfile(key_path):
return False
return paramiko.RSAKey.from_private_key_file(key_path) | python | def validate_key(key_path):
""" Validate a key
:param key_path: path to a key to use for authentication
:type key_path: str
:return: key object used for authentication
:rtype: paramiko.RSAKey
"""
key_path = os.path.expanduser(key_path)
if not os.path.isfile(key_path):
return False
return paramiko.RSAKey.from_private_key_file(key_path) | [
"def",
"validate_key",
"(",
"key_path",
")",
":",
"key_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"key_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"key_path",
")",
":",
"return",
"False",
"return",
"paramiko",
".",
"RSAK... | Validate a key
:param key_path: path to a key to use for authentication
:type key_path: str
:return: key object used for authentication
:rtype: paramiko.RSAKey | [
"Validate",
"a",
"key"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/helpers.py#L86-L101 | train | 39,573 |
dcos/shakedown | shakedown/dcos/service.py | get_marathon_task | def get_marathon_task(
task_name,
inactive=False,
completed=False
):
""" Get a dictionary describing a named marathon task
"""
return get_service_task('marathon', task_name, inactive, completed) | python | def get_marathon_task(
task_name,
inactive=False,
completed=False
):
""" Get a dictionary describing a named marathon task
"""
return get_service_task('marathon', task_name, inactive, completed) | [
"def",
"get_marathon_task",
"(",
"task_name",
",",
"inactive",
"=",
"False",
",",
"completed",
"=",
"False",
")",
":",
"return",
"get_service_task",
"(",
"'marathon'",
",",
"task_name",
",",
"inactive",
",",
"completed",
")"
] | Get a dictionary describing a named marathon task | [
"Get",
"a",
"dictionary",
"describing",
"a",
"named",
"marathon",
"task"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L161-L169 | train | 39,574 |
dcos/shakedown | shakedown/dcos/service.py | get_mesos_task | def get_mesos_task(task_name):
""" Get a mesos task with a specific task name
"""
tasks = get_mesos_tasks()
if tasks is not None:
for task in tasks:
if task['name'] == task_name:
return task
return None | python | def get_mesos_task(task_name):
""" Get a mesos task with a specific task name
"""
tasks = get_mesos_tasks()
if tasks is not None:
for task in tasks:
if task['name'] == task_name:
return task
return None | [
"def",
"get_mesos_task",
"(",
"task_name",
")",
":",
"tasks",
"=",
"get_mesos_tasks",
"(",
")",
"if",
"tasks",
"is",
"not",
"None",
":",
"for",
"task",
"in",
"tasks",
":",
"if",
"task",
"[",
"'name'",
"]",
"==",
"task_name",
":",
"return",
"task",
"ret... | Get a mesos task with a specific task name | [
"Get",
"a",
"mesos",
"task",
"with",
"a",
"specific",
"task",
"name"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L172-L181 | train | 39,575 |
dcos/shakedown | shakedown/dcos/service.py | service_healthy | def service_healthy(service_name, app_id=None):
""" Check whether a named service is healthy
:param service_name: the service name
:type service_name: str
:param app_id: app_id to filter
:type app_id: str
:return: True if healthy, False otherwise
:rtype: bool
"""
marathon_client = marathon.create_client()
apps = marathon_client.get_apps_for_framework(service_name)
if apps:
for app in apps:
if (app_id is not None) and (app['id'] != "/{}".format(str(app_id))):
continue
if (app['tasksHealthy']) \
and (app['tasksRunning']) \
and (not app['tasksStaged']) \
and (not app['tasksUnhealthy']):
return True
return False | python | def service_healthy(service_name, app_id=None):
""" Check whether a named service is healthy
:param service_name: the service name
:type service_name: str
:param app_id: app_id to filter
:type app_id: str
:return: True if healthy, False otherwise
:rtype: bool
"""
marathon_client = marathon.create_client()
apps = marathon_client.get_apps_for_framework(service_name)
if apps:
for app in apps:
if (app_id is not None) and (app['id'] != "/{}".format(str(app_id))):
continue
if (app['tasksHealthy']) \
and (app['tasksRunning']) \
and (not app['tasksStaged']) \
and (not app['tasksUnhealthy']):
return True
return False | [
"def",
"service_healthy",
"(",
"service_name",
",",
"app_id",
"=",
"None",
")",
":",
"marathon_client",
"=",
"marathon",
".",
"create_client",
"(",
")",
"apps",
"=",
"marathon_client",
".",
"get_apps_for_framework",
"(",
"service_name",
")",
"if",
"apps",
":",
... | Check whether a named service is healthy
:param service_name: the service name
:type service_name: str
:param app_id: app_id to filter
:type app_id: str
:return: True if healthy, False otherwise
:rtype: bool | [
"Check",
"whether",
"a",
"named",
"service",
"is",
"healthy"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L221-L247 | train | 39,576 |
dcos/shakedown | shakedown/dcos/service.py | delete_persistent_data | def delete_persistent_data(role, zk_node):
""" Deletes any persistent data associated with the specified role, and zk node.
:param role: the mesos role to delete, or None to omit this
:type role: str
:param zk_node: the zookeeper node to be deleted, or None to skip this deletion
:type zk_node: str
"""
if role:
destroy_volumes(role)
unreserve_resources(role)
if zk_node:
delete_zk_node(zk_node) | python | def delete_persistent_data(role, zk_node):
""" Deletes any persistent data associated with the specified role, and zk node.
:param role: the mesos role to delete, or None to omit this
:type role: str
:param zk_node: the zookeeper node to be deleted, or None to skip this deletion
:type zk_node: str
"""
if role:
destroy_volumes(role)
unreserve_resources(role)
if zk_node:
delete_zk_node(zk_node) | [
"def",
"delete_persistent_data",
"(",
"role",
",",
"zk_node",
")",
":",
"if",
"role",
":",
"destroy_volumes",
"(",
"role",
")",
"unreserve_resources",
"(",
"role",
")",
"if",
"zk_node",
":",
"delete_zk_node",
"(",
"zk_node",
")"
] | Deletes any persistent data associated with the specified role, and zk node.
:param role: the mesos role to delete, or None to omit this
:type role: str
:param zk_node: the zookeeper node to be deleted, or None to skip this deletion
:type zk_node: str | [
"Deletes",
"any",
"persistent",
"data",
"associated",
"with",
"the",
"specified",
"role",
"and",
"zk",
"node",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L266-L279 | train | 39,577 |
dcos/shakedown | shakedown/dcos/service.py | destroy_volumes | def destroy_volumes(role):
""" Destroys all volumes on all the slaves in the cluster for the role.
"""
state = dcos_agents_state()
if not state or 'slaves' not in state.keys():
return False
all_success = True
for agent in state['slaves']:
if not destroy_volume(agent, role):
all_success = False
return all_success | python | def destroy_volumes(role):
""" Destroys all volumes on all the slaves in the cluster for the role.
"""
state = dcos_agents_state()
if not state or 'slaves' not in state.keys():
return False
all_success = True
for agent in state['slaves']:
if not destroy_volume(agent, role):
all_success = False
return all_success | [
"def",
"destroy_volumes",
"(",
"role",
")",
":",
"state",
"=",
"dcos_agents_state",
"(",
")",
"if",
"not",
"state",
"or",
"'slaves'",
"not",
"in",
"state",
".",
"keys",
"(",
")",
":",
"return",
"False",
"all_success",
"=",
"True",
"for",
"agent",
"in",
... | Destroys all volumes on all the slaves in the cluster for the role. | [
"Destroys",
"all",
"volumes",
"on",
"all",
"the",
"slaves",
"in",
"the",
"cluster",
"for",
"the",
"role",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L282-L292 | train | 39,578 |
dcos/shakedown | shakedown/dcos/service.py | destroy_volume | def destroy_volume(agent, role):
""" Deletes the volumes on the specific agent for the role
"""
volumes = []
agent_id = agent['id']
reserved_resources_full = agent.get('reserved_resources_full', None)
if not reserved_resources_full:
# doesn't exist
return True
reserved_resources = reserved_resources_full.get(role, None)
if not reserved_resources:
# doesn't exist
return True
for reserved_resource in reserved_resources:
name = reserved_resource.get('name', None)
disk = reserved_resource.get('disk', None)
if name == 'disk' and disk is not None and 'persistence' in disk:
volumes.append(reserved_resource)
req_url = urljoin(master_url(), 'destroy-volumes')
data = {
'slaveId': agent_id,
'volumes': json.dumps(volumes)
}
success = False
try:
response = http.post(req_url, data=data)
success = 200 <= response.status_code < 300
if response.status_code == 409:
# thoughts on what to do here? throw exception
# i would rather not print
print('''###\nIs a framework using these resources still installed?\n###''')
except DCOSHTTPException as e:
print("HTTP {}: Unabled to delete volume based on: {}".format(
e.response.status_code,
e.response.text))
return success | python | def destroy_volume(agent, role):
""" Deletes the volumes on the specific agent for the role
"""
volumes = []
agent_id = agent['id']
reserved_resources_full = agent.get('reserved_resources_full', None)
if not reserved_resources_full:
# doesn't exist
return True
reserved_resources = reserved_resources_full.get(role, None)
if not reserved_resources:
# doesn't exist
return True
for reserved_resource in reserved_resources:
name = reserved_resource.get('name', None)
disk = reserved_resource.get('disk', None)
if name == 'disk' and disk is not None and 'persistence' in disk:
volumes.append(reserved_resource)
req_url = urljoin(master_url(), 'destroy-volumes')
data = {
'slaveId': agent_id,
'volumes': json.dumps(volumes)
}
success = False
try:
response = http.post(req_url, data=data)
success = 200 <= response.status_code < 300
if response.status_code == 409:
# thoughts on what to do here? throw exception
# i would rather not print
print('''###\nIs a framework using these resources still installed?\n###''')
except DCOSHTTPException as e:
print("HTTP {}: Unabled to delete volume based on: {}".format(
e.response.status_code,
e.response.text))
return success | [
"def",
"destroy_volume",
"(",
"agent",
",",
"role",
")",
":",
"volumes",
"=",
"[",
"]",
"agent_id",
"=",
"agent",
"[",
"'id'",
"]",
"reserved_resources_full",
"=",
"agent",
".",
"get",
"(",
"'reserved_resources_full'",
",",
"None",
")",
"if",
"not",
"reser... | Deletes the volumes on the specific agent for the role | [
"Deletes",
"the",
"volumes",
"on",
"the",
"specific",
"agent",
"for",
"the",
"role"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L295-L337 | train | 39,579 |
dcos/shakedown | shakedown/dcos/service.py | unreserve_resources | def unreserve_resources(role):
""" Unreserves all the resources for all the slaves for the role.
"""
state = dcos_agents_state()
if not state or 'slaves' not in state.keys():
return False
all_success = True
for agent in state['slaves']:
if not unreserve_resource(agent, role):
all_success = False
return all_success | python | def unreserve_resources(role):
""" Unreserves all the resources for all the slaves for the role.
"""
state = dcos_agents_state()
if not state or 'slaves' not in state.keys():
return False
all_success = True
for agent in state['slaves']:
if not unreserve_resource(agent, role):
all_success = False
return all_success | [
"def",
"unreserve_resources",
"(",
"role",
")",
":",
"state",
"=",
"dcos_agents_state",
"(",
")",
"if",
"not",
"state",
"or",
"'slaves'",
"not",
"in",
"state",
".",
"keys",
"(",
")",
":",
"return",
"False",
"all_success",
"=",
"True",
"for",
"agent",
"in... | Unreserves all the resources for all the slaves for the role. | [
"Unreserves",
"all",
"the",
"resources",
"for",
"all",
"the",
"slaves",
"for",
"the",
"role",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L340-L350 | train | 39,580 |
dcos/shakedown | shakedown/dcos/service.py | wait_for_service_endpoint | def wait_for_service_endpoint(service_name, timeout_sec=120):
"""Checks the service url if available it returns true, on expiration
it returns false"""
master_count = len(get_all_masters())
return time_wait(lambda: service_available_predicate(service_name),
timeout_seconds=timeout_sec,
required_consecutive_success_count=master_count) | python | def wait_for_service_endpoint(service_name, timeout_sec=120):
"""Checks the service url if available it returns true, on expiration
it returns false"""
master_count = len(get_all_masters())
return time_wait(lambda: service_available_predicate(service_name),
timeout_seconds=timeout_sec,
required_consecutive_success_count=master_count) | [
"def",
"wait_for_service_endpoint",
"(",
"service_name",
",",
"timeout_sec",
"=",
"120",
")",
":",
"master_count",
"=",
"len",
"(",
"get_all_masters",
"(",
")",
")",
"return",
"time_wait",
"(",
"lambda",
":",
"service_available_predicate",
"(",
"service_name",
")"... | Checks the service url if available it returns true, on expiration
it returns false | [
"Checks",
"the",
"service",
"url",
"if",
"available",
"it",
"returns",
"true",
"on",
"expiration",
"it",
"returns",
"false"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L410-L417 | train | 39,581 |
dcos/shakedown | shakedown/dcos/service.py | task_states_predicate | def task_states_predicate(service_name, expected_task_count, expected_task_states):
""" Returns whether the provided service_names's tasks have expected_task_count tasks
in any of expected_task_states. For example, if service 'foo' has 5 tasks which are
TASK_STAGING or TASK_RUNNING.
:param service_name: the service name
:type service_name: str
:param expected_task_count: the number of tasks which should have an expected state
:type expected_task_count: int
:param expected_task_states: the list states to search for among the service's tasks
:type expected_task_states: [str]
:return: True if expected_task_count tasks have any of expected_task_states, False otherwise
:rtype: bool
"""
try:
tasks = get_service_tasks(service_name)
except (DCOSConnectionError, DCOSHTTPException):
tasks = []
matching_tasks = []
other_tasks = []
for t in tasks:
name = t.get('name', 'UNKNOWN_NAME')
state = t.get('state', None)
if state and state in expected_task_states:
matching_tasks.append(name)
else:
other_tasks.append('{}={}'.format(name, state))
print('expected {} tasks in {}:\n- {} in expected {}: {}\n- {} in other states: {}'.format(
expected_task_count, ', '.join(expected_task_states),
len(matching_tasks), ', '.join(expected_task_states), ', '.join(matching_tasks),
len(other_tasks), ', '.join(other_tasks)))
return len(matching_tasks) >= expected_task_count | python | def task_states_predicate(service_name, expected_task_count, expected_task_states):
""" Returns whether the provided service_names's tasks have expected_task_count tasks
in any of expected_task_states. For example, if service 'foo' has 5 tasks which are
TASK_STAGING or TASK_RUNNING.
:param service_name: the service name
:type service_name: str
:param expected_task_count: the number of tasks which should have an expected state
:type expected_task_count: int
:param expected_task_states: the list states to search for among the service's tasks
:type expected_task_states: [str]
:return: True if expected_task_count tasks have any of expected_task_states, False otherwise
:rtype: bool
"""
try:
tasks = get_service_tasks(service_name)
except (DCOSConnectionError, DCOSHTTPException):
tasks = []
matching_tasks = []
other_tasks = []
for t in tasks:
name = t.get('name', 'UNKNOWN_NAME')
state = t.get('state', None)
if state and state in expected_task_states:
matching_tasks.append(name)
else:
other_tasks.append('{}={}'.format(name, state))
print('expected {} tasks in {}:\n- {} in expected {}: {}\n- {} in other states: {}'.format(
expected_task_count, ', '.join(expected_task_states),
len(matching_tasks), ', '.join(expected_task_states), ', '.join(matching_tasks),
len(other_tasks), ', '.join(other_tasks)))
return len(matching_tasks) >= expected_task_count | [
"def",
"task_states_predicate",
"(",
"service_name",
",",
"expected_task_count",
",",
"expected_task_states",
")",
":",
"try",
":",
"tasks",
"=",
"get_service_tasks",
"(",
"service_name",
")",
"except",
"(",
"DCOSConnectionError",
",",
"DCOSHTTPException",
")",
":",
... | Returns whether the provided service_names's tasks have expected_task_count tasks
in any of expected_task_states. For example, if service 'foo' has 5 tasks which are
TASK_STAGING or TASK_RUNNING.
:param service_name: the service name
:type service_name: str
:param expected_task_count: the number of tasks which should have an expected state
:type expected_task_count: int
:param expected_task_states: the list states to search for among the service's tasks
:type expected_task_states: [str]
:return: True if expected_task_count tasks have any of expected_task_states, False otherwise
:rtype: bool | [
"Returns",
"whether",
"the",
"provided",
"service_names",
"s",
"tasks",
"have",
"expected_task_count",
"tasks",
"in",
"any",
"of",
"expected_task_states",
".",
"For",
"example",
"if",
"service",
"foo",
"has",
"5",
"tasks",
"which",
"are",
"TASK_STAGING",
"or",
"... | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L427-L459 | train | 39,582 |
dcos/shakedown | shakedown/dcos/service.py | tasks_all_replaced_predicate | def tasks_all_replaced_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:return: True if none of old_task_ids are still present in the service
:rtype: bool
"""
try:
task_ids = get_service_task_ids(service_name, task_predicate)
except DCOSHTTPException:
print('failed to get task ids for service {}'.format(service_name))
task_ids = []
print('waiting for all task ids in "{}" to change:\n- old tasks: {}\n- current tasks: {}'.format(
service_name, old_task_ids, task_ids))
for id in task_ids:
if id in old_task_ids:
return False # old task still present
if len(task_ids) < len(old_task_ids): # new tasks haven't fully replaced old tasks
return False
return True | python | def tasks_all_replaced_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:return: True if none of old_task_ids are still present in the service
:rtype: bool
"""
try:
task_ids = get_service_task_ids(service_name, task_predicate)
except DCOSHTTPException:
print('failed to get task ids for service {}'.format(service_name))
task_ids = []
print('waiting for all task ids in "{}" to change:\n- old tasks: {}\n- current tasks: {}'.format(
service_name, old_task_ids, task_ids))
for id in task_ids:
if id in old_task_ids:
return False # old task still present
if len(task_ids) < len(old_task_ids): # new tasks haven't fully replaced old tasks
return False
return True | [
"def",
"tasks_all_replaced_predicate",
"(",
"service_name",
",",
"old_task_ids",
",",
"task_predicate",
"=",
"None",
")",
":",
"try",
":",
"task_ids",
"=",
"get_service_task_ids",
"(",
"service_name",
",",
"task_predicate",
")",
"except",
"DCOSHTTPException",
":",
"... | Returns whether ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:return: True if none of old_task_ids are still present in the service
:rtype: bool | [
"Returns",
"whether",
"ALL",
"of",
"old_task_ids",
"have",
"been",
"replaced",
"with",
"new",
"tasks"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L507-L537 | train | 39,583 |
dcos/shakedown | shakedown/dcos/service.py | tasks_missing_predicate | def tasks_missing_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:return: True if any of old_task_ids are no longer present in the service
:rtype: bool
"""
try:
task_ids = get_service_task_ids(service_name, task_predicate)
except DCOSHTTPException:
print('failed to get task ids for service {}'.format(service_name))
task_ids = []
print('checking whether old tasks in "{}" are missing:\n- old tasks: {}\n- current tasks: {}'.format(
service_name, old_task_ids, task_ids))
for id in old_task_ids:
if id not in task_ids:
return True # an old task was not present
return False | python | def tasks_missing_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:return: True if any of old_task_ids are no longer present in the service
:rtype: bool
"""
try:
task_ids = get_service_task_ids(service_name, task_predicate)
except DCOSHTTPException:
print('failed to get task ids for service {}'.format(service_name))
task_ids = []
print('checking whether old tasks in "{}" are missing:\n- old tasks: {}\n- current tasks: {}'.format(
service_name, old_task_ids, task_ids))
for id in old_task_ids:
if id not in task_ids:
return True # an old task was not present
return False | [
"def",
"tasks_missing_predicate",
"(",
"service_name",
",",
"old_task_ids",
",",
"task_predicate",
"=",
"None",
")",
":",
"try",
":",
"task_ids",
"=",
"get_service_task_ids",
"(",
"service_name",
",",
"task_predicate",
")",
"except",
"DCOSHTTPException",
":",
"print... | Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:return: True if any of old_task_ids are no longer present in the service
:rtype: bool | [
"Returns",
"whether",
"any",
"of",
"old_task_ids",
"are",
"no",
"longer",
"present"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L540-L568 | train | 39,584 |
dcos/shakedown | shakedown/dcos/service.py | wait_for_service_tasks_all_changed | def wait_for_service_tasks_all_changed(
service_name,
old_task_ids,
task_predicate=None,
timeout_sec=120
):
""" Returns once ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:param timeout_sec: duration to wait
:type timeout_sec: int
:return: the duration waited in seconds
:rtype: int
"""
return time_wait(
lambda: tasks_all_replaced_predicate(service_name, old_task_ids, task_predicate),
timeout_seconds=timeout_sec) | python | def wait_for_service_tasks_all_changed(
service_name,
old_task_ids,
task_predicate=None,
timeout_sec=120
):
""" Returns once ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:param timeout_sec: duration to wait
:type timeout_sec: int
:return: the duration waited in seconds
:rtype: int
"""
return time_wait(
lambda: tasks_all_replaced_predicate(service_name, old_task_ids, task_predicate),
timeout_seconds=timeout_sec) | [
"def",
"wait_for_service_tasks_all_changed",
"(",
"service_name",
",",
"old_task_ids",
",",
"task_predicate",
"=",
"None",
",",
"timeout_sec",
"=",
"120",
")",
":",
"return",
"time_wait",
"(",
"lambda",
":",
"tasks_all_replaced_predicate",
"(",
"service_name",
",",
... | Returns once ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:param timeout_sec: duration to wait
:type timeout_sec: int
:return: the duration waited in seconds
:rtype: int | [
"Returns",
"once",
"ALL",
"of",
"old_task_ids",
"have",
"been",
"replaced",
"with",
"new",
"tasks"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L571-L593 | train | 39,585 |
dcos/shakedown | shakedown/dcos/service.py | wait_for_service_tasks_all_unchanged | def wait_for_service_tasks_all_unchanged(
service_name,
old_task_ids,
task_predicate=None,
timeout_sec=30
):
""" Returns after verifying that NONE of old_task_ids have been removed or replaced from the service
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:param timeout_sec: duration to wait until assuming tasks are unchanged
:type timeout_sec: int
:return: the duration waited in seconds (the timeout value)
:rtype: int
"""
try:
time_wait(
lambda: tasks_missing_predicate(service_name, old_task_ids, task_predicate),
timeout_seconds=timeout_sec)
# shouldn't have exited successfully: raise below
except TimeoutExpired:
return timeout_sec # no changes occurred within timeout, as expected
raise DCOSException("One or more of the following tasks were no longer found: {}".format(old_task_ids)) | python | def wait_for_service_tasks_all_unchanged(
service_name,
old_task_ids,
task_predicate=None,
timeout_sec=30
):
""" Returns after verifying that NONE of old_task_ids have been removed or replaced from the service
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:param timeout_sec: duration to wait until assuming tasks are unchanged
:type timeout_sec: int
:return: the duration waited in seconds (the timeout value)
:rtype: int
"""
try:
time_wait(
lambda: tasks_missing_predicate(service_name, old_task_ids, task_predicate),
timeout_seconds=timeout_sec)
# shouldn't have exited successfully: raise below
except TimeoutExpired:
return timeout_sec # no changes occurred within timeout, as expected
raise DCOSException("One or more of the following tasks were no longer found: {}".format(old_task_ids)) | [
"def",
"wait_for_service_tasks_all_unchanged",
"(",
"service_name",
",",
"old_task_ids",
",",
"task_predicate",
"=",
"None",
",",
"timeout_sec",
"=",
"30",
")",
":",
"try",
":",
"time_wait",
"(",
"lambda",
":",
"tasks_missing_predicate",
"(",
"service_name",
",",
... | Returns after verifying that NONE of old_task_ids have been removed or replaced from the service
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:param timeout_sec: duration to wait until assuming tasks are unchanged
:type timeout_sec: int
:return: the duration waited in seconds (the timeout value)
:rtype: int | [
"Returns",
"after",
"verifying",
"that",
"NONE",
"of",
"old_task_ids",
"have",
"been",
"removed",
"or",
"replaced",
"from",
"the",
"service"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L596-L623 | train | 39,586 |
dcos/shakedown | shakedown/dcos/docker.py | distribute_docker_credentials_to_private_agents | def distribute_docker_credentials_to_private_agents(
username,
password,
file_name='docker.tar.gz'):
""" Create and distributes a docker credentials file to all private agents
:param username: docker username
:type username: str
:param password: docker password
:type password: str
:param file_name: credentials file name `docker.tar.gz` by default
:type file_name: str
"""
create_docker_credentials_file(username, password, file_name)
try:
__distribute_docker_credentials_file()
finally:
os.remove(file_name) | python | def distribute_docker_credentials_to_private_agents(
username,
password,
file_name='docker.tar.gz'):
""" Create and distributes a docker credentials file to all private agents
:param username: docker username
:type username: str
:param password: docker password
:type password: str
:param file_name: credentials file name `docker.tar.gz` by default
:type file_name: str
"""
create_docker_credentials_file(username, password, file_name)
try:
__distribute_docker_credentials_file()
finally:
os.remove(file_name) | [
"def",
"distribute_docker_credentials_to_private_agents",
"(",
"username",
",",
"password",
",",
"file_name",
"=",
"'docker.tar.gz'",
")",
":",
"create_docker_credentials_file",
"(",
"username",
",",
"password",
",",
"file_name",
")",
"try",
":",
"__distribute_docker_cred... | Create and distributes a docker credentials file to all private agents
:param username: docker username
:type username: str
:param password: docker password
:type password: str
:param file_name: credentials file name `docker.tar.gz` by default
:type file_name: str | [
"Create",
"and",
"distributes",
"a",
"docker",
"credentials",
"file",
"to",
"all",
"private",
"agents"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/docker.py#L117-L136 | train | 39,587 |
dcos/shakedown | shakedown/dcos/docker.py | prefetch_docker_image_on_private_agents | def prefetch_docker_image_on_private_agents(
image,
timeout=timedelta(minutes=5).total_seconds()):
""" Given a docker image. An app with the image is scale across the private
agents to ensure that the image is prefetched to all nodes.
:param image: docker image name
:type image: str
:param timeout: timeout for deployment wait in secs (default: 5m)
:type password: int
"""
agents = len(shakedown.get_private_agents())
app = {
"id": "/prefetch",
"instances": agents,
"container": {
"type": "DOCKER",
"docker": {"image": image}
},
"cpus": 0.1,
"mem": 128
}
client = marathon.create_client()
client.add_app(app)
shakedown.deployment_wait(timeout)
shakedown.delete_all_apps()
shakedown.deployment_wait(timeout) | python | def prefetch_docker_image_on_private_agents(
image,
timeout=timedelta(minutes=5).total_seconds()):
""" Given a docker image. An app with the image is scale across the private
agents to ensure that the image is prefetched to all nodes.
:param image: docker image name
:type image: str
:param timeout: timeout for deployment wait in secs (default: 5m)
:type password: int
"""
agents = len(shakedown.get_private_agents())
app = {
"id": "/prefetch",
"instances": agents,
"container": {
"type": "DOCKER",
"docker": {"image": image}
},
"cpus": 0.1,
"mem": 128
}
client = marathon.create_client()
client.add_app(app)
shakedown.deployment_wait(timeout)
shakedown.delete_all_apps()
shakedown.deployment_wait(timeout) | [
"def",
"prefetch_docker_image_on_private_agents",
"(",
"image",
",",
"timeout",
"=",
"timedelta",
"(",
"minutes",
"=",
"5",
")",
".",
"total_seconds",
"(",
")",
")",
":",
"agents",
"=",
"len",
"(",
"shakedown",
".",
"get_private_agents",
"(",
")",
")",
"app"... | Given a docker image. An app with the image is scale across the private
agents to ensure that the image is prefetched to all nodes.
:param image: docker image name
:type image: str
:param timeout: timeout for deployment wait in secs (default: 5m)
:type password: int | [
"Given",
"a",
"docker",
"image",
".",
"An",
"app",
"with",
"the",
"image",
"is",
"scale",
"across",
"the",
"private",
"agents",
"to",
"ensure",
"that",
"the",
"image",
"is",
"prefetched",
"to",
"all",
"nodes",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/docker.py#L139-L168 | train | 39,588 |
dcos/shakedown | shakedown/dcos/package.py | _get_options | def _get_options(options_file=None):
""" Read in options_file as JSON.
:param options_file: filename to return
:type options_file: str
:return: options as dictionary
:rtype: dict
"""
if options_file is not None:
with open(options_file, 'r') as opt_file:
options = json.loads(opt_file.read())
else:
options = {}
return options | python | def _get_options(options_file=None):
""" Read in options_file as JSON.
:param options_file: filename to return
:type options_file: str
:return: options as dictionary
:rtype: dict
"""
if options_file is not None:
with open(options_file, 'r') as opt_file:
options = json.loads(opt_file.read())
else:
options = {}
return options | [
"def",
"_get_options",
"(",
"options_file",
"=",
"None",
")",
":",
"if",
"options_file",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"options_file",
",",
"'r'",
")",
"as",
"opt_file",
":",
"options",
"=",
"json",
".",
"loads",
"(",
"opt_file",
".",
... | Read in options_file as JSON.
:param options_file: filename to return
:type options_file: str
:return: options as dictionary
:rtype: dict | [
"Read",
"in",
"options_file",
"as",
"JSON",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/package.py#L10-L25 | train | 39,589 |
dcos/shakedown | shakedown/dcos/package.py | package_installed | def package_installed(package_name, service_name=None):
""" Check whether the package package_name is currently installed.
:param package_name: package name
:type package_name: str
:param service_name: service_name
:type service_name: str
:return: True if installed, False otherwise
:rtype: bool
"""
package_manager = _get_package_manager()
app_installed = len(package_manager.installed_apps(package_name, service_name)) > 0
subcommand_installed = False
for subcmd in package.installed_subcommands():
package_json = subcmd.package_json()
if package_json['name'] == package_name:
subcommand_installed = True
return (app_installed or subcommand_installed) | python | def package_installed(package_name, service_name=None):
""" Check whether the package package_name is currently installed.
:param package_name: package name
:type package_name: str
:param service_name: service_name
:type service_name: str
:return: True if installed, False otherwise
:rtype: bool
"""
package_manager = _get_package_manager()
app_installed = len(package_manager.installed_apps(package_name, service_name)) > 0
subcommand_installed = False
for subcmd in package.installed_subcommands():
package_json = subcmd.package_json()
if package_json['name'] == package_name:
subcommand_installed = True
return (app_installed or subcommand_installed) | [
"def",
"package_installed",
"(",
"package_name",
",",
"service_name",
"=",
"None",
")",
":",
"package_manager",
"=",
"_get_package_manager",
"(",
")",
"app_installed",
"=",
"len",
"(",
"package_manager",
".",
"installed_apps",
"(",
"package_name",
",",
"service_name... | Check whether the package package_name is currently installed.
:param package_name: package name
:type package_name: str
:param service_name: service_name
:type service_name: str
:return: True if installed, False otherwise
:rtype: bool | [
"Check",
"whether",
"the",
"package",
"package_name",
"is",
"currently",
"installed",
"."
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/package.py#L172-L194 | train | 39,590 |
dcos/shakedown | shakedown/dcos/package.py | add_package_repo | def add_package_repo(
repo_name,
repo_url,
index=None,
wait_for_package=None,
expect_prev_version=None):
""" Add a repository to the list of package sources
:param repo_name: name of the repository to add
:type repo_name: str
:param repo_url: location of the repository to add
:type repo_url: str
:param index: index (precedence) for this repository
:type index: int
:param wait_for_package: the package whose version should change after the repo is added
:type wait_for_package: str, or None
:return: True if successful, False otherwise
:rtype: bool
"""
package_manager = _get_package_manager()
if wait_for_package:
prev_version = package_manager.get_package_version(wait_for_package, None)
if not package_manager.add_repo(repo_name, repo_url, index):
return False
if wait_for_package:
try:
spinner.time_wait(lambda: package_version_changed_predicate(package_manager, wait_for_package, prev_version))
except TimeoutExpired:
return False
return True | python | def add_package_repo(
repo_name,
repo_url,
index=None,
wait_for_package=None,
expect_prev_version=None):
""" Add a repository to the list of package sources
:param repo_name: name of the repository to add
:type repo_name: str
:param repo_url: location of the repository to add
:type repo_url: str
:param index: index (precedence) for this repository
:type index: int
:param wait_for_package: the package whose version should change after the repo is added
:type wait_for_package: str, or None
:return: True if successful, False otherwise
:rtype: bool
"""
package_manager = _get_package_manager()
if wait_for_package:
prev_version = package_manager.get_package_version(wait_for_package, None)
if not package_manager.add_repo(repo_name, repo_url, index):
return False
if wait_for_package:
try:
spinner.time_wait(lambda: package_version_changed_predicate(package_manager, wait_for_package, prev_version))
except TimeoutExpired:
return False
return True | [
"def",
"add_package_repo",
"(",
"repo_name",
",",
"repo_url",
",",
"index",
"=",
"None",
",",
"wait_for_package",
"=",
"None",
",",
"expect_prev_version",
"=",
"None",
")",
":",
"package_manager",
"=",
"_get_package_manager",
"(",
")",
"if",
"wait_for_package",
... | Add a repository to the list of package sources
:param repo_name: name of the repository to add
:type repo_name: str
:param repo_url: location of the repository to add
:type repo_url: str
:param index: index (precedence) for this repository
:type index: int
:param wait_for_package: the package whose version should change after the repo is added
:type wait_for_package: str, or None
:return: True if successful, False otherwise
:rtype: bool | [
"Add",
"a",
"repository",
"to",
"the",
"list",
"of",
"package",
"sources"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/package.py#L352-L383 | train | 39,591 |
dcos/shakedown | shakedown/dcos/package.py | remove_package_repo | def remove_package_repo(repo_name, wait_for_package=None):
""" Remove a repository from the list of package sources
:param repo_name: name of the repository to remove
:type repo_name: str
:param wait_for_package: the package whose version should change after the repo is removed
:type wait_for_package: str, or None
:returns: True if successful, False otherwise
:rtype: bool
"""
package_manager = _get_package_manager()
if wait_for_package:
prev_version = package_manager.get_package_version(wait_for_package, None)
if not package_manager.remove_repo(repo_name):
return False
if wait_for_package:
try:
spinner.time_wait(lambda: package_version_changed_predicate(package_manager, wait_for_package, prev_version))
except TimeoutExpired:
return False
return True | python | def remove_package_repo(repo_name, wait_for_package=None):
""" Remove a repository from the list of package sources
:param repo_name: name of the repository to remove
:type repo_name: str
:param wait_for_package: the package whose version should change after the repo is removed
:type wait_for_package: str, or None
:returns: True if successful, False otherwise
:rtype: bool
"""
package_manager = _get_package_manager()
if wait_for_package:
prev_version = package_manager.get_package_version(wait_for_package, None)
if not package_manager.remove_repo(repo_name):
return False
if wait_for_package:
try:
spinner.time_wait(lambda: package_version_changed_predicate(package_manager, wait_for_package, prev_version))
except TimeoutExpired:
return False
return True | [
"def",
"remove_package_repo",
"(",
"repo_name",
",",
"wait_for_package",
"=",
"None",
")",
":",
"package_manager",
"=",
"_get_package_manager",
"(",
")",
"if",
"wait_for_package",
":",
"prev_version",
"=",
"package_manager",
".",
"get_package_version",
"(",
"wait_for_... | Remove a repository from the list of package sources
:param repo_name: name of the repository to remove
:type repo_name: str
:param wait_for_package: the package whose version should change after the repo is removed
:type wait_for_package: str, or None
:returns: True if successful, False otherwise
:rtype: bool | [
"Remove",
"a",
"repository",
"from",
"the",
"list",
"of",
"package",
"sources"
] | e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/package.py#L386-L408 | train | 39,592 |
makinacorpus/landez | landez/sources.py | TileDownloader.tile | def tile(self, z, x, y):
"""
Download the specified tile from `tiles_url`
"""
logger.debug(_("Download tile %s") % ((z, x, y),))
# Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
size = self.tilesize
s = self.tiles_subdomains[(x + y) % len(self.tiles_subdomains)];
try:
url = self.tiles_url.format(**locals())
except KeyError as e:
raise DownloadError(_("Unknown keyword %s in URL") % e)
logger.debug(_("Retrieve tile at %s") % url)
r = DOWNLOAD_RETRIES
sleeptime = 1
while r > 0:
try:
request = requests.get(url, headers=self.headers)
if request.status_code == 200:
return request.content
raise DownloadError(_("Status code : %s, url : %s") % (request.status_code, url))
except requests.exceptions.ConnectionError as e:
logger.debug(_("Download error, retry (%s left). (%s)") % (r, e))
r -= 1
time.sleep(sleeptime)
# progressivly sleep longer to wait for this tile
if (sleeptime <= 10) and (r % 2 == 0):
sleeptime += 1 # increase wait
raise DownloadError(_("Cannot download URL %s") % url) | python | def tile(self, z, x, y):
"""
Download the specified tile from `tiles_url`
"""
logger.debug(_("Download tile %s") % ((z, x, y),))
# Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
size = self.tilesize
s = self.tiles_subdomains[(x + y) % len(self.tiles_subdomains)];
try:
url = self.tiles_url.format(**locals())
except KeyError as e:
raise DownloadError(_("Unknown keyword %s in URL") % e)
logger.debug(_("Retrieve tile at %s") % url)
r = DOWNLOAD_RETRIES
sleeptime = 1
while r > 0:
try:
request = requests.get(url, headers=self.headers)
if request.status_code == 200:
return request.content
raise DownloadError(_("Status code : %s, url : %s") % (request.status_code, url))
except requests.exceptions.ConnectionError as e:
logger.debug(_("Download error, retry (%s left). (%s)") % (r, e))
r -= 1
time.sleep(sleeptime)
# progressivly sleep longer to wait for this tile
if (sleeptime <= 10) and (r % 2 == 0):
sleeptime += 1 # increase wait
raise DownloadError(_("Cannot download URL %s") % url) | [
"def",
"tile",
"(",
"self",
",",
"z",
",",
"x",
",",
"y",
")",
":",
"logger",
".",
"debug",
"(",
"_",
"(",
"\"Download tile %s\"",
")",
"%",
"(",
"(",
"z",
",",
"x",
",",
"y",
")",
",",
")",
")",
"# Render each keyword in URL ({s}, {x}, {y}, {z}, {size... | Download the specified tile from `tiles_url` | [
"Download",
"the",
"specified",
"tile",
"from",
"tiles_url"
] | 6e5c71ded6071158e7943df204cd7bd1ed623a30 | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/sources.py#L163-L192 | train | 39,593 |
makinacorpus/landez | landez/proj.py | GoogleProjection.project | def project(self, lng_lat):
"""
Returns the coordinates in meters from WGS84
"""
(lng, lat) = lng_lat
x = lng * DEG_TO_RAD
lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE)
y = lat * DEG_TO_RAD
y = log(tan((pi / 4) + (y / 2)))
return (x*EARTH_RADIUS, y*EARTH_RADIUS) | python | def project(self, lng_lat):
"""
Returns the coordinates in meters from WGS84
"""
(lng, lat) = lng_lat
x = lng * DEG_TO_RAD
lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE)
y = lat * DEG_TO_RAD
y = log(tan((pi / 4) + (y / 2)))
return (x*EARTH_RADIUS, y*EARTH_RADIUS) | [
"def",
"project",
"(",
"self",
",",
"lng_lat",
")",
":",
"(",
"lng",
",",
"lat",
")",
"=",
"lng_lat",
"x",
"=",
"lng",
"*",
"DEG_TO_RAD",
"lat",
"=",
"max",
"(",
"min",
"(",
"MAX_LATITUDE",
",",
"lat",
")",
",",
"-",
"MAX_LATITUDE",
")",
"y",
"="... | Returns the coordinates in meters from WGS84 | [
"Returns",
"the",
"coordinates",
"in",
"meters",
"from",
"WGS84"
] | 6e5c71ded6071158e7943df204cd7bd1ed623a30 | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/proj.py#L84-L93 | train | 39,594 |
makinacorpus/landez | landez/tiles.py | TilesManager.add_filter | def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_) | python | def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_) | [
"def",
"add_filter",
"(",
"self",
",",
"filter_",
")",
":",
"assert",
"has_pil",
",",
"_",
"(",
"\"Cannot add filters without python PIL\"",
")",
"self",
".",
"cache",
".",
"basename",
"+=",
"filter_",
".",
"basename",
"self",
".",
"_filters",
".",
"append",
... | Add an image filter for post-processing | [
"Add",
"an",
"image",
"filter",
"for",
"post",
"-",
"processing"
] | 6e5c71ded6071158e7943df204cd7bd1ed623a30 | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L158-L162 | train | 39,595 |
makinacorpus/landez | landez/tiles.py | TilesManager.grid | def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content | python | def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content | [
"def",
"grid",
"(",
"self",
",",
"z_x_y",
")",
":",
"# sources.py -> MapnikRenderer -> grid",
"(",
"z",
",",
"x",
",",
"y",
")",
"=",
"z_x_y",
"content",
"=",
"self",
".",
"reader",
".",
"grid",
"(",
"z",
",",
"x",
",",
"y",
",",
"self",
".",
"grid... | Return the UTFGrid content | [
"Return",
"the",
"UTFGrid",
"content"
] | 6e5c71ded6071158e7943df204cd7bd1ed623a30 | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L188-L193 | train | 39,596 |
makinacorpus/landez | landez/tiles.py | TilesManager._blend_layers | def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result) | python | def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result) | [
"def",
"_blend_layers",
"(",
"self",
",",
"imagecontent",
",",
"z_x_y",
")",
":",
"(",
"z",
",",
"x",
",",
"y",
")",
"=",
"z_x_y",
"result",
"=",
"self",
".",
"_tile_image",
"(",
"imagecontent",
")",
"# Paste each layer",
"for",
"(",
"layer",
",",
"opa... | Merge tiles of all layers into the specified tile path | [
"Merge",
"tiles",
"of",
"all",
"layers",
"into",
"the",
"specified",
"tile",
"path"
] | 6e5c71ded6071158e7943df204cd7bd1ed623a30 | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L196-L219 | train | 39,597 |
makinacorpus/landez | landez/tiles.py | TilesManager._tile_image | def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA') | python | def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA') | [
"def",
"_tile_image",
"(",
"self",
",",
"data",
")",
":",
"image",
"=",
"Image",
".",
"open",
"(",
"BytesIO",
"(",
"data",
")",
")",
"return",
"image",
".",
"convert",
"(",
"'RGBA'",
")"
] | Tile binary content as PIL Image. | [
"Tile",
"binary",
"content",
"as",
"PIL",
"Image",
"."
] | 6e5c71ded6071158e7943df204cd7bd1ed623a30 | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L221-L226 | train | 39,598 |
makinacorpus/landez | landez/tiles.py | MBTilesBuilder.zoomlevels | def zoomlevels(self):
"""
Return the list of covered zoom levels, in ascending order
"""
zooms = set()
for coverage in self._bboxes:
for zoom in coverage[1]:
zooms.add(zoom)
return sorted(zooms) | python | def zoomlevels(self):
"""
Return the list of covered zoom levels, in ascending order
"""
zooms = set()
for coverage in self._bboxes:
for zoom in coverage[1]:
zooms.add(zoom)
return sorted(zooms) | [
"def",
"zoomlevels",
"(",
"self",
")",
":",
"zooms",
"=",
"set",
"(",
")",
"for",
"coverage",
"in",
"self",
".",
"_bboxes",
":",
"for",
"zoom",
"in",
"coverage",
"[",
"1",
"]",
":",
"zooms",
".",
"add",
"(",
"zoom",
")",
"return",
"sorted",
"(",
... | Return the list of covered zoom levels, in ascending order | [
"Return",
"the",
"list",
"of",
"covered",
"zoom",
"levels",
"in",
"ascending",
"order"
] | 6e5c71ded6071158e7943df204cd7bd1ed623a30 | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L263-L271 | train | 39,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.