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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.get_reference_fields | def get_reference_fields(self, exclude_models=None):
"""
Get all Django model fields which reference the Item model.
"""
if exclude_models is None:
exclude_models = []
result = []
for django_model in django.apps.apps.get_models():
if any([issubclass(django_model, m) for m in exclude_models]):
continue
for django_field in django_model._meta.fields:
if isinstance(django_field, models.ForeignKey) and django_field.related.to == Item:
result = [(m, f) for (m, f) in result if not issubclass(django_model, m)]
result.append((django_model, django_field))
return result | python | def get_reference_fields(self, exclude_models=None):
"""
Get all Django model fields which reference the Item model.
"""
if exclude_models is None:
exclude_models = []
result = []
for django_model in django.apps.apps.get_models():
if any([issubclass(django_model, m) for m in exclude_models]):
continue
for django_field in django_model._meta.fields:
if isinstance(django_field, models.ForeignKey) and django_field.related.to == Item:
result = [(m, f) for (m, f) in result if not issubclass(django_model, m)]
result.append((django_model, django_field))
return result | [
"def",
"get_reference_fields",
"(",
"self",
",",
"exclude_models",
"=",
"None",
")",
":",
"if",
"exclude_models",
"is",
"None",
":",
"exclude_models",
"=",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"django_model",
"in",
"django",
".",
"apps",
".",
"apps",
".",
"get_models",
"(",
")",
":",
"if",
"any",
"(",
"[",
"issubclass",
"(",
"django_model",
",",
"m",
")",
"for",
"m",
"in",
"exclude_models",
"]",
")",
":",
"continue",
"for",
"django_field",
"in",
"django_model",
".",
"_meta",
".",
"fields",
":",
"if",
"isinstance",
"(",
"django_field",
",",
"models",
".",
"ForeignKey",
")",
"and",
"django_field",
".",
"related",
".",
"to",
"==",
"Item",
":",
"result",
"=",
"[",
"(",
"m",
",",
"f",
")",
"for",
"(",
"m",
",",
"f",
")",
"in",
"result",
"if",
"not",
"issubclass",
"(",
"django_model",
",",
"m",
")",
"]",
"result",
".",
"append",
"(",
"(",
"django_model",
",",
"django_field",
")",
")",
"return",
"result"
]
| Get all Django model fields which reference the Item model. | [
"Get",
"all",
"Django",
"model",
"fields",
"which",
"reference",
"the",
"Item",
"model",
"."
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L712-L726 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.override_parent_subgraph | def override_parent_subgraph(self, parent_subgraph, invisible_edges=None):
"""
Get all items with outcoming edges from the given subgraph, drop all
their parent relations, and then add parents according to the given
subgraph.
Args:
parent_subgraph (dict): item id -> list of parents(item ids)
invisible_edges (list|set): set of (from, to) tuples specifying
invisible edges
"""
with transaction.atomic():
if invisible_edges is None:
invisible_edges = set()
children = list(parent_subgraph.keys())
all_old_relations = dict(proso.list.group_by(
list(ItemRelation.objects.filter(child_id__in=children)),
by=lambda relation: relation.child_id
))
to_delete = set()
for child_id, parents in parent_subgraph.items():
old_relations = {
relation.parent_id: relation
for relation in all_old_relations.get(child_id, [])
}
for parent_id in parents:
if parent_id not in old_relations:
ItemRelation.objects.create(
parent_id=parent_id,
child_id=child_id,
visible=(child_id, parent_id) not in invisible_edges
)
elif old_relations[parent_id].visible != ((child_id, parent_id) not in invisible_edges):
old_relations[parent_id].visible = (child_id, parent_id) not in invisible_edges
old_relations[parent_id].save()
to_delete |= {old_relations[parent_id].pk for parent_id in set(old_relations.keys()) - set(parents)}
ItemRelation.objects.filter(pk__in=to_delete).delete() | python | def override_parent_subgraph(self, parent_subgraph, invisible_edges=None):
"""
Get all items with outcoming edges from the given subgraph, drop all
their parent relations, and then add parents according to the given
subgraph.
Args:
parent_subgraph (dict): item id -> list of parents(item ids)
invisible_edges (list|set): set of (from, to) tuples specifying
invisible edges
"""
with transaction.atomic():
if invisible_edges is None:
invisible_edges = set()
children = list(parent_subgraph.keys())
all_old_relations = dict(proso.list.group_by(
list(ItemRelation.objects.filter(child_id__in=children)),
by=lambda relation: relation.child_id
))
to_delete = set()
for child_id, parents in parent_subgraph.items():
old_relations = {
relation.parent_id: relation
for relation in all_old_relations.get(child_id, [])
}
for parent_id in parents:
if parent_id not in old_relations:
ItemRelation.objects.create(
parent_id=parent_id,
child_id=child_id,
visible=(child_id, parent_id) not in invisible_edges
)
elif old_relations[parent_id].visible != ((child_id, parent_id) not in invisible_edges):
old_relations[parent_id].visible = (child_id, parent_id) not in invisible_edges
old_relations[parent_id].save()
to_delete |= {old_relations[parent_id].pk for parent_id in set(old_relations.keys()) - set(parents)}
ItemRelation.objects.filter(pk__in=to_delete).delete() | [
"def",
"override_parent_subgraph",
"(",
"self",
",",
"parent_subgraph",
",",
"invisible_edges",
"=",
"None",
")",
":",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"if",
"invisible_edges",
"is",
"None",
":",
"invisible_edges",
"=",
"set",
"(",
")",
"children",
"=",
"list",
"(",
"parent_subgraph",
".",
"keys",
"(",
")",
")",
"all_old_relations",
"=",
"dict",
"(",
"proso",
".",
"list",
".",
"group_by",
"(",
"list",
"(",
"ItemRelation",
".",
"objects",
".",
"filter",
"(",
"child_id__in",
"=",
"children",
")",
")",
",",
"by",
"=",
"lambda",
"relation",
":",
"relation",
".",
"child_id",
")",
")",
"to_delete",
"=",
"set",
"(",
")",
"for",
"child_id",
",",
"parents",
"in",
"parent_subgraph",
".",
"items",
"(",
")",
":",
"old_relations",
"=",
"{",
"relation",
".",
"parent_id",
":",
"relation",
"for",
"relation",
"in",
"all_old_relations",
".",
"get",
"(",
"child_id",
",",
"[",
"]",
")",
"}",
"for",
"parent_id",
"in",
"parents",
":",
"if",
"parent_id",
"not",
"in",
"old_relations",
":",
"ItemRelation",
".",
"objects",
".",
"create",
"(",
"parent_id",
"=",
"parent_id",
",",
"child_id",
"=",
"child_id",
",",
"visible",
"=",
"(",
"child_id",
",",
"parent_id",
")",
"not",
"in",
"invisible_edges",
")",
"elif",
"old_relations",
"[",
"parent_id",
"]",
".",
"visible",
"!=",
"(",
"(",
"child_id",
",",
"parent_id",
")",
"not",
"in",
"invisible_edges",
")",
":",
"old_relations",
"[",
"parent_id",
"]",
".",
"visible",
"=",
"(",
"child_id",
",",
"parent_id",
")",
"not",
"in",
"invisible_edges",
"old_relations",
"[",
"parent_id",
"]",
".",
"save",
"(",
")",
"to_delete",
"|=",
"{",
"old_relations",
"[",
"parent_id",
"]",
".",
"pk",
"for",
"parent_id",
"in",
"set",
"(",
"old_relations",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"parents",
")",
"}",
"ItemRelation",
".",
"objects",
".",
"filter",
"(",
"pk__in",
"=",
"to_delete",
")",
".",
"delete",
"(",
")"
]
| Get all items with outcoming edges from the given subgraph, drop all
their parent relations, and then add parents according to the given
subgraph.
Args:
parent_subgraph (dict): item id -> list of parents(item ids)
invisible_edges (list|set): set of (from, to) tuples specifying
invisible edges | [
"Get",
"all",
"items",
"with",
"outcoming",
"edges",
"from",
"the",
"given",
"subgraph",
"drop",
"all",
"their",
"parent",
"relations",
"and",
"then",
"add",
"parents",
"according",
"to",
"the",
"given",
"subgraph",
"."
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L728-L764 | train |
46elks/elkme | elkme/elks.py | Elks.query_api | def query_api(self, data=None, endpoint='SMS'):
""" Send a request to the 46elks API.
Fetches SMS history as JSON by default, sends a HTTP POST request
with the incoming data dictionary as a urlencoded query if data is
provided, otherwise HTTP GET
Throws HTTPError on non 2xx
"""
url = self.api_url % endpoint
if data:
response = requests.post(
url,
data=data,
auth=self.auth
)
else:
response = requests.get(
url,
auth=self.auth
)
try:
response.raise_for_status()
except HTTPError as e:
raise HTTPError('HTTP %s\n%s' %
(response.status_code, response.text))
return response.text | python | def query_api(self, data=None, endpoint='SMS'):
""" Send a request to the 46elks API.
Fetches SMS history as JSON by default, sends a HTTP POST request
with the incoming data dictionary as a urlencoded query if data is
provided, otherwise HTTP GET
Throws HTTPError on non 2xx
"""
url = self.api_url % endpoint
if data:
response = requests.post(
url,
data=data,
auth=self.auth
)
else:
response = requests.get(
url,
auth=self.auth
)
try:
response.raise_for_status()
except HTTPError as e:
raise HTTPError('HTTP %s\n%s' %
(response.status_code, response.text))
return response.text | [
"def",
"query_api",
"(",
"self",
",",
"data",
"=",
"None",
",",
"endpoint",
"=",
"'SMS'",
")",
":",
"url",
"=",
"self",
".",
"api_url",
"%",
"endpoint",
"if",
"data",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"else",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"try",
":",
"response",
".",
"raise_for_status",
"(",
")",
"except",
"HTTPError",
"as",
"e",
":",
"raise",
"HTTPError",
"(",
"'HTTP %s\\n%s'",
"%",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"text",
")",
")",
"return",
"response",
".",
"text"
]
| Send a request to the 46elks API.
Fetches SMS history as JSON by default, sends a HTTP POST request
with the incoming data dictionary as a urlencoded query if data is
provided, otherwise HTTP GET
Throws HTTPError on non 2xx | [
"Send",
"a",
"request",
"to",
"the",
"46elks",
"API",
".",
"Fetches",
"SMS",
"history",
"as",
"JSON",
"by",
"default",
"sends",
"a",
"HTTP",
"POST",
"request",
"with",
"the",
"incoming",
"data",
"dictionary",
"as",
"a",
"urlencoded",
"query",
"if",
"data",
"is",
"provided",
"otherwise",
"HTTP",
"GET"
]
| 6ebdce6f8ac852fc6f714d1f1b836f2777fece4e | https://github.com/46elks/elkme/blob/6ebdce6f8ac852fc6f714d1f1b836f2777fece4e/elkme/elks.py#L33-L58 | train |
46elks/elkme | elkme/elks.py | Elks.validate_number | def validate_number(self, number):
""" Checks if a number looks somewhat like a E.164 number. Not an
exhaustive check, as the API takes care of that
"""
if not isinstance(number, str):
raise ElksException('Recipient phone number may not be empty')
if number[0] == '+' and len(number) > 2 and len(number) < 16:
return True
else:
raise ElksException("Phone number must be of format +CCCXXX...") | python | def validate_number(self, number):
""" Checks if a number looks somewhat like a E.164 number. Not an
exhaustive check, as the API takes care of that
"""
if not isinstance(number, str):
raise ElksException('Recipient phone number may not be empty')
if number[0] == '+' and len(number) > 2 and len(number) < 16:
return True
else:
raise ElksException("Phone number must be of format +CCCXXX...") | [
"def",
"validate_number",
"(",
"self",
",",
"number",
")",
":",
"if",
"not",
"isinstance",
"(",
"number",
",",
"str",
")",
":",
"raise",
"ElksException",
"(",
"'Recipient phone number may not be empty'",
")",
"if",
"number",
"[",
"0",
"]",
"==",
"'+'",
"and",
"len",
"(",
"number",
")",
">",
"2",
"and",
"len",
"(",
"number",
")",
"<",
"16",
":",
"return",
"True",
"else",
":",
"raise",
"ElksException",
"(",
"\"Phone number must be of format +CCCXXX...\"",
")"
]
| Checks if a number looks somewhat like a E.164 number. Not an
exhaustive check, as the API takes care of that | [
"Checks",
"if",
"a",
"number",
"looks",
"somewhat",
"like",
"a",
"E",
".",
"164",
"number",
".",
"Not",
"an",
"exhaustive",
"check",
"as",
"the",
"API",
"takes",
"care",
"of",
"that"
]
| 6ebdce6f8ac852fc6f714d1f1b836f2777fece4e | https://github.com/46elks/elkme/blob/6ebdce6f8ac852fc6f714d1f1b836f2777fece4e/elkme/elks.py#L61-L70 | train |
46elks/elkme | elkme/elks.py | Elks.format_sms_payload | def format_sms_payload(self, message, to, sender='elkme', options=[]):
""" Helper function to create a SMS payload with little effort
"""
self.validate_number(to)
if not isinstance(message, str):
message = " ".join(message)
message = message.rstrip()
sms = {
'from': sender,
'to': to,
'message': message
}
for option in options:
if option not in ['dontlog', 'dryrun', 'flashsms']:
raise ElksException('Option %s not supported' % option)
sms[option] = 'yes'
return sms | python | def format_sms_payload(self, message, to, sender='elkme', options=[]):
""" Helper function to create a SMS payload with little effort
"""
self.validate_number(to)
if not isinstance(message, str):
message = " ".join(message)
message = message.rstrip()
sms = {
'from': sender,
'to': to,
'message': message
}
for option in options:
if option not in ['dontlog', 'dryrun', 'flashsms']:
raise ElksException('Option %s not supported' % option)
sms[option] = 'yes'
return sms | [
"def",
"format_sms_payload",
"(",
"self",
",",
"message",
",",
"to",
",",
"sender",
"=",
"'elkme'",
",",
"options",
"=",
"[",
"]",
")",
":",
"self",
".",
"validate_number",
"(",
"to",
")",
"if",
"not",
"isinstance",
"(",
"message",
",",
"str",
")",
":",
"message",
"=",
"\" \"",
".",
"join",
"(",
"message",
")",
"message",
"=",
"message",
".",
"rstrip",
"(",
")",
"sms",
"=",
"{",
"'from'",
":",
"sender",
",",
"'to'",
":",
"to",
",",
"'message'",
":",
"message",
"}",
"for",
"option",
"in",
"options",
":",
"if",
"option",
"not",
"in",
"[",
"'dontlog'",
",",
"'dryrun'",
",",
"'flashsms'",
"]",
":",
"raise",
"ElksException",
"(",
"'Option %s not supported'",
"%",
"option",
")",
"sms",
"[",
"option",
"]",
"=",
"'yes'",
"return",
"sms"
]
| Helper function to create a SMS payload with little effort | [
"Helper",
"function",
"to",
"create",
"a",
"SMS",
"payload",
"with",
"little",
"effort"
]
| 6ebdce6f8ac852fc6f714d1f1b836f2777fece4e | https://github.com/46elks/elkme/blob/6ebdce6f8ac852fc6f714d1f1b836f2777fece4e/elkme/elks.py#L73-L94 | train |
46elks/elkme | elkme/elks.py | Elks.send_sms | def send_sms(self, message, to, sender='elkme', options=[]):
"""Sends a text message to a configuration conf containing the message
in the message paramter"""
sms = self.format_sms_payload(message=message,
to=to,
sender=sender,
options=options)
return self.query_api(sms) | python | def send_sms(self, message, to, sender='elkme', options=[]):
"""Sends a text message to a configuration conf containing the message
in the message paramter"""
sms = self.format_sms_payload(message=message,
to=to,
sender=sender,
options=options)
return self.query_api(sms) | [
"def",
"send_sms",
"(",
"self",
",",
"message",
",",
"to",
",",
"sender",
"=",
"'elkme'",
",",
"options",
"=",
"[",
"]",
")",
":",
"sms",
"=",
"self",
".",
"format_sms_payload",
"(",
"message",
"=",
"message",
",",
"to",
"=",
"to",
",",
"sender",
"=",
"sender",
",",
"options",
"=",
"options",
")",
"return",
"self",
".",
"query_api",
"(",
"sms",
")"
]
| Sends a text message to a configuration conf containing the message
in the message paramter | [
"Sends",
"a",
"text",
"message",
"to",
"a",
"configuration",
"conf",
"containing",
"the",
"message",
"in",
"the",
"message",
"paramter"
]
| 6ebdce6f8ac852fc6f714d1f1b836f2777fece4e | https://github.com/46elks/elkme/blob/6ebdce6f8ac852fc6f714d1f1b836f2777fece4e/elkme/elks.py#L96-L103 | train |
Desiiii/weeb.py | weeb/client.py | Client.get_types | async def get_types(self):
"""Gets all available types.
This function is a coroutine.
Return Type: `list`"""
async with aiohttp.ClientSession() as session:
async with session.get('https://api.weeb.sh/images/types', headers=self.__headers) as resp:
if resp.status == 200:
return (await resp.json())['types']
else:
raise Exception((await resp.json())['message']) | python | async def get_types(self):
"""Gets all available types.
This function is a coroutine.
Return Type: `list`"""
async with aiohttp.ClientSession() as session:
async with session.get('https://api.weeb.sh/images/types', headers=self.__headers) as resp:
if resp.status == 200:
return (await resp.json())['types']
else:
raise Exception((await resp.json())['message']) | [
"async",
"def",
"get_types",
"(",
"self",
")",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"async",
"with",
"session",
".",
"get",
"(",
"'https://api.weeb.sh/images/types'",
",",
"headers",
"=",
"self",
".",
"__headers",
")",
"as",
"resp",
":",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"return",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'types'",
"]",
"else",
":",
"raise",
"Exception",
"(",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'message'",
"]",
")"
]
| Gets all available types.
This function is a coroutine.
Return Type: `list` | [
"Gets",
"all",
"available",
"types",
"."
]
| 5174c22e0cd34cb77f69ad18fbe87ee1fad51859 | https://github.com/Desiiii/weeb.py/blob/5174c22e0cd34cb77f69ad18fbe87ee1fad51859/weeb/client.py#L18-L29 | train |
Desiiii/weeb.py | weeb/client.py | Client.get_image | async def get_image(self, imgtype=None, tags=None, nsfw=None, hidden=None, filetype=None):
"""Request an image from weeb.sh.
This function is a coroutine.
Parameters:
imgtype: str - the type of image to get. (If not specified, needs at least one tag)
tags: list - the tags to search by. (If not specified, needs type)
nsfw: str - whether or not the images recieved are nsfw. (Optional)
hidden: bool - whether you only get public images or hidden images uploaded by yourself. (If not specified, both are supplied)
filetype: str - the file type to get. Supported are jpg,jpeg,png,gif. (If not specified, all filetypes are grabbed)
Return Type: `list` (returns as [url, id, filetype])"""
if not imgtype and not tags:
raise MissingTypeOrTags("'get_image' requires at least one of either type or tags.")
if imgtype and not isinstance(imgtype, str):
raise TypeError("type of 'imgtype' must be str.")
if tags and not isinstance(tags, list):
raise TypeError("type of 'tags' must be list or None.")
if hidden and not isinstance(hidden, bool):
raise TypeError("type of 'hidden' must be bool or None.")
if nsfw and not isinstance(nsfw, bool) and (isinstance(nsfw, str) and nsfw == 'only'):
raise TypeError("type of 'nsfw' must be str, bool or None.")
if filetype and not isinstance(filetype, str):
raise TypeError("type of 'filetype' must be str.")
url = 'https://api.weeb.sh/images/random' + (f'?type={imgtype}' if imgtype else '') + (
f'{"?" if not imgtype else "&"}tags={",".join(tags)}' if tags else '') + (
f'&nsfw={nsfw.lower()}' if nsfw else '') + (f'&hidden={hidden}' if hidden else '') + (
f'&filetype={filetype}' if filetype else '')
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.__headers) as resp:
if resp.status == 200:
js = await resp.json()
return [js['url'], js['id'], js['fileType']]
else:
raise Exception((await resp.json())['message']) | python | async def get_image(self, imgtype=None, tags=None, nsfw=None, hidden=None, filetype=None):
"""Request an image from weeb.sh.
This function is a coroutine.
Parameters:
imgtype: str - the type of image to get. (If not specified, needs at least one tag)
tags: list - the tags to search by. (If not specified, needs type)
nsfw: str - whether or not the images recieved are nsfw. (Optional)
hidden: bool - whether you only get public images or hidden images uploaded by yourself. (If not specified, both are supplied)
filetype: str - the file type to get. Supported are jpg,jpeg,png,gif. (If not specified, all filetypes are grabbed)
Return Type: `list` (returns as [url, id, filetype])"""
if not imgtype and not tags:
raise MissingTypeOrTags("'get_image' requires at least one of either type or tags.")
if imgtype and not isinstance(imgtype, str):
raise TypeError("type of 'imgtype' must be str.")
if tags and not isinstance(tags, list):
raise TypeError("type of 'tags' must be list or None.")
if hidden and not isinstance(hidden, bool):
raise TypeError("type of 'hidden' must be bool or None.")
if nsfw and not isinstance(nsfw, bool) and (isinstance(nsfw, str) and nsfw == 'only'):
raise TypeError("type of 'nsfw' must be str, bool or None.")
if filetype and not isinstance(filetype, str):
raise TypeError("type of 'filetype' must be str.")
url = 'https://api.weeb.sh/images/random' + (f'?type={imgtype}' if imgtype else '') + (
f'{"?" if not imgtype else "&"}tags={",".join(tags)}' if tags else '') + (
f'&nsfw={nsfw.lower()}' if nsfw else '') + (f'&hidden={hidden}' if hidden else '') + (
f'&filetype={filetype}' if filetype else '')
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.__headers) as resp:
if resp.status == 200:
js = await resp.json()
return [js['url'], js['id'], js['fileType']]
else:
raise Exception((await resp.json())['message']) | [
"async",
"def",
"get_image",
"(",
"self",
",",
"imgtype",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"nsfw",
"=",
"None",
",",
"hidden",
"=",
"None",
",",
"filetype",
"=",
"None",
")",
":",
"if",
"not",
"imgtype",
"and",
"not",
"tags",
":",
"raise",
"MissingTypeOrTags",
"(",
"\"'get_image' requires at least one of either type or tags.\"",
")",
"if",
"imgtype",
"and",
"not",
"isinstance",
"(",
"imgtype",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'imgtype' must be str.\"",
")",
"if",
"tags",
"and",
"not",
"isinstance",
"(",
"tags",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'tags' must be list or None.\"",
")",
"if",
"hidden",
"and",
"not",
"isinstance",
"(",
"hidden",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'hidden' must be bool or None.\"",
")",
"if",
"nsfw",
"and",
"not",
"isinstance",
"(",
"nsfw",
",",
"bool",
")",
"and",
"(",
"isinstance",
"(",
"nsfw",
",",
"str",
")",
"and",
"nsfw",
"==",
"'only'",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'nsfw' must be str, bool or None.\"",
")",
"if",
"filetype",
"and",
"not",
"isinstance",
"(",
"filetype",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'filetype' must be str.\"",
")",
"url",
"=",
"'https://api.weeb.sh/images/random'",
"+",
"(",
"f'?type={imgtype}'",
"if",
"imgtype",
"else",
"''",
")",
"+",
"(",
"f'{\"?\" if not imgtype else \"&\"}tags={\",\".join(tags)}'",
"if",
"tags",
"else",
"''",
")",
"+",
"(",
"f'&nsfw={nsfw.lower()}'",
"if",
"nsfw",
"else",
"''",
")",
"+",
"(",
"f'&hidden={hidden}'",
"if",
"hidden",
"else",
"''",
")",
"+",
"(",
"f'&filetype={filetype}'",
"if",
"filetype",
"else",
"''",
")",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"async",
"with",
"session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"__headers",
")",
"as",
"resp",
":",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"js",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"return",
"[",
"js",
"[",
"'url'",
"]",
",",
"js",
"[",
"'id'",
"]",
",",
"js",
"[",
"'fileType'",
"]",
"]",
"else",
":",
"raise",
"Exception",
"(",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'message'",
"]",
")"
]
| Request an image from weeb.sh.
This function is a coroutine.
Parameters:
imgtype: str - the type of image to get. (If not specified, needs at least one tag)
tags: list - the tags to search by. (If not specified, needs type)
nsfw: str - whether or not the images recieved are nsfw. (Optional)
hidden: bool - whether you only get public images or hidden images uploaded by yourself. (If not specified, both are supplied)
filetype: str - the file type to get. Supported are jpg,jpeg,png,gif. (If not specified, all filetypes are grabbed)
Return Type: `list` (returns as [url, id, filetype]) | [
"Request",
"an",
"image",
"from",
"weeb",
".",
"sh",
"."
]
| 5174c22e0cd34cb77f69ad18fbe87ee1fad51859 | https://github.com/Desiiii/weeb.py/blob/5174c22e0cd34cb77f69ad18fbe87ee1fad51859/weeb/client.py#L44-L79 | train |
Desiiii/weeb.py | weeb/client.py | Client.generate_image | async def generate_image(self, imgtype, face=None, hair=None):
"""Generate a basic image using the auto-image endpoint of weeb.sh.
This function is a coroutine.
Parameters:
imgtype: str - type of the generation to create, possible types are awooo, eyes, or won.
face: str - only used with awooo type, defines color of face
hair: str - only used with awooo type, defines color of hair/fur
Return Type: image data"""
if not isinstance(imgtype, str):
raise TypeError("type of 'imgtype' must be str.")
if face and not isinstance(face, str):
raise TypeError("type of 'face' must be str.")
if hair and not isinstance(hair, str):
raise TypeError("type of 'hair' must be str.")
if (face or hair) and imgtype != 'awooo':
raise InvalidArguments('\'face\' and \'hair\' are arguments only available on the \'awoo\' image type')
url = f'https://api.weeb.sh/auto-image/generate?type={imgtype}' + ("&face="+face if face else "")+ ("&hair="+hair if hair else "")
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.__headers) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | python | async def generate_image(self, imgtype, face=None, hair=None):
"""Generate a basic image using the auto-image endpoint of weeb.sh.
This function is a coroutine.
Parameters:
imgtype: str - type of the generation to create, possible types are awooo, eyes, or won.
face: str - only used with awooo type, defines color of face
hair: str - only used with awooo type, defines color of hair/fur
Return Type: image data"""
if not isinstance(imgtype, str):
raise TypeError("type of 'imgtype' must be str.")
if face and not isinstance(face, str):
raise TypeError("type of 'face' must be str.")
if hair and not isinstance(hair, str):
raise TypeError("type of 'hair' must be str.")
if (face or hair) and imgtype != 'awooo':
raise InvalidArguments('\'face\' and \'hair\' are arguments only available on the \'awoo\' image type')
url = f'https://api.weeb.sh/auto-image/generate?type={imgtype}' + ("&face="+face if face else "")+ ("&hair="+hair if hair else "")
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.__headers) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | [
"async",
"def",
"generate_image",
"(",
"self",
",",
"imgtype",
",",
"face",
"=",
"None",
",",
"hair",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"imgtype",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'imgtype' must be str.\"",
")",
"if",
"face",
"and",
"not",
"isinstance",
"(",
"face",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'face' must be str.\"",
")",
"if",
"hair",
"and",
"not",
"isinstance",
"(",
"hair",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'hair' must be str.\"",
")",
"if",
"(",
"face",
"or",
"hair",
")",
"and",
"imgtype",
"!=",
"'awooo'",
":",
"raise",
"InvalidArguments",
"(",
"'\\'face\\' and \\'hair\\' are arguments only available on the \\'awoo\\' image type'",
")",
"url",
"=",
"f'https://api.weeb.sh/auto-image/generate?type={imgtype}'",
"+",
"(",
"\"&face=\"",
"+",
"face",
"if",
"face",
"else",
"\"\"",
")",
"+",
"(",
"\"&hair=\"",
"+",
"hair",
"if",
"hair",
"else",
"\"\"",
")",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"async",
"with",
"session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"__headers",
")",
"as",
"resp",
":",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"return",
"await",
"resp",
".",
"read",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'message'",
"]",
")"
]
| Generate a basic image using the auto-image endpoint of weeb.sh.
This function is a coroutine.
Parameters:
imgtype: str - type of the generation to create, possible types are awooo, eyes, or won.
face: str - only used with awooo type, defines color of face
hair: str - only used with awooo type, defines color of hair/fur
Return Type: image data | [
"Generate",
"a",
"basic",
"image",
"using",
"the",
"auto",
"-",
"image",
"endpoint",
"of",
"weeb",
".",
"sh",
"."
]
| 5174c22e0cd34cb77f69ad18fbe87ee1fad51859 | https://github.com/Desiiii/weeb.py/blob/5174c22e0cd34cb77f69ad18fbe87ee1fad51859/weeb/client.py#L81-L106 | train |
Desiiii/weeb.py | weeb/client.py | Client.generate_status | async def generate_status(self, status, avatar=None):
"""Generate a discord status icon below the image provided.
This function is a coroutine.
Parameters:
status: str - a discord status, must be online, idle, dnd, or streaming
avatar: str - http/s url pointing to an avatar, has to have proper headers and be a direct link to an image
(Note, this url is encoded by the wrapper itself, so you don't have to worry about encoding it ;))
Return Type: image data"""
if not isinstance(status, str):
raise TypeError("type of 'status' must be str.")
if avatar and not isinstance(avatar, str):
raise TypeError("type of 'avatar' must be str.")
url = f'https://api.weeb.sh/auto-image/discord-status?status={status}' + (f'&avatar={urllib.parse.quote(avatar, safe="")}' if avatar else '')
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.__headers) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | python | async def generate_status(self, status, avatar=None):
"""Generate a discord status icon below the image provided.
This function is a coroutine.
Parameters:
status: str - a discord status, must be online, idle, dnd, or streaming
avatar: str - http/s url pointing to an avatar, has to have proper headers and be a direct link to an image
(Note, this url is encoded by the wrapper itself, so you don't have to worry about encoding it ;))
Return Type: image data"""
if not isinstance(status, str):
raise TypeError("type of 'status' must be str.")
if avatar and not isinstance(avatar, str):
raise TypeError("type of 'avatar' must be str.")
url = f'https://api.weeb.sh/auto-image/discord-status?status={status}' + (f'&avatar={urllib.parse.quote(avatar, safe="")}' if avatar else '')
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.__headers) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | [
"async",
"def",
"generate_status",
"(",
"self",
",",
"status",
",",
"avatar",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"status",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'status' must be str.\"",
")",
"if",
"avatar",
"and",
"not",
"isinstance",
"(",
"avatar",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'avatar' must be str.\"",
")",
"url",
"=",
"f'https://api.weeb.sh/auto-image/discord-status?status={status}'",
"+",
"(",
"f'&avatar={urllib.parse.quote(avatar, safe=\"\")}'",
"if",
"avatar",
"else",
"''",
")",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"async",
"with",
"session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"__headers",
")",
"as",
"resp",
":",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"return",
"await",
"resp",
".",
"read",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'message'",
"]",
")"
]
| Generate a discord status icon below the image provided.
This function is a coroutine.
Parameters:
status: str - a discord status, must be online, idle, dnd, or streaming
avatar: str - http/s url pointing to an avatar, has to have proper headers and be a direct link to an image
(Note, this url is encoded by the wrapper itself, so you don't have to worry about encoding it ;))
Return Type: image data | [
"Generate",
"a",
"discord",
"status",
"icon",
"below",
"the",
"image",
"provided",
"."
]
| 5174c22e0cd34cb77f69ad18fbe87ee1fad51859 | https://github.com/Desiiii/weeb.py/blob/5174c22e0cd34cb77f69ad18fbe87ee1fad51859/weeb/client.py#L108-L129 | train |
Desiiii/weeb.py | weeb/client.py | Client.generate_waifu_insult | async def generate_waifu_insult(self, avatar):
"""Generate a waifu insult image.
This function is a coroutine.
Parameters:
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
Return Type: image data"""
if not isinstance(avatar, str):
raise TypeError("type of 'avatar' must be str.")
async with aiohttp.ClientSession() as session:
async with session.post("https://api.weeb.sh/auto-image/waifu-insult", headers=self.__headers, data={"avatar": avatar}) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | python | async def generate_waifu_insult(self, avatar):
"""Generate a waifu insult image.
This function is a coroutine.
Parameters:
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
Return Type: image data"""
if not isinstance(avatar, str):
raise TypeError("type of 'avatar' must be str.")
async with aiohttp.ClientSession() as session:
async with session.post("https://api.weeb.sh/auto-image/waifu-insult", headers=self.__headers, data={"avatar": avatar}) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | [
"async",
"def",
"generate_waifu_insult",
"(",
"self",
",",
"avatar",
")",
":",
"if",
"not",
"isinstance",
"(",
"avatar",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'avatar' must be str.\"",
")",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"async",
"with",
"session",
".",
"post",
"(",
"\"https://api.weeb.sh/auto-image/waifu-insult\"",
",",
"headers",
"=",
"self",
".",
"__headers",
",",
"data",
"=",
"{",
"\"avatar\"",
":",
"avatar",
"}",
")",
"as",
"resp",
":",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"return",
"await",
"resp",
".",
"read",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'message'",
"]",
")"
]
| Generate a waifu insult image.
This function is a coroutine.
Parameters:
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
Return Type: image data | [
"Generate",
"a",
"waifu",
"insult",
"image",
"."
]
| 5174c22e0cd34cb77f69ad18fbe87ee1fad51859 | https://github.com/Desiiii/weeb.py/blob/5174c22e0cd34cb77f69ad18fbe87ee1fad51859/weeb/client.py#L131-L147 | train |
Desiiii/weeb.py | weeb/client.py | Client.generate_license | async def generate_license(self, title, avatar, badges=None, widgets=None):
"""Generate a license.
This function is a coroutine.
Parameters:
title: str - title of the license
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
badges: list - list of 1-3 direct image urls. Same requirements as avatar (optional)
widgets: list - list of 1-3 strings to fill the three boxes with (optional)
Return Type: image data"""
if not isinstance(title, str):
raise TypeError("type of 'title' must be str.")
if not isinstance(avatar, str):
raise TypeError("type of 'avatar' must be str.")
if badges and not isinstance(badges, list):
raise TypeError("type of 'badges' must be list.")
if widgets and not isinstance(widgets, list):
raise TypeError("type of 'widgets' must be list.")
data = {"title": title, "avatar": avatar}
if badges and len(badges) <= 3:
data['badges'] = badges
if widgets and len(widgets) <= 3:
data['widgets'] = widgets
async with aiohttp.ClientSession() as session:
async with session.post("https://api.weeb.sh/auto-image/license", headers=self.__headers, data=data) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | python | async def generate_license(self, title, avatar, badges=None, widgets=None):
"""Generate a license.
This function is a coroutine.
Parameters:
title: str - title of the license
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
badges: list - list of 1-3 direct image urls. Same requirements as avatar (optional)
widgets: list - list of 1-3 strings to fill the three boxes with (optional)
Return Type: image data"""
if not isinstance(title, str):
raise TypeError("type of 'title' must be str.")
if not isinstance(avatar, str):
raise TypeError("type of 'avatar' must be str.")
if badges and not isinstance(badges, list):
raise TypeError("type of 'badges' must be list.")
if widgets and not isinstance(widgets, list):
raise TypeError("type of 'widgets' must be list.")
data = {"title": title, "avatar": avatar}
if badges and len(badges) <= 3:
data['badges'] = badges
if widgets and len(widgets) <= 3:
data['widgets'] = widgets
async with aiohttp.ClientSession() as session:
async with session.post("https://api.weeb.sh/auto-image/license", headers=self.__headers, data=data) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | [
"async",
"def",
"generate_license",
"(",
"self",
",",
"title",
",",
"avatar",
",",
"badges",
"=",
"None",
",",
"widgets",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"title",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'title' must be str.\"",
")",
"if",
"not",
"isinstance",
"(",
"avatar",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'avatar' must be str.\"",
")",
"if",
"badges",
"and",
"not",
"isinstance",
"(",
"badges",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'badges' must be list.\"",
")",
"if",
"widgets",
"and",
"not",
"isinstance",
"(",
"widgets",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'widgets' must be list.\"",
")",
"data",
"=",
"{",
"\"title\"",
":",
"title",
",",
"\"avatar\"",
":",
"avatar",
"}",
"if",
"badges",
"and",
"len",
"(",
"badges",
")",
"<=",
"3",
":",
"data",
"[",
"'badges'",
"]",
"=",
"badges",
"if",
"widgets",
"and",
"len",
"(",
"widgets",
")",
"<=",
"3",
":",
"data",
"[",
"'widgets'",
"]",
"=",
"widgets",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"async",
"with",
"session",
".",
"post",
"(",
"\"https://api.weeb.sh/auto-image/license\"",
",",
"headers",
"=",
"self",
".",
"__headers",
",",
"data",
"=",
"data",
")",
"as",
"resp",
":",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"return",
"await",
"resp",
".",
"read",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'message'",
"]",
")"
]
| Generate a license.
This function is a coroutine.
Parameters:
title: str - title of the license
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
badges: list - list of 1-3 direct image urls. Same requirements as avatar (optional)
widgets: list - list of 1-3 strings to fill the three boxes with (optional)
Return Type: image data | [
"Generate",
"a",
"license",
"."
]
| 5174c22e0cd34cb77f69ad18fbe87ee1fad51859 | https://github.com/Desiiii/weeb.py/blob/5174c22e0cd34cb77f69ad18fbe87ee1fad51859/weeb/client.py#L149-L179 | train |
Desiiii/weeb.py | weeb/client.py | Client.generate_love_ship | async def generate_love_ship(self, target_one, target_two):
"""Generate a love ship.
This function is a coroutine.
Parameters:
target_one: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image, image will be on the left side.
target_two: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image, image will be on the left side.
Return Type: image data"""
if not isinstance(target_one, str):
raise TypeError("type of 'target_one' must be str.")
if not isinstance(target_two, str):
raise TypeError("type of 'target_two' must be str.")
data = {"targetOne": target_one, "targetTwo": target_two}
async with aiohttp.ClientSession() as session:
async with session.post("https://api.weeb.sh/auto-image/love-ship", headers=self.__headers, data=data) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | python | async def generate_love_ship(self, target_one, target_two):
"""Generate a love ship.
This function is a coroutine.
Parameters:
target_one: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image, image will be on the left side.
target_two: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image, image will be on the left side.
Return Type: image data"""
if not isinstance(target_one, str):
raise TypeError("type of 'target_one' must be str.")
if not isinstance(target_two, str):
raise TypeError("type of 'target_two' must be str.")
data = {"targetOne": target_one, "targetTwo": target_two}
async with aiohttp.ClientSession() as session:
async with session.post("https://api.weeb.sh/auto-image/love-ship", headers=self.__headers, data=data) as resp:
if resp.status == 200:
return await resp.read()
else:
raise Exception((await resp.json())['message']) | [
"async",
"def",
"generate_love_ship",
"(",
"self",
",",
"target_one",
",",
"target_two",
")",
":",
"if",
"not",
"isinstance",
"(",
"target_one",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'target_one' must be str.\"",
")",
"if",
"not",
"isinstance",
"(",
"target_two",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"type of 'target_two' must be str.\"",
")",
"data",
"=",
"{",
"\"targetOne\"",
":",
"target_one",
",",
"\"targetTwo\"",
":",
"target_two",
"}",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"async",
"with",
"session",
".",
"post",
"(",
"\"https://api.weeb.sh/auto-image/love-ship\"",
",",
"headers",
"=",
"self",
".",
"__headers",
",",
"data",
"=",
"data",
")",
"as",
"resp",
":",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"return",
"await",
"resp",
".",
"read",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"(",
"await",
"resp",
".",
"json",
"(",
")",
")",
"[",
"'message'",
"]",
")"
]
| Generate a love ship.
This function is a coroutine.
Parameters:
target_one: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image, image will be on the left side.
target_two: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image, image will be on the left side.
Return Type: image data | [
"Generate",
"a",
"love",
"ship",
"."
]
| 5174c22e0cd34cb77f69ad18fbe87ee1fad51859 | https://github.com/Desiiii/weeb.py/blob/5174c22e0cd34cb77f69ad18fbe87ee1fad51859/weeb/client.py#L181-L201 | train |
cozy/python_cozy_management | cozy_management/monitor.py | launch_command | def launch_command(command, parameter=''):
'''Can launch a cozy-monitor command
:param command: The cozy-monitor command to launch
:param parameter: The parameter to push on cozy-monitor if needed
:returns: the command string
'''
result = ''
# Transform into an array if it not one
if not isinstance(parameter, list):
parameter = [parameter]
# Iterate on all parameter with action & put them in result string
for name in parameter:
result += subprocess.Popen('cozy-monitor {} {}'.format(command, name),
shell=True,
stdout=subprocess.PIPE).stdout.read()
return result | python | def launch_command(command, parameter=''):
'''Can launch a cozy-monitor command
:param command: The cozy-monitor command to launch
:param parameter: The parameter to push on cozy-monitor if needed
:returns: the command string
'''
result = ''
# Transform into an array if it not one
if not isinstance(parameter, list):
parameter = [parameter]
# Iterate on all parameter with action & put them in result string
for name in parameter:
result += subprocess.Popen('cozy-monitor {} {}'.format(command, name),
shell=True,
stdout=subprocess.PIPE).stdout.read()
return result | [
"def",
"launch_command",
"(",
"command",
",",
"parameter",
"=",
"''",
")",
":",
"result",
"=",
"''",
"# Transform into an array if it not one",
"if",
"not",
"isinstance",
"(",
"parameter",
",",
"list",
")",
":",
"parameter",
"=",
"[",
"parameter",
"]",
"# Iterate on all parameter with action & put them in result string",
"for",
"name",
"in",
"parameter",
":",
"result",
"+=",
"subprocess",
".",
"Popen",
"(",
"'cozy-monitor {} {}'",
".",
"format",
"(",
"command",
",",
"name",
")",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"stdout",
".",
"read",
"(",
")",
"return",
"result"
]
| Can launch a cozy-monitor command
:param command: The cozy-monitor command to launch
:param parameter: The parameter to push on cozy-monitor if needed
:returns: the command string | [
"Can",
"launch",
"a",
"cozy",
"-",
"monitor",
"command"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/monitor.py#L15-L33 | train |
cozy/python_cozy_management | cozy_management/monitor.py | status | def status(app_name=None, only_cozy=False, as_boolean=False):
'''Get apps status
:param app_name: If pass app name return this app status
:return: dict with all apps status or str with one app status
'''
apps = {}
# Get all apps status & slip them
apps_status = subprocess.Popen('cozy-monitor status',
shell=True,
stdout=subprocess.PIPE).stdout.read()
apps_status = apps_status.split('\n')
# Parse result to store them in apps dictionary
for app_status in apps_status:
if app_status:
app_status = ANSI_ESCAPE.sub('', app_status).split(': ')
if len(app_status) == 2:
current_status = app_status[1]
if as_boolean:
if app_status[1] == 'up':
current_status = True
else:
current_status = False
if only_cozy and app_status[0] not in SYSTEM_APPS:
apps[app_status[0]] = current_status
else:
apps[app_status[0]] = current_status
# Return app status if get as param or return all apps status
if app_name:
return apps.get(app_name, None)
else:
return apps | python | def status(app_name=None, only_cozy=False, as_boolean=False):
'''Get apps status
:param app_name: If pass app name return this app status
:return: dict with all apps status or str with one app status
'''
apps = {}
# Get all apps status & slip them
apps_status = subprocess.Popen('cozy-monitor status',
shell=True,
stdout=subprocess.PIPE).stdout.read()
apps_status = apps_status.split('\n')
# Parse result to store them in apps dictionary
for app_status in apps_status:
if app_status:
app_status = ANSI_ESCAPE.sub('', app_status).split(': ')
if len(app_status) == 2:
current_status = app_status[1]
if as_boolean:
if app_status[1] == 'up':
current_status = True
else:
current_status = False
if only_cozy and app_status[0] not in SYSTEM_APPS:
apps[app_status[0]] = current_status
else:
apps[app_status[0]] = current_status
# Return app status if get as param or return all apps status
if app_name:
return apps.get(app_name, None)
else:
return apps | [
"def",
"status",
"(",
"app_name",
"=",
"None",
",",
"only_cozy",
"=",
"False",
",",
"as_boolean",
"=",
"False",
")",
":",
"apps",
"=",
"{",
"}",
"# Get all apps status & slip them",
"apps_status",
"=",
"subprocess",
".",
"Popen",
"(",
"'cozy-monitor status'",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"stdout",
".",
"read",
"(",
")",
"apps_status",
"=",
"apps_status",
".",
"split",
"(",
"'\\n'",
")",
"# Parse result to store them in apps dictionary",
"for",
"app_status",
"in",
"apps_status",
":",
"if",
"app_status",
":",
"app_status",
"=",
"ANSI_ESCAPE",
".",
"sub",
"(",
"''",
",",
"app_status",
")",
".",
"split",
"(",
"': '",
")",
"if",
"len",
"(",
"app_status",
")",
"==",
"2",
":",
"current_status",
"=",
"app_status",
"[",
"1",
"]",
"if",
"as_boolean",
":",
"if",
"app_status",
"[",
"1",
"]",
"==",
"'up'",
":",
"current_status",
"=",
"True",
"else",
":",
"current_status",
"=",
"False",
"if",
"only_cozy",
"and",
"app_status",
"[",
"0",
"]",
"not",
"in",
"SYSTEM_APPS",
":",
"apps",
"[",
"app_status",
"[",
"0",
"]",
"]",
"=",
"current_status",
"else",
":",
"apps",
"[",
"app_status",
"[",
"0",
"]",
"]",
"=",
"current_status",
"# Return app status if get as param or return all apps status",
"if",
"app_name",
":",
"return",
"apps",
".",
"get",
"(",
"app_name",
",",
"None",
")",
"else",
":",
"return",
"apps"
]
| Get apps status
:param app_name: If pass app name return this app status
:return: dict with all apps status or str with one app status | [
"Get",
"apps",
"status"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/monitor.py#L36-L69 | train |
uogbuji/versa | tools/py/util.py | transitive_closure | def transitive_closure(m, orig, rel):
'''
Generate the closure over a transitive relationship in depth-first fashion
'''
#FIXME: Broken for now
links = list(m.match(orig, rel))
for link in links:
yield link[0][TARGET]
yield from transitive_closure(m, target, rel) | python | def transitive_closure(m, orig, rel):
'''
Generate the closure over a transitive relationship in depth-first fashion
'''
#FIXME: Broken for now
links = list(m.match(orig, rel))
for link in links:
yield link[0][TARGET]
yield from transitive_closure(m, target, rel) | [
"def",
"transitive_closure",
"(",
"m",
",",
"orig",
",",
"rel",
")",
":",
"#FIXME: Broken for now",
"links",
"=",
"list",
"(",
"m",
".",
"match",
"(",
"orig",
",",
"rel",
")",
")",
"for",
"link",
"in",
"links",
":",
"yield",
"link",
"[",
"0",
"]",
"[",
"TARGET",
"]",
"yield",
"from",
"transitive_closure",
"(",
"m",
",",
"target",
",",
"rel",
")"
]
| Generate the closure over a transitive relationship in depth-first fashion | [
"Generate",
"the",
"closure",
"over",
"a",
"transitive",
"relationship",
"in",
"depth",
"-",
"first",
"fashion"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L36-L44 | train |
uogbuji/versa | tools/py/util.py | all_origins | def all_origins(m):
'''
Generate all unique statement origins in the given model
'''
seen = set()
for link in m.match():
origin = link[ORIGIN]
if origin not in seen:
seen.add(origin)
yield origin | python | def all_origins(m):
'''
Generate all unique statement origins in the given model
'''
seen = set()
for link in m.match():
origin = link[ORIGIN]
if origin not in seen:
seen.add(origin)
yield origin | [
"def",
"all_origins",
"(",
"m",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"link",
"in",
"m",
".",
"match",
"(",
")",
":",
"origin",
"=",
"link",
"[",
"ORIGIN",
"]",
"if",
"origin",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"origin",
")",
"yield",
"origin"
]
| Generate all unique statement origins in the given model | [
"Generate",
"all",
"unique",
"statement",
"origins",
"in",
"the",
"given",
"model"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L47-L56 | train |
uogbuji/versa | tools/py/util.py | column | def column(m, linkpart):
'''
Generate all parts of links according to the parameter
'''
assert linkpart in (0, 1, 2, 3)
seen = set()
for link in m.match():
val = link[linkpart]
if val not in seen:
seen.add(val)
yield val | python | def column(m, linkpart):
'''
Generate all parts of links according to the parameter
'''
assert linkpart in (0, 1, 2, 3)
seen = set()
for link in m.match():
val = link[linkpart]
if val not in seen:
seen.add(val)
yield val | [
"def",
"column",
"(",
"m",
",",
"linkpart",
")",
":",
"assert",
"linkpart",
"in",
"(",
"0",
",",
"1",
",",
"2",
",",
"3",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"link",
"in",
"m",
".",
"match",
"(",
")",
":",
"val",
"=",
"link",
"[",
"linkpart",
"]",
"if",
"val",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"val",
")",
"yield",
"val"
]
| Generate all parts of links according to the parameter | [
"Generate",
"all",
"parts",
"of",
"links",
"according",
"to",
"the",
"parameter"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L59-L69 | train |
uogbuji/versa | tools/py/util.py | resourcetypes | def resourcetypes(rid, model):
'''
Return a list of Versa types for a resource
'''
types = []
for o, r, t, a in model.match(rid, VTYPE_REL):
types.append(t)
return types | python | def resourcetypes(rid, model):
'''
Return a list of Versa types for a resource
'''
types = []
for o, r, t, a in model.match(rid, VTYPE_REL):
types.append(t)
return types | [
"def",
"resourcetypes",
"(",
"rid",
",",
"model",
")",
":",
"types",
"=",
"[",
"]",
"for",
"o",
",",
"r",
",",
"t",
",",
"a",
"in",
"model",
".",
"match",
"(",
"rid",
",",
"VTYPE_REL",
")",
":",
"types",
".",
"append",
"(",
"t",
")",
"return",
"types"
]
| Return a list of Versa types for a resource | [
"Return",
"a",
"list",
"of",
"Versa",
"types",
"for",
"a",
"resource"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L72-L79 | train |
uogbuji/versa | tools/py/util.py | replace_values | def replace_values(in_m, out_m, map_from=(), map_to=()):
'''
Make a copy of a model with one value replaced with another
'''
for link in in_m.match():
new_link = list(link)
if map_from:
if link[ORIGIN] in map_from: new_link[ORIGIN] = map_to[map_from.index(link[ORIGIN])]
new_link[ATTRIBUTES] = link[ATTRIBUTES].copy()
out_m.add(*new_link)
return | python | def replace_values(in_m, out_m, map_from=(), map_to=()):
'''
Make a copy of a model with one value replaced with another
'''
for link in in_m.match():
new_link = list(link)
if map_from:
if link[ORIGIN] in map_from: new_link[ORIGIN] = map_to[map_from.index(link[ORIGIN])]
new_link[ATTRIBUTES] = link[ATTRIBUTES].copy()
out_m.add(*new_link)
return | [
"def",
"replace_values",
"(",
"in_m",
",",
"out_m",
",",
"map_from",
"=",
"(",
")",
",",
"map_to",
"=",
"(",
")",
")",
":",
"for",
"link",
"in",
"in_m",
".",
"match",
"(",
")",
":",
"new_link",
"=",
"list",
"(",
"link",
")",
"if",
"map_from",
":",
"if",
"link",
"[",
"ORIGIN",
"]",
"in",
"map_from",
":",
"new_link",
"[",
"ORIGIN",
"]",
"=",
"map_to",
"[",
"map_from",
".",
"index",
"(",
"link",
"[",
"ORIGIN",
"]",
")",
"]",
"new_link",
"[",
"ATTRIBUTES",
"]",
"=",
"link",
"[",
"ATTRIBUTES",
"]",
".",
"copy",
"(",
")",
"out_m",
".",
"add",
"(",
"*",
"new_link",
")",
"return"
]
| Make a copy of a model with one value replaced with another | [
"Make",
"a",
"copy",
"of",
"a",
"model",
"with",
"one",
"value",
"replaced",
"with",
"another"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L83-L93 | train |
uogbuji/versa | tools/py/util.py | replace_entity_resource | def replace_entity_resource(model, oldres, newres):
'''
Replace one entity in the model with another with the same links
:param model: Versa model to be updated
:param oldres: old/former resource IRI to be replaced
:param newres: new/replacement resource IRI
:return: None
'''
oldrids = set()
for rid, link in model:
if link[ORIGIN] == oldres or link[TARGET] == oldres or oldres in link[ATTRIBUTES].values():
oldrids.add(rid)
new_link = (newres if o == oldres else o, r, newres if t == oldres else t, dict((k, newres if v == oldres else v) for k, v in a.items()))
model.add(*new_link)
model.delete(oldrids)
return | python | def replace_entity_resource(model, oldres, newres):
'''
Replace one entity in the model with another with the same links
:param model: Versa model to be updated
:param oldres: old/former resource IRI to be replaced
:param newres: new/replacement resource IRI
:return: None
'''
oldrids = set()
for rid, link in model:
if link[ORIGIN] == oldres or link[TARGET] == oldres or oldres in link[ATTRIBUTES].values():
oldrids.add(rid)
new_link = (newres if o == oldres else o, r, newres if t == oldres else t, dict((k, newres if v == oldres else v) for k, v in a.items()))
model.add(*new_link)
model.delete(oldrids)
return | [
"def",
"replace_entity_resource",
"(",
"model",
",",
"oldres",
",",
"newres",
")",
":",
"oldrids",
"=",
"set",
"(",
")",
"for",
"rid",
",",
"link",
"in",
"model",
":",
"if",
"link",
"[",
"ORIGIN",
"]",
"==",
"oldres",
"or",
"link",
"[",
"TARGET",
"]",
"==",
"oldres",
"or",
"oldres",
"in",
"link",
"[",
"ATTRIBUTES",
"]",
".",
"values",
"(",
")",
":",
"oldrids",
".",
"add",
"(",
"rid",
")",
"new_link",
"=",
"(",
"newres",
"if",
"o",
"==",
"oldres",
"else",
"o",
",",
"r",
",",
"newres",
"if",
"t",
"==",
"oldres",
"else",
"t",
",",
"dict",
"(",
"(",
"k",
",",
"newres",
"if",
"v",
"==",
"oldres",
"else",
"v",
")",
"for",
"k",
",",
"v",
"in",
"a",
".",
"items",
"(",
")",
")",
")",
"model",
".",
"add",
"(",
"*",
"new_link",
")",
"model",
".",
"delete",
"(",
"oldrids",
")",
"return"
]
| Replace one entity in the model with another with the same links
:param model: Versa model to be updated
:param oldres: old/former resource IRI to be replaced
:param newres: new/replacement resource IRI
:return: None | [
"Replace",
"one",
"entity",
"in",
"the",
"model",
"with",
"another",
"with",
"the",
"same",
"links"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L96-L112 | train |
uogbuji/versa | tools/py/util.py | duplicate_statements | def duplicate_statements(model, oldorigin, neworigin, rfilter=None):
'''
Take links with a given origin, and create duplicate links with the same information but a new origin
:param model: Versa model to be updated
:param oldres: resource IRI to be duplicated
:param newres: origin resource IRI for duplication
:return: None
'''
for o, r, t, a in model.match(oldorigin):
if rfilter is None or rfilter(o, r, t, a):
model.add(I(neworigin), r, t, a)
return | python | def duplicate_statements(model, oldorigin, neworigin, rfilter=None):
'''
Take links with a given origin, and create duplicate links with the same information but a new origin
:param model: Versa model to be updated
:param oldres: resource IRI to be duplicated
:param newres: origin resource IRI for duplication
:return: None
'''
for o, r, t, a in model.match(oldorigin):
if rfilter is None or rfilter(o, r, t, a):
model.add(I(neworigin), r, t, a)
return | [
"def",
"duplicate_statements",
"(",
"model",
",",
"oldorigin",
",",
"neworigin",
",",
"rfilter",
"=",
"None",
")",
":",
"for",
"o",
",",
"r",
",",
"t",
",",
"a",
"in",
"model",
".",
"match",
"(",
"oldorigin",
")",
":",
"if",
"rfilter",
"is",
"None",
"or",
"rfilter",
"(",
"o",
",",
"r",
",",
"t",
",",
"a",
")",
":",
"model",
".",
"add",
"(",
"I",
"(",
"neworigin",
")",
",",
"r",
",",
"t",
",",
"a",
")",
"return"
]
| Take links with a given origin, and create duplicate links with the same information but a new origin
:param model: Versa model to be updated
:param oldres: resource IRI to be duplicated
:param newres: origin resource IRI for duplication
:return: None | [
"Take",
"links",
"with",
"a",
"given",
"origin",
"and",
"create",
"duplicate",
"links",
"with",
"the",
"same",
"information",
"but",
"a",
"new",
"origin"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L115-L127 | train |
uogbuji/versa | tools/py/util.py | uniquify | def uniquify(model):
'''
Remove all duplicate relationships
'''
seen = set()
to_remove = set()
for ix, (o, r, t, a) in model:
hashable_link = (o, r, t) + tuple(sorted(a.items()))
#print(hashable_link)
if hashable_link in seen:
to_remove.add(ix)
seen.add(hashable_link)
model.remove(to_remove)
return | python | def uniquify(model):
'''
Remove all duplicate relationships
'''
seen = set()
to_remove = set()
for ix, (o, r, t, a) in model:
hashable_link = (o, r, t) + tuple(sorted(a.items()))
#print(hashable_link)
if hashable_link in seen:
to_remove.add(ix)
seen.add(hashable_link)
model.remove(to_remove)
return | [
"def",
"uniquify",
"(",
"model",
")",
":",
"seen",
"=",
"set",
"(",
")",
"to_remove",
"=",
"set",
"(",
")",
"for",
"ix",
",",
"(",
"o",
",",
"r",
",",
"t",
",",
"a",
")",
"in",
"model",
":",
"hashable_link",
"=",
"(",
"o",
",",
"r",
",",
"t",
")",
"+",
"tuple",
"(",
"sorted",
"(",
"a",
".",
"items",
"(",
")",
")",
")",
"#print(hashable_link)",
"if",
"hashable_link",
"in",
"seen",
":",
"to_remove",
".",
"add",
"(",
"ix",
")",
"seen",
".",
"add",
"(",
"hashable_link",
")",
"model",
".",
"remove",
"(",
"to_remove",
")",
"return"
]
| Remove all duplicate relationships | [
"Remove",
"all",
"duplicate",
"relationships"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L130-L144 | train |
uogbuji/versa | tools/py/util.py | jsonload | def jsonload(model, fp):
'''
Load Versa model dumped into JSON form, either raw or canonical
'''
dumped_list = json.load(fp)
for link in dumped_list:
if len(link) == 2:
sid, (s, p, o, a) = link
elif len(link) == 4: #canonical
(s, p, o, a) = link
tt = a.get('@target-type')
if tt == '@iri-ref':
o = I(o)
a.pop('@target-type', None)
else:
continue
model.add(s, p, o, a)
return | python | def jsonload(model, fp):
'''
Load Versa model dumped into JSON form, either raw or canonical
'''
dumped_list = json.load(fp)
for link in dumped_list:
if len(link) == 2:
sid, (s, p, o, a) = link
elif len(link) == 4: #canonical
(s, p, o, a) = link
tt = a.get('@target-type')
if tt == '@iri-ref':
o = I(o)
a.pop('@target-type', None)
else:
continue
model.add(s, p, o, a)
return | [
"def",
"jsonload",
"(",
"model",
",",
"fp",
")",
":",
"dumped_list",
"=",
"json",
".",
"load",
"(",
"fp",
")",
"for",
"link",
"in",
"dumped_list",
":",
"if",
"len",
"(",
"link",
")",
"==",
"2",
":",
"sid",
",",
"(",
"s",
",",
"p",
",",
"o",
",",
"a",
")",
"=",
"link",
"elif",
"len",
"(",
"link",
")",
"==",
"4",
":",
"#canonical",
"(",
"s",
",",
"p",
",",
"o",
",",
"a",
")",
"=",
"link",
"tt",
"=",
"a",
".",
"get",
"(",
"'@target-type'",
")",
"if",
"tt",
"==",
"'@iri-ref'",
":",
"o",
"=",
"I",
"(",
"o",
")",
"a",
".",
"pop",
"(",
"'@target-type'",
",",
"None",
")",
"else",
":",
"continue",
"model",
".",
"add",
"(",
"s",
",",
"p",
",",
"o",
",",
"a",
")",
"return"
]
| Load Versa model dumped into JSON form, either raw or canonical | [
"Load",
"Versa",
"model",
"dumped",
"into",
"JSON",
"form",
"either",
"raw",
"or",
"canonical"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L147-L164 | train |
uogbuji/versa | tools/py/util.py | jsondump | def jsondump(model, fp):
'''
Dump Versa model into JSON form
'''
fp.write('[')
links_ser = []
for link in model:
links_ser.append(json.dumps(link))
fp.write(',\n'.join(links_ser))
fp.write(']') | python | def jsondump(model, fp):
'''
Dump Versa model into JSON form
'''
fp.write('[')
links_ser = []
for link in model:
links_ser.append(json.dumps(link))
fp.write(',\n'.join(links_ser))
fp.write(']') | [
"def",
"jsondump",
"(",
"model",
",",
"fp",
")",
":",
"fp",
".",
"write",
"(",
"'['",
")",
"links_ser",
"=",
"[",
"]",
"for",
"link",
"in",
"model",
":",
"links_ser",
".",
"append",
"(",
"json",
".",
"dumps",
"(",
"link",
")",
")",
"fp",
".",
"write",
"(",
"',\\n'",
".",
"join",
"(",
"links_ser",
")",
")",
"fp",
".",
"write",
"(",
"']'",
")"
]
| Dump Versa model into JSON form | [
"Dump",
"Versa",
"model",
"into",
"JSON",
"form"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/util.py#L167-L176 | train |
TheGhouls/oct | oct/results/writer.py | ReportWriter.set_statics | def set_statics(self):
"""Create statics directory and copy files in it
"""
if not os.path.exists(self.results_dir):
return None
try:
shutil.copytree(os.path.join(self.templates_dir, 'css'), os.path.join(self.results_dir, 'css'))
shutil.copytree(os.path.join(self.templates_dir, 'scripts'), os.path.join(self.results_dir, 'scripts'))
shutil.copytree(os.path.join(self.templates_dir, 'fonts'), os.path.join(self.results_dir, 'fonts'))
except OSError as e:
if e.errno == 17: # File exists
print("WARNING : existing output directory for static files, will not replace them")
else: # in all other cases, re-raise exceptions
raise
try:
shutil.copytree(os.path.join(self.templates_dir, 'img'), os.path.join(self.results_dir, 'img'))
except OSError as e:
pass | python | def set_statics(self):
"""Create statics directory and copy files in it
"""
if not os.path.exists(self.results_dir):
return None
try:
shutil.copytree(os.path.join(self.templates_dir, 'css'), os.path.join(self.results_dir, 'css'))
shutil.copytree(os.path.join(self.templates_dir, 'scripts'), os.path.join(self.results_dir, 'scripts'))
shutil.copytree(os.path.join(self.templates_dir, 'fonts'), os.path.join(self.results_dir, 'fonts'))
except OSError as e:
if e.errno == 17: # File exists
print("WARNING : existing output directory for static files, will not replace them")
else: # in all other cases, re-raise exceptions
raise
try:
shutil.copytree(os.path.join(self.templates_dir, 'img'), os.path.join(self.results_dir, 'img'))
except OSError as e:
pass | [
"def",
"set_statics",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"results_dir",
")",
":",
"return",
"None",
"try",
":",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"templates_dir",
",",
"'css'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"results_dir",
",",
"'css'",
")",
")",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"templates_dir",
",",
"'scripts'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"results_dir",
",",
"'scripts'",
")",
")",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"templates_dir",
",",
"'fonts'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"results_dir",
",",
"'fonts'",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"17",
":",
"# File exists",
"print",
"(",
"\"WARNING : existing output directory for static files, will not replace them\"",
")",
"else",
":",
"# in all other cases, re-raise exceptions",
"raise",
"try",
":",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"templates_dir",
",",
"'img'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"results_dir",
",",
"'img'",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"pass"
]
| Create statics directory and copy files in it | [
"Create",
"statics",
"directory",
"and",
"copy",
"files",
"in",
"it"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/writer.py#L18-L35 | train |
TheGhouls/oct | oct/results/writer.py | ReportWriter.write_report | def write_report(self, template):
"""Write the compiled jinja template to the results file
:param template str: the compiled jinja template
"""
with open(self.fn, 'w') as f:
f.write(template) | python | def write_report(self, template):
"""Write the compiled jinja template to the results file
:param template str: the compiled jinja template
"""
with open(self.fn, 'w') as f:
f.write(template) | [
"def",
"write_report",
"(",
"self",
",",
"template",
")",
":",
"with",
"open",
"(",
"self",
".",
"fn",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"template",
")"
]
| Write the compiled jinja template to the results file
:param template str: the compiled jinja template | [
"Write",
"the",
"compiled",
"jinja",
"template",
"to",
"the",
"results",
"file"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/writer.py#L37-L43 | train |
Sabesto/pyflexit | pyflexit/pyflexit.py | pyflexit.set_raw_holding_register | def set_raw_holding_register(self, name, value):
"""Write to register by name."""
self._conn.write_register(
unit=self._slave,
address=(self._holding_regs[name]['addr']),
value=value) | python | def set_raw_holding_register(self, name, value):
"""Write to register by name."""
self._conn.write_register(
unit=self._slave,
address=(self._holding_regs[name]['addr']),
value=value) | [
"def",
"set_raw_holding_register",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"_conn",
".",
"write_register",
"(",
"unit",
"=",
"self",
".",
"_slave",
",",
"address",
"=",
"(",
"self",
".",
"_holding_regs",
"[",
"name",
"]",
"[",
"'addr'",
"]",
")",
",",
"value",
"=",
"value",
")"
]
| Write to register by name. | [
"Write",
"to",
"register",
"by",
"name",
"."
]
| b88c235fe1659c82c09fd5d3a16c59d407fcf94c | https://github.com/Sabesto/pyflexit/blob/b88c235fe1659c82c09fd5d3a16c59d407fcf94c/pyflexit/pyflexit.py#L171-L176 | train |
ronhanson/python-tbx | tbx/file.py | unzip | def unzip(filepath, output_path):
"""
Unzip an archive file
"""
filename = os.path.split(filepath)[1]
(name, extension) = os.path.splitext(filename)
extension = extension[1:].lower()
extension2 = os.path.splitext(name)[1][1:].lower()
if extension not in ZIP_EXTENSIONS:
raise Exception("Impossible to extract archive file %s" % filepath)
extract_command = "unzip"
output_args = "-d"
if extension == 'bz2' and extension2 == 'tar':
extract_command = "tar -xjf"
output_args = "-C"
elif extension == 'gz' and extension2 == 'tar':
extract_command = "tar -xzf"
output_args = "-C"
elif extension == 'xz' and extension2 == 'tar':
extract_command = "tar -xJf"
output_args = "-C"
elif extension == 'bz2':
extract_command = "bunzip2 -dc "
output_args = ">"
output_path = os.path.join(output_path, name)
elif extension == 'rar':
extract_command = "unrar x"
output_args = ""
elif extension == 'gz':
extract_command = "gunzip"
output_args = ""
elif extension == 'tar':
extract_command = "tar -xf"
output_args = "-C"
elif extension == 'tbz2':
extract_command = "tar -xjf"
output_args = "-C"
elif extension == 'tgz':
extract_command = "tar -xzf"
output_args = "-C"
elif extension == 'zip':
extract_command = "unzip"
output_args = "-d"
elif extension == 'Z':
extract_command = "uncompress"
output_args = ""
elif extension == '7z':
extract_command = "7z x"
output_args = ""
elif extension == 'xz':
extract_command = "unxz"
output_args = ""
elif extension == 'ace':
extract_command = "unace"
output_args = ""
elif extension == 'iso':
extract_command = "7z x"
output_args = ""
elif extension == 'arj':
extract_command = "7z x"
output_args = ""
command = """%(extract_command)s "%(filepath)s" %(output_args)s "%(output_folder)s" """
params = {
'extract_command': extract_command,
'filepath': filepath,
'output_folder': output_path,
'output_args': output_args,
}
result = os.system(command % params)
return result | python | def unzip(filepath, output_path):
"""
Unzip an archive file
"""
filename = os.path.split(filepath)[1]
(name, extension) = os.path.splitext(filename)
extension = extension[1:].lower()
extension2 = os.path.splitext(name)[1][1:].lower()
if extension not in ZIP_EXTENSIONS:
raise Exception("Impossible to extract archive file %s" % filepath)
extract_command = "unzip"
output_args = "-d"
if extension == 'bz2' and extension2 == 'tar':
extract_command = "tar -xjf"
output_args = "-C"
elif extension == 'gz' and extension2 == 'tar':
extract_command = "tar -xzf"
output_args = "-C"
elif extension == 'xz' and extension2 == 'tar':
extract_command = "tar -xJf"
output_args = "-C"
elif extension == 'bz2':
extract_command = "bunzip2 -dc "
output_args = ">"
output_path = os.path.join(output_path, name)
elif extension == 'rar':
extract_command = "unrar x"
output_args = ""
elif extension == 'gz':
extract_command = "gunzip"
output_args = ""
elif extension == 'tar':
extract_command = "tar -xf"
output_args = "-C"
elif extension == 'tbz2':
extract_command = "tar -xjf"
output_args = "-C"
elif extension == 'tgz':
extract_command = "tar -xzf"
output_args = "-C"
elif extension == 'zip':
extract_command = "unzip"
output_args = "-d"
elif extension == 'Z':
extract_command = "uncompress"
output_args = ""
elif extension == '7z':
extract_command = "7z x"
output_args = ""
elif extension == 'xz':
extract_command = "unxz"
output_args = ""
elif extension == 'ace':
extract_command = "unace"
output_args = ""
elif extension == 'iso':
extract_command = "7z x"
output_args = ""
elif extension == 'arj':
extract_command = "7z x"
output_args = ""
command = """%(extract_command)s "%(filepath)s" %(output_args)s "%(output_folder)s" """
params = {
'extract_command': extract_command,
'filepath': filepath,
'output_folder': output_path,
'output_args': output_args,
}
result = os.system(command % params)
return result | [
"def",
"unzip",
"(",
"filepath",
",",
"output_path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filepath",
")",
"[",
"1",
"]",
"(",
"name",
",",
"extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"extension",
"=",
"extension",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"extension2",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"if",
"extension",
"not",
"in",
"ZIP_EXTENSIONS",
":",
"raise",
"Exception",
"(",
"\"Impossible to extract archive file %s\"",
"%",
"filepath",
")",
"extract_command",
"=",
"\"unzip\"",
"output_args",
"=",
"\"-d\"",
"if",
"extension",
"==",
"'bz2'",
"and",
"extension2",
"==",
"'tar'",
":",
"extract_command",
"=",
"\"tar -xjf\"",
"output_args",
"=",
"\"-C\"",
"elif",
"extension",
"==",
"'gz'",
"and",
"extension2",
"==",
"'tar'",
":",
"extract_command",
"=",
"\"tar -xzf\"",
"output_args",
"=",
"\"-C\"",
"elif",
"extension",
"==",
"'xz'",
"and",
"extension2",
"==",
"'tar'",
":",
"extract_command",
"=",
"\"tar -xJf\"",
"output_args",
"=",
"\"-C\"",
"elif",
"extension",
"==",
"'bz2'",
":",
"extract_command",
"=",
"\"bunzip2 -dc \"",
"output_args",
"=",
"\">\"",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_path",
",",
"name",
")",
"elif",
"extension",
"==",
"'rar'",
":",
"extract_command",
"=",
"\"unrar x\"",
"output_args",
"=",
"\"\"",
"elif",
"extension",
"==",
"'gz'",
":",
"extract_command",
"=",
"\"gunzip\"",
"output_args",
"=",
"\"\"",
"elif",
"extension",
"==",
"'tar'",
":",
"extract_command",
"=",
"\"tar -xf\"",
"output_args",
"=",
"\"-C\"",
"elif",
"extension",
"==",
"'tbz2'",
":",
"extract_command",
"=",
"\"tar -xjf\"",
"output_args",
"=",
"\"-C\"",
"elif",
"extension",
"==",
"'tgz'",
":",
"extract_command",
"=",
"\"tar -xzf\"",
"output_args",
"=",
"\"-C\"",
"elif",
"extension",
"==",
"'zip'",
":",
"extract_command",
"=",
"\"unzip\"",
"output_args",
"=",
"\"-d\"",
"elif",
"extension",
"==",
"'Z'",
":",
"extract_command",
"=",
"\"uncompress\"",
"output_args",
"=",
"\"\"",
"elif",
"extension",
"==",
"'7z'",
":",
"extract_command",
"=",
"\"7z x\"",
"output_args",
"=",
"\"\"",
"elif",
"extension",
"==",
"'xz'",
":",
"extract_command",
"=",
"\"unxz\"",
"output_args",
"=",
"\"\"",
"elif",
"extension",
"==",
"'ace'",
":",
"extract_command",
"=",
"\"unace\"",
"output_args",
"=",
"\"\"",
"elif",
"extension",
"==",
"'iso'",
":",
"extract_command",
"=",
"\"7z x\"",
"output_args",
"=",
"\"\"",
"elif",
"extension",
"==",
"'arj'",
":",
"extract_command",
"=",
"\"7z x\"",
"output_args",
"=",
"\"\"",
"command",
"=",
"\"\"\"%(extract_command)s \"%(filepath)s\" %(output_args)s \"%(output_folder)s\" \"\"\"",
"params",
"=",
"{",
"'extract_command'",
":",
"extract_command",
",",
"'filepath'",
":",
"filepath",
",",
"'output_folder'",
":",
"output_path",
",",
"'output_args'",
":",
"output_args",
",",
"}",
"result",
"=",
"os",
".",
"system",
"(",
"command",
"%",
"params",
")",
"return",
"result"
]
| Unzip an archive file | [
"Unzip",
"an",
"archive",
"file"
]
| 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/file.py#L80-L152 | train |
TheGhouls/oct | oct/core/hq.py | HightQuarter._configure_sockets | def _configure_sockets(self, config, with_streamer=False, with_forwarder=False):
"""Configure sockets for HQ
:param dict config: test configuration
:param bool with_streamer: tell if we need to connect to streamer or simply bind
:param bool with_forwarder: tell if we need to connect to forwarder or simply bind
"""
rc_port = config.get('rc_port', 5001)
self.result_collector.set_hwm(0)
self.result_collector.bind("tcp://*:{}".format(rc_port))
self.poller.register(self.result_collector, zmq.POLLIN) | python | def _configure_sockets(self, config, with_streamer=False, with_forwarder=False):
"""Configure sockets for HQ
:param dict config: test configuration
:param bool with_streamer: tell if we need to connect to streamer or simply bind
:param bool with_forwarder: tell if we need to connect to forwarder or simply bind
"""
rc_port = config.get('rc_port', 5001)
self.result_collector.set_hwm(0)
self.result_collector.bind("tcp://*:{}".format(rc_port))
self.poller.register(self.result_collector, zmq.POLLIN) | [
"def",
"_configure_sockets",
"(",
"self",
",",
"config",
",",
"with_streamer",
"=",
"False",
",",
"with_forwarder",
"=",
"False",
")",
":",
"rc_port",
"=",
"config",
".",
"get",
"(",
"'rc_port'",
",",
"5001",
")",
"self",
".",
"result_collector",
".",
"set_hwm",
"(",
"0",
")",
"self",
".",
"result_collector",
".",
"bind",
"(",
"\"tcp://*:{}\"",
".",
"format",
"(",
"rc_port",
")",
")",
"self",
".",
"poller",
".",
"register",
"(",
"self",
".",
"result_collector",
",",
"zmq",
".",
"POLLIN",
")"
]
| Configure sockets for HQ
:param dict config: test configuration
:param bool with_streamer: tell if we need to connect to streamer or simply bind
:param bool with_forwarder: tell if we need to connect to forwarder or simply bind | [
"Configure",
"sockets",
"for",
"HQ"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/hq.py#L75-L87 | train |
TheGhouls/oct | oct/core/hq.py | HightQuarter.wait_turrets | def wait_turrets(self, wait_for):
"""Wait until wait_for turrets are connected and ready
"""
print("Waiting for %d turrets" % (wait_for - len(self.turrets_manager.turrets)))
while len(self.turrets_manager.turrets) < wait_for:
self.turrets_manager.status_request()
socks = dict(self.poller.poll(2000))
if self.result_collector in socks:
data = self.result_collector.recv_json()
self.turrets_manager.process_message(data)
print("Waiting for %d turrets" % (wait_for - len(self.turrets_manager.turrets))) | python | def wait_turrets(self, wait_for):
"""Wait until wait_for turrets are connected and ready
"""
print("Waiting for %d turrets" % (wait_for - len(self.turrets_manager.turrets)))
while len(self.turrets_manager.turrets) < wait_for:
self.turrets_manager.status_request()
socks = dict(self.poller.poll(2000))
if self.result_collector in socks:
data = self.result_collector.recv_json()
self.turrets_manager.process_message(data)
print("Waiting for %d turrets" % (wait_for - len(self.turrets_manager.turrets))) | [
"def",
"wait_turrets",
"(",
"self",
",",
"wait_for",
")",
":",
"print",
"(",
"\"Waiting for %d turrets\"",
"%",
"(",
"wait_for",
"-",
"len",
"(",
"self",
".",
"turrets_manager",
".",
"turrets",
")",
")",
")",
"while",
"len",
"(",
"self",
".",
"turrets_manager",
".",
"turrets",
")",
"<",
"wait_for",
":",
"self",
".",
"turrets_manager",
".",
"status_request",
"(",
")",
"socks",
"=",
"dict",
"(",
"self",
".",
"poller",
".",
"poll",
"(",
"2000",
")",
")",
"if",
"self",
".",
"result_collector",
"in",
"socks",
":",
"data",
"=",
"self",
".",
"result_collector",
".",
"recv_json",
"(",
")",
"self",
".",
"turrets_manager",
".",
"process_message",
"(",
"data",
")",
"print",
"(",
"\"Waiting for %d turrets\"",
"%",
"(",
"wait_for",
"-",
"len",
"(",
"self",
".",
"turrets_manager",
".",
"turrets",
")",
")",
")"
]
| Wait until wait_for turrets are connected and ready | [
"Wait",
"until",
"wait_for",
"turrets",
"are",
"connected",
"and",
"ready"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/hq.py#L119-L133 | train |
TheGhouls/oct | oct/core/hq.py | HightQuarter.run | def run(self):
"""Run the hight quarter, lunch the turrets and wait for results
"""
elapsed = 0
run_time = self.config['run_time']
start_time = time.time()
t = time.time
self.turrets_manager.start(self.transaction_context)
self.started = True
while elapsed <= run_time:
try:
self._run_loop_action()
self._print_status(elapsed)
elapsed = t() - start_time
except (Exception, KeyboardInterrupt):
print("\nStopping test, sending stop command to turrets")
self.turrets_manager.stop()
self.stats_handler.write_remaining()
traceback.print_exc()
break
self.turrets_manager.stop()
print("\n\nProcessing all remaining messages... This could take time depending on message volume")
t = time.time()
self.result_collector.unbind(self.result_collector.LAST_ENDPOINT)
self._clean_queue()
print("took %s" % (time.time() - t)) | python | def run(self):
"""Run the hight quarter, lunch the turrets and wait for results
"""
elapsed = 0
run_time = self.config['run_time']
start_time = time.time()
t = time.time
self.turrets_manager.start(self.transaction_context)
self.started = True
while elapsed <= run_time:
try:
self._run_loop_action()
self._print_status(elapsed)
elapsed = t() - start_time
except (Exception, KeyboardInterrupt):
print("\nStopping test, sending stop command to turrets")
self.turrets_manager.stop()
self.stats_handler.write_remaining()
traceback.print_exc()
break
self.turrets_manager.stop()
print("\n\nProcessing all remaining messages... This could take time depending on message volume")
t = time.time()
self.result_collector.unbind(self.result_collector.LAST_ENDPOINT)
self._clean_queue()
print("took %s" % (time.time() - t)) | [
"def",
"run",
"(",
"self",
")",
":",
"elapsed",
"=",
"0",
"run_time",
"=",
"self",
".",
"config",
"[",
"'run_time'",
"]",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"t",
"=",
"time",
".",
"time",
"self",
".",
"turrets_manager",
".",
"start",
"(",
"self",
".",
"transaction_context",
")",
"self",
".",
"started",
"=",
"True",
"while",
"elapsed",
"<=",
"run_time",
":",
"try",
":",
"self",
".",
"_run_loop_action",
"(",
")",
"self",
".",
"_print_status",
"(",
"elapsed",
")",
"elapsed",
"=",
"t",
"(",
")",
"-",
"start_time",
"except",
"(",
"Exception",
",",
"KeyboardInterrupt",
")",
":",
"print",
"(",
"\"\\nStopping test, sending stop command to turrets\"",
")",
"self",
".",
"turrets_manager",
".",
"stop",
"(",
")",
"self",
".",
"stats_handler",
".",
"write_remaining",
"(",
")",
"traceback",
".",
"print_exc",
"(",
")",
"break",
"self",
".",
"turrets_manager",
".",
"stop",
"(",
")",
"print",
"(",
"\"\\n\\nProcessing all remaining messages... This could take time depending on message volume\"",
")",
"t",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"result_collector",
".",
"unbind",
"(",
"self",
".",
"result_collector",
".",
"LAST_ENDPOINT",
")",
"self",
".",
"_clean_queue",
"(",
")",
"print",
"(",
"\"took %s\"",
"%",
"(",
"time",
".",
"time",
"(",
")",
"-",
"t",
")",
")"
]
| Run the hight quarter, lunch the turrets and wait for results | [
"Run",
"the",
"hight",
"quarter",
"lunch",
"the",
"turrets",
"and",
"wait",
"for",
"results"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/hq.py#L135-L162 | train |
Kortemme-Lab/klab | klab/bio/fragments/hpc/SGE.py | query | def query(logfile, jobID = None):
"""If jobID is an integer then return False if the job has finished and True if it is still running.
Otherwise, returns a table of jobs run by the user."""
joblist = logfile.readFromLogfile()
if jobID and type(jobID) == type(1):
command = ['qstat', '-j', str(jobID)]
else:
command = ['qstat']
processoutput = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
output = processoutput[0]
serror = processoutput[1]
# Form command
jobs = {}
if type(jobID) == type(1):
if serror.find("Following jobs do not exist") != -1:
return False
else:
return True
if not output.strip():
colorprinter.message("No jobs running at present.")
output = output.strip().split("\n")
if len(output) > 2:
for line in output[2:]:
# We assume that our script names contain no spaces for the parsing below to work
tokens = line.split()
jid = int(tokens[0])
jobstate = tokens[4]
details = { "jobid" : jid,
"prior" : tokens[1],
"name" : tokens[2],
"user" : tokens[3],
"state" : jobstate,
"submit/start at" : "%s %s" % (tokens[5], tokens[6])
}
jataskID = 0
if jobstate == "r":
details["queue"] = tokens[7]
details["slots"] = tokens[8]
elif jobstate == "qw":
details["slots"] = tokens[7]
if len(tokens) >= 9:
jataskID = tokens[8]
details["ja-task-ID"] = jataskID
if len(tokens) > 9:
jataskID = tokens[9]
details["ja-task-ID"] = jataskID
jobs[jid] = jobs.get(jid) or {}
jobs[jid][jataskID] = details
if joblist.get(jid):
jobdir = joblist[jid]["Directory"]
jobtime = joblist[jid]["TimeInSeconds"]
colorprinter.message("Job %d submitted %d minutes ago. Status: '%s'. Destination directory: %s." % (jid, jobtime / 60, jobstate, jobdir))
else:
colorprinter.message("Job %d submitted at %s %s. Status: '%s'. Destination directory unknown." % (jid, tokens[5], tokens[6], jobstate))
return True | python | def query(logfile, jobID = None):
"""If jobID is an integer then return False if the job has finished and True if it is still running.
Otherwise, returns a table of jobs run by the user."""
joblist = logfile.readFromLogfile()
if jobID and type(jobID) == type(1):
command = ['qstat', '-j', str(jobID)]
else:
command = ['qstat']
processoutput = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
output = processoutput[0]
serror = processoutput[1]
# Form command
jobs = {}
if type(jobID) == type(1):
if serror.find("Following jobs do not exist") != -1:
return False
else:
return True
if not output.strip():
colorprinter.message("No jobs running at present.")
output = output.strip().split("\n")
if len(output) > 2:
for line in output[2:]:
# We assume that our script names contain no spaces for the parsing below to work
tokens = line.split()
jid = int(tokens[0])
jobstate = tokens[4]
details = { "jobid" : jid,
"prior" : tokens[1],
"name" : tokens[2],
"user" : tokens[3],
"state" : jobstate,
"submit/start at" : "%s %s" % (tokens[5], tokens[6])
}
jataskID = 0
if jobstate == "r":
details["queue"] = tokens[7]
details["slots"] = tokens[8]
elif jobstate == "qw":
details["slots"] = tokens[7]
if len(tokens) >= 9:
jataskID = tokens[8]
details["ja-task-ID"] = jataskID
if len(tokens) > 9:
jataskID = tokens[9]
details["ja-task-ID"] = jataskID
jobs[jid] = jobs.get(jid) or {}
jobs[jid][jataskID] = details
if joblist.get(jid):
jobdir = joblist[jid]["Directory"]
jobtime = joblist[jid]["TimeInSeconds"]
colorprinter.message("Job %d submitted %d minutes ago. Status: '%s'. Destination directory: %s." % (jid, jobtime / 60, jobstate, jobdir))
else:
colorprinter.message("Job %d submitted at %s %s. Status: '%s'. Destination directory unknown." % (jid, tokens[5], tokens[6], jobstate))
return True | [
"def",
"query",
"(",
"logfile",
",",
"jobID",
"=",
"None",
")",
":",
"joblist",
"=",
"logfile",
".",
"readFromLogfile",
"(",
")",
"if",
"jobID",
"and",
"type",
"(",
"jobID",
")",
"==",
"type",
"(",
"1",
")",
":",
"command",
"=",
"[",
"'qstat'",
",",
"'-j'",
",",
"str",
"(",
"jobID",
")",
"]",
"else",
":",
"command",
"=",
"[",
"'qstat'",
"]",
"processoutput",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"output",
"=",
"processoutput",
"[",
"0",
"]",
"serror",
"=",
"processoutput",
"[",
"1",
"]",
"# Form command",
"jobs",
"=",
"{",
"}",
"if",
"type",
"(",
"jobID",
")",
"==",
"type",
"(",
"1",
")",
":",
"if",
"serror",
".",
"find",
"(",
"\"Following jobs do not exist\"",
")",
"!=",
"-",
"1",
":",
"return",
"False",
"else",
":",
"return",
"True",
"if",
"not",
"output",
".",
"strip",
"(",
")",
":",
"colorprinter",
".",
"message",
"(",
"\"No jobs running at present.\"",
")",
"output",
"=",
"output",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"len",
"(",
"output",
")",
">",
"2",
":",
"for",
"line",
"in",
"output",
"[",
"2",
":",
"]",
":",
"# We assume that our script names contain no spaces for the parsing below to work",
"tokens",
"=",
"line",
".",
"split",
"(",
")",
"jid",
"=",
"int",
"(",
"tokens",
"[",
"0",
"]",
")",
"jobstate",
"=",
"tokens",
"[",
"4",
"]",
"details",
"=",
"{",
"\"jobid\"",
":",
"jid",
",",
"\"prior\"",
":",
"tokens",
"[",
"1",
"]",
",",
"\"name\"",
":",
"tokens",
"[",
"2",
"]",
",",
"\"user\"",
":",
"tokens",
"[",
"3",
"]",
",",
"\"state\"",
":",
"jobstate",
",",
"\"submit/start at\"",
":",
"\"%s %s\"",
"%",
"(",
"tokens",
"[",
"5",
"]",
",",
"tokens",
"[",
"6",
"]",
")",
"}",
"jataskID",
"=",
"0",
"if",
"jobstate",
"==",
"\"r\"",
":",
"details",
"[",
"\"queue\"",
"]",
"=",
"tokens",
"[",
"7",
"]",
"details",
"[",
"\"slots\"",
"]",
"=",
"tokens",
"[",
"8",
"]",
"elif",
"jobstate",
"==",
"\"qw\"",
":",
"details",
"[",
"\"slots\"",
"]",
"=",
"tokens",
"[",
"7",
"]",
"if",
"len",
"(",
"tokens",
")",
">=",
"9",
":",
"jataskID",
"=",
"tokens",
"[",
"8",
"]",
"details",
"[",
"\"ja-task-ID\"",
"]",
"=",
"jataskID",
"if",
"len",
"(",
"tokens",
")",
">",
"9",
":",
"jataskID",
"=",
"tokens",
"[",
"9",
"]",
"details",
"[",
"\"ja-task-ID\"",
"]",
"=",
"jataskID",
"jobs",
"[",
"jid",
"]",
"=",
"jobs",
".",
"get",
"(",
"jid",
")",
"or",
"{",
"}",
"jobs",
"[",
"jid",
"]",
"[",
"jataskID",
"]",
"=",
"details",
"if",
"joblist",
".",
"get",
"(",
"jid",
")",
":",
"jobdir",
"=",
"joblist",
"[",
"jid",
"]",
"[",
"\"Directory\"",
"]",
"jobtime",
"=",
"joblist",
"[",
"jid",
"]",
"[",
"\"TimeInSeconds\"",
"]",
"colorprinter",
".",
"message",
"(",
"\"Job %d submitted %d minutes ago. Status: '%s'. Destination directory: %s.\"",
"%",
"(",
"jid",
",",
"jobtime",
"/",
"60",
",",
"jobstate",
",",
"jobdir",
")",
")",
"else",
":",
"colorprinter",
".",
"message",
"(",
"\"Job %d submitted at %s %s. Status: '%s'. Destination directory unknown.\"",
"%",
"(",
"jid",
",",
"tokens",
"[",
"5",
"]",
",",
"tokens",
"[",
"6",
"]",
",",
"jobstate",
")",
")",
"return",
"True"
]
| If jobID is an integer then return False if the job has finished and True if it is still running.
Otherwise, returns a table of jobs run by the user. | [
"If",
"jobID",
"is",
"an",
"integer",
"then",
"return",
"False",
"if",
"the",
"job",
"has",
"finished",
"and",
"True",
"if",
"it",
"is",
"still",
"running",
".",
"Otherwise",
"returns",
"a",
"table",
"of",
"jobs",
"run",
"by",
"the",
"user",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fragments/hpc/SGE.py#L150-L210 | train |
PBR/MQ2 | MQ2/__init__.py | set_tmp_folder | def set_tmp_folder():
""" Create a temporary folder using the current time in which
the zip can be extracted and which should be destroyed afterward.
"""
output = "%s" % datetime.datetime.now()
for char in [' ', ':', '.', '-']:
output = output.replace(char, '')
output.strip()
tmp_folder = os.path.join(tempfile.gettempdir(), output)
return tmp_folder | python | def set_tmp_folder():
""" Create a temporary folder using the current time in which
the zip can be extracted and which should be destroyed afterward.
"""
output = "%s" % datetime.datetime.now()
for char in [' ', ':', '.', '-']:
output = output.replace(char, '')
output.strip()
tmp_folder = os.path.join(tempfile.gettempdir(), output)
return tmp_folder | [
"def",
"set_tmp_folder",
"(",
")",
":",
"output",
"=",
"\"%s\"",
"%",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"for",
"char",
"in",
"[",
"' '",
",",
"':'",
",",
"'.'",
",",
"'-'",
"]",
":",
"output",
"=",
"output",
".",
"replace",
"(",
"char",
",",
"''",
")",
"output",
".",
"strip",
"(",
")",
"tmp_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"output",
")",
"return",
"tmp_folder"
]
| Create a temporary folder using the current time in which
the zip can be extracted and which should be destroyed afterward. | [
"Create",
"a",
"temporary",
"folder",
"using",
"the",
"current",
"time",
"in",
"which",
"the",
"zip",
"can",
"be",
"extracted",
"and",
"which",
"should",
"be",
"destroyed",
"afterward",
"."
]
| 6d84dea47e6751333004743f588f03158e35c28d | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/__init__.py#L39-L48 | train |
projectshift/shift-boiler | boiler/log/file.py | file_logger | def file_logger(app, level=None):
"""
Get file logger
Returns configured fire logger ready to be attached to app
:param app: application instance
:param level: log this level
:return: RotatingFileHandler
"""
path = os.path.join(os.getcwd(), 'var', 'logs', 'app.log')
max_bytes = 1024 * 1024 * 2
file_handler = RotatingFileHandler(
filename=path,
mode='a',
maxBytes=max_bytes,
backupCount=10
)
if level is None: level = logging.INFO
file_handler.setLevel(level)
log_format = '%(asctime)s %(levelname)s: %(message)s'
log_format += ' [in %(pathname)s:%(lineno)d]'
file_handler.setFormatter(logging.Formatter(log_format))
return file_handler | python | def file_logger(app, level=None):
"""
Get file logger
Returns configured fire logger ready to be attached to app
:param app: application instance
:param level: log this level
:return: RotatingFileHandler
"""
path = os.path.join(os.getcwd(), 'var', 'logs', 'app.log')
max_bytes = 1024 * 1024 * 2
file_handler = RotatingFileHandler(
filename=path,
mode='a',
maxBytes=max_bytes,
backupCount=10
)
if level is None: level = logging.INFO
file_handler.setLevel(level)
log_format = '%(asctime)s %(levelname)s: %(message)s'
log_format += ' [in %(pathname)s:%(lineno)d]'
file_handler.setFormatter(logging.Formatter(log_format))
return file_handler | [
"def",
"file_logger",
"(",
"app",
",",
"level",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'var'",
",",
"'logs'",
",",
"'app.log'",
")",
"max_bytes",
"=",
"1024",
"*",
"1024",
"*",
"2",
"file_handler",
"=",
"RotatingFileHandler",
"(",
"filename",
"=",
"path",
",",
"mode",
"=",
"'a'",
",",
"maxBytes",
"=",
"max_bytes",
",",
"backupCount",
"=",
"10",
")",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"logging",
".",
"INFO",
"file_handler",
".",
"setLevel",
"(",
"level",
")",
"log_format",
"=",
"'%(asctime)s %(levelname)s: %(message)s'",
"log_format",
"+=",
"' [in %(pathname)s:%(lineno)d]'",
"file_handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"log_format",
")",
")",
"return",
"file_handler"
]
| Get file logger
Returns configured fire logger ready to be attached to app
:param app: application instance
:param level: log this level
:return: RotatingFileHandler | [
"Get",
"file",
"logger",
"Returns",
"configured",
"fire",
"logger",
"ready",
"to",
"be",
"attached",
"to",
"app"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/log/file.py#L5-L31 | train |
TUNE-Archive/freight_forwarder | freight_forwarder/image.py | Image.tag | def tag(self, repository_tag, tags=[]):
"""
Tags image with one or more tags.
Raises exception on failure.
"""
if not isinstance(repository_tag, six.string_types):
raise TypeError('repository_tag must be a string')
if not isinstance(tags, list):
raise TypeError('tags must be a list.')
if ':' in repository_tag:
repository, tag = repository_tag.split(':')
tags.append(tag)
else:
repository = repository_tag
if not tags:
tags.append('latest')
for tag in tags:
repo_tag = "{0}:{1}".format(repository, tag)
if repo_tag not in self.repo_tags:
logger.info("Tagging Image: {0} Repo Tag: {1}".format(self.identifier, repo_tag))
self.repo_tags = self.repo_tags + (repo_tag, )
# always going to force tags until a feature is added to allow users to specify.
try:
self.client.tag(self.id, repository, tag)
except:
self.client.tag(self.id, repository, tag, force=True) | python | def tag(self, repository_tag, tags=[]):
"""
Tags image with one or more tags.
Raises exception on failure.
"""
if not isinstance(repository_tag, six.string_types):
raise TypeError('repository_tag must be a string')
if not isinstance(tags, list):
raise TypeError('tags must be a list.')
if ':' in repository_tag:
repository, tag = repository_tag.split(':')
tags.append(tag)
else:
repository = repository_tag
if not tags:
tags.append('latest')
for tag in tags:
repo_tag = "{0}:{1}".format(repository, tag)
if repo_tag not in self.repo_tags:
logger.info("Tagging Image: {0} Repo Tag: {1}".format(self.identifier, repo_tag))
self.repo_tags = self.repo_tags + (repo_tag, )
# always going to force tags until a feature is added to allow users to specify.
try:
self.client.tag(self.id, repository, tag)
except:
self.client.tag(self.id, repository, tag, force=True) | [
"def",
"tag",
"(",
"self",
",",
"repository_tag",
",",
"tags",
"=",
"[",
"]",
")",
":",
"if",
"not",
"isinstance",
"(",
"repository_tag",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'repository_tag must be a string'",
")",
"if",
"not",
"isinstance",
"(",
"tags",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'tags must be a list.'",
")",
"if",
"':'",
"in",
"repository_tag",
":",
"repository",
",",
"tag",
"=",
"repository_tag",
".",
"split",
"(",
"':'",
")",
"tags",
".",
"append",
"(",
"tag",
")",
"else",
":",
"repository",
"=",
"repository_tag",
"if",
"not",
"tags",
":",
"tags",
".",
"append",
"(",
"'latest'",
")",
"for",
"tag",
"in",
"tags",
":",
"repo_tag",
"=",
"\"{0}:{1}\"",
".",
"format",
"(",
"repository",
",",
"tag",
")",
"if",
"repo_tag",
"not",
"in",
"self",
".",
"repo_tags",
":",
"logger",
".",
"info",
"(",
"\"Tagging Image: {0} Repo Tag: {1}\"",
".",
"format",
"(",
"self",
".",
"identifier",
",",
"repo_tag",
")",
")",
"self",
".",
"repo_tags",
"=",
"self",
".",
"repo_tags",
"+",
"(",
"repo_tag",
",",
")",
"# always going to force tags until a feature is added to allow users to specify.",
"try",
":",
"self",
".",
"client",
".",
"tag",
"(",
"self",
".",
"id",
",",
"repository",
",",
"tag",
")",
"except",
":",
"self",
".",
"client",
".",
"tag",
"(",
"self",
".",
"id",
",",
"repository",
",",
"tag",
",",
"force",
"=",
"True",
")"
]
| Tags image with one or more tags.
Raises exception on failure. | [
"Tags",
"image",
"with",
"one",
"or",
"more",
"tags",
"."
]
| 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/image.py#L52-L84 | train |
TUNE-Archive/freight_forwarder | freight_forwarder/image.py | Image.build | def build(client, repository_tag, docker_file, tag=None, use_cache=False):
"""
Build a docker image
"""
if not isinstance(client, docker.Client):
raise TypeError("client needs to be of type docker.Client.")
if not isinstance(docker_file, six.string_types) or not os.path.exists(docker_file):
# TODO: need to add path stuff for git and http etc.
raise Exception("docker file path doesn't exist: {0}".format(docker_file))
if not isinstance(repository_tag, six.string_types):
raise TypeError('repository must be a string')
if not tag:
tag = 'latest'
if not isinstance(use_cache, bool):
raise TypeError("use_cache must be a bool. {0} was passed.".format(use_cache))
no_cache = not use_cache
if ':' not in repository_tag:
repository_tag = "{0}:{1}".format(repository_tag, tag)
file_obj = None
try:
if os.path.isfile(docker_file):
path = os.getcwd()
docker_file = "./{0}".format(os.path.relpath(docker_file))
# TODO: support using file_obj in the future. Needed for post pre hooks and the injector.
# with open(docker_file) as Dockerfile:
# testing = Dockerfile.read()
# file_obj = BytesIO(testing.encode('utf-8'))
response = client.build(
path=path,
nocache=no_cache,
# custom_context=True,
dockerfile=docker_file,
# fileobj=file_obj,
tag=repository_tag,
rm=True,
stream=True
)
else:
response = client.build(path=docker_file, tag=repository_tag, rm=True, nocache=no_cache, stream=True)
except Exception as e:
raise e
finally:
if file_obj:
file_obj.close()
parse_stream(response)
client.close()
return Image(client, repository_tag) | python | def build(client, repository_tag, docker_file, tag=None, use_cache=False):
"""
Build a docker image
"""
if not isinstance(client, docker.Client):
raise TypeError("client needs to be of type docker.Client.")
if not isinstance(docker_file, six.string_types) or not os.path.exists(docker_file):
# TODO: need to add path stuff for git and http etc.
raise Exception("docker file path doesn't exist: {0}".format(docker_file))
if not isinstance(repository_tag, six.string_types):
raise TypeError('repository must be a string')
if not tag:
tag = 'latest'
if not isinstance(use_cache, bool):
raise TypeError("use_cache must be a bool. {0} was passed.".format(use_cache))
no_cache = not use_cache
if ':' not in repository_tag:
repository_tag = "{0}:{1}".format(repository_tag, tag)
file_obj = None
try:
if os.path.isfile(docker_file):
path = os.getcwd()
docker_file = "./{0}".format(os.path.relpath(docker_file))
# TODO: support using file_obj in the future. Needed for post pre hooks and the injector.
# with open(docker_file) as Dockerfile:
# testing = Dockerfile.read()
# file_obj = BytesIO(testing.encode('utf-8'))
response = client.build(
path=path,
nocache=no_cache,
# custom_context=True,
dockerfile=docker_file,
# fileobj=file_obj,
tag=repository_tag,
rm=True,
stream=True
)
else:
response = client.build(path=docker_file, tag=repository_tag, rm=True, nocache=no_cache, stream=True)
except Exception as e:
raise e
finally:
if file_obj:
file_obj.close()
parse_stream(response)
client.close()
return Image(client, repository_tag) | [
"def",
"build",
"(",
"client",
",",
"repository_tag",
",",
"docker_file",
",",
"tag",
"=",
"None",
",",
"use_cache",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"client",
",",
"docker",
".",
"Client",
")",
":",
"raise",
"TypeError",
"(",
"\"client needs to be of type docker.Client.\"",
")",
"if",
"not",
"isinstance",
"(",
"docker_file",
",",
"six",
".",
"string_types",
")",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"docker_file",
")",
":",
"# TODO: need to add path stuff for git and http etc.",
"raise",
"Exception",
"(",
"\"docker file path doesn't exist: {0}\"",
".",
"format",
"(",
"docker_file",
")",
")",
"if",
"not",
"isinstance",
"(",
"repository_tag",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'repository must be a string'",
")",
"if",
"not",
"tag",
":",
"tag",
"=",
"'latest'",
"if",
"not",
"isinstance",
"(",
"use_cache",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"use_cache must be a bool. {0} was passed.\"",
".",
"format",
"(",
"use_cache",
")",
")",
"no_cache",
"=",
"not",
"use_cache",
"if",
"':'",
"not",
"in",
"repository_tag",
":",
"repository_tag",
"=",
"\"{0}:{1}\"",
".",
"format",
"(",
"repository_tag",
",",
"tag",
")",
"file_obj",
"=",
"None",
"try",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"docker_file",
")",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"docker_file",
"=",
"\"./{0}\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"docker_file",
")",
")",
"# TODO: support using file_obj in the future. Needed for post pre hooks and the injector.",
"# with open(docker_file) as Dockerfile:",
"# testing = Dockerfile.read()",
"# file_obj = BytesIO(testing.encode('utf-8'))",
"response",
"=",
"client",
".",
"build",
"(",
"path",
"=",
"path",
",",
"nocache",
"=",
"no_cache",
",",
"# custom_context=True,",
"dockerfile",
"=",
"docker_file",
",",
"# fileobj=file_obj,",
"tag",
"=",
"repository_tag",
",",
"rm",
"=",
"True",
",",
"stream",
"=",
"True",
")",
"else",
":",
"response",
"=",
"client",
".",
"build",
"(",
"path",
"=",
"docker_file",
",",
"tag",
"=",
"repository_tag",
",",
"rm",
"=",
"True",
",",
"nocache",
"=",
"no_cache",
",",
"stream",
"=",
"True",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"finally",
":",
"if",
"file_obj",
":",
"file_obj",
".",
"close",
"(",
")",
"parse_stream",
"(",
"response",
")",
"client",
".",
"close",
"(",
")",
"return",
"Image",
"(",
"client",
",",
"repository_tag",
")"
]
| Build a docker image | [
"Build",
"a",
"docker",
"image"
]
| 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/image.py#L322-L378 | train |
uw-it-aca/uw-restclients-sws | uw_sws/enrollment.py | get_grades_by_regid_and_term | def get_grades_by_regid_and_term(regid, term):
"""
Returns a StudentGrades model for the regid and term.
"""
url = "{}/{},{},{}.json".format(enrollment_res_url_prefix,
term.year,
term.quarter,
regid)
return _json_to_grades(get_resource(url), regid, term) | python | def get_grades_by_regid_and_term(regid, term):
"""
Returns a StudentGrades model for the regid and term.
"""
url = "{}/{},{},{}.json".format(enrollment_res_url_prefix,
term.year,
term.quarter,
regid)
return _json_to_grades(get_resource(url), regid, term) | [
"def",
"get_grades_by_regid_and_term",
"(",
"regid",
",",
"term",
")",
":",
"url",
"=",
"\"{}/{},{},{}.json\"",
".",
"format",
"(",
"enrollment_res_url_prefix",
",",
"term",
".",
"year",
",",
"term",
".",
"quarter",
",",
"regid",
")",
"return",
"_json_to_grades",
"(",
"get_resource",
"(",
"url",
")",
",",
"regid",
",",
"term",
")"
]
| Returns a StudentGrades model for the regid and term. | [
"Returns",
"a",
"StudentGrades",
"model",
"for",
"the",
"regid",
"and",
"term",
"."
]
| 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/enrollment.py#L21-L29 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber._requires_refresh_token | def _requires_refresh_token(self):
"""
Check if a refresh of the token is needed
"""
expires_on = datetime.datetime.strptime(
self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ')
refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
return expires_on < refresh | python | def _requires_refresh_token(self):
"""
Check if a refresh of the token is needed
"""
expires_on = datetime.datetime.strptime(
self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ')
refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
return expires_on < refresh | [
"def",
"_requires_refresh_token",
"(",
"self",
")",
":",
"expires_on",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'expiresOn'",
"]",
",",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
"refresh",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"30",
")",
"return",
"expires_on",
"<",
"refresh"
]
| Check if a refresh of the token is needed | [
"Check",
"if",
"a",
"refresh",
"of",
"the",
"token",
"is",
"needed"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L32-L39 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber._request_token | def _request_token(self, force=False):
"""
Request a new auth token
"""
if self.login_data is None:
raise RuntimeError("Don't have a token to refresh")
if not force:
if not self._requires_refresh_token():
# no need to refresh as token is valid
return True
headers = {
"Accept": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "account/RefreshToken"
response = requests.get(url, headers=headers, timeout=10)
if response.status_code != 200:
return False
refresh_data = response.json()
if 'token' not in refresh_data:
return False
self.login_data['token']['accessToken'] = refresh_data['accessToken']
self.login_data['token']['issuedOn'] = refresh_data['issuedOn']
self.login_data['token']['expiresOn'] = refresh_data['expiresOn']
return True | python | def _request_token(self, force=False):
"""
Request a new auth token
"""
if self.login_data is None:
raise RuntimeError("Don't have a token to refresh")
if not force:
if not self._requires_refresh_token():
# no need to refresh as token is valid
return True
headers = {
"Accept": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "account/RefreshToken"
response = requests.get(url, headers=headers, timeout=10)
if response.status_code != 200:
return False
refresh_data = response.json()
if 'token' not in refresh_data:
return False
self.login_data['token']['accessToken'] = refresh_data['accessToken']
self.login_data['token']['issuedOn'] = refresh_data['issuedOn']
self.login_data['token']['expiresOn'] = refresh_data['expiresOn']
return True | [
"def",
"_request_token",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"login_data",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Don't have a token to refresh\"",
")",
"if",
"not",
"force",
":",
"if",
"not",
"self",
".",
"_requires_refresh_token",
"(",
")",
":",
"# no need to refresh as token is valid",
"return",
"True",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
",",
"'Authorization'",
":",
"'Bearer '",
"+",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'accessToken'",
"]",
"}",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"\"account/RefreshToken\"",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"10",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"return",
"False",
"refresh_data",
"=",
"response",
".",
"json",
"(",
")",
"if",
"'token'",
"not",
"in",
"refresh_data",
":",
"return",
"False",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'accessToken'",
"]",
"=",
"refresh_data",
"[",
"'accessToken'",
"]",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'issuedOn'",
"]",
"=",
"refresh_data",
"[",
"'issuedOn'",
"]",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'expiresOn'",
"]",
"=",
"refresh_data",
"[",
"'expiresOn'",
"]",
"return",
"True"
]
| Request a new auth token | [
"Request",
"a",
"new",
"auth",
"token"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L41-L75 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_home | def get_home(self, home_id=None):
"""
Get the data about a home
"""
now = datetime.datetime.utcnow()
if self.home and now < self.home_refresh_at:
return self.home
if not self._do_auth():
raise RuntimeError("Unable to login")
if home_id is None:
home_id = self.home_id
url = self.api_base_url + "Home/GetHomeById"
params = {
"homeId": home_id
}
headers = {
"Accept": "application/json",
'Authorization':
'bearer ' + self.login_data['token']['accessToken']
}
response = requests.get(
url, params=params, headers=headers, timeout=10)
if response.status_code != 200:
raise RuntimeError(
"{} response code when getting home".format(
response.status_code))
home = response.json()
if self.cache_home:
self.home = home
self.home_refresh_at = (datetime.datetime.utcnow()
+ datetime.timedelta(minutes=5))
return home | python | def get_home(self, home_id=None):
"""
Get the data about a home
"""
now = datetime.datetime.utcnow()
if self.home and now < self.home_refresh_at:
return self.home
if not self._do_auth():
raise RuntimeError("Unable to login")
if home_id is None:
home_id = self.home_id
url = self.api_base_url + "Home/GetHomeById"
params = {
"homeId": home_id
}
headers = {
"Accept": "application/json",
'Authorization':
'bearer ' + self.login_data['token']['accessToken']
}
response = requests.get(
url, params=params, headers=headers, timeout=10)
if response.status_code != 200:
raise RuntimeError(
"{} response code when getting home".format(
response.status_code))
home = response.json()
if self.cache_home:
self.home = home
self.home_refresh_at = (datetime.datetime.utcnow()
+ datetime.timedelta(minutes=5))
return home | [
"def",
"get_home",
"(",
"self",
",",
"home_id",
"=",
"None",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"self",
".",
"home",
"and",
"now",
"<",
"self",
".",
"home_refresh_at",
":",
"return",
"self",
".",
"home",
"if",
"not",
"self",
".",
"_do_auth",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to login\"",
")",
"if",
"home_id",
"is",
"None",
":",
"home_id",
"=",
"self",
".",
"home_id",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"\"Home/GetHomeById\"",
"params",
"=",
"{",
"\"homeId\"",
":",
"home_id",
"}",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
",",
"'Authorization'",
":",
"'bearer '",
"+",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'accessToken'",
"]",
"}",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"10",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"RuntimeError",
"(",
"\"{} response code when getting home\"",
".",
"format",
"(",
"response",
".",
"status_code",
")",
")",
"home",
"=",
"response",
".",
"json",
"(",
")",
"if",
"self",
".",
"cache_home",
":",
"self",
".",
"home",
"=",
"home",
"self",
".",
"home_refresh_at",
"=",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"5",
")",
")",
"return",
"home"
]
| Get the data about a home | [
"Get",
"the",
"data",
"about",
"a",
"home"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L121-L162 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zones | def get_zones(self):
"""
Get all zones
"""
home_data = self.get_home()
if not home_data['isSuccess']:
return []
zones = []
for receiver in home_data['data']['receivers']:
for zone in receiver['zones']:
zones.append(zone)
return zones | python | def get_zones(self):
"""
Get all zones
"""
home_data = self.get_home()
if not home_data['isSuccess']:
return []
zones = []
for receiver in home_data['data']['receivers']:
for zone in receiver['zones']:
zones.append(zone)
return zones | [
"def",
"get_zones",
"(",
"self",
")",
":",
"home_data",
"=",
"self",
".",
"get_home",
"(",
")",
"if",
"not",
"home_data",
"[",
"'isSuccess'",
"]",
":",
"return",
"[",
"]",
"zones",
"=",
"[",
"]",
"for",
"receiver",
"in",
"home_data",
"[",
"'data'",
"]",
"[",
"'receivers'",
"]",
":",
"for",
"zone",
"in",
"receiver",
"[",
"'zones'",
"]",
":",
"zones",
".",
"append",
"(",
"zone",
")",
"return",
"zones"
]
| Get all zones | [
"Get",
"all",
"zones"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L164-L178 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone_names | def get_zone_names(self):
"""
Get the name of all zones
"""
zone_names = []
for zone in self.get_zones():
zone_names.append(zone['name'])
return zone_names | python | def get_zone_names(self):
"""
Get the name of all zones
"""
zone_names = []
for zone in self.get_zones():
zone_names.append(zone['name'])
return zone_names | [
"def",
"get_zone_names",
"(",
"self",
")",
":",
"zone_names",
"=",
"[",
"]",
"for",
"zone",
"in",
"self",
".",
"get_zones",
"(",
")",
":",
"zone_names",
".",
"append",
"(",
"zone",
"[",
"'name'",
"]",
")",
"return",
"zone_names"
]
| Get the name of all zones | [
"Get",
"the",
"name",
"of",
"all",
"zones"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L180-L188 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone | def get_zone(self, zone_name):
"""
Get the information about a particular zone
"""
for zone in self.get_zones():
if zone_name == zone['name']:
return zone
raise RuntimeError("Unknown zone") | python | def get_zone(self, zone_name):
"""
Get the information about a particular zone
"""
for zone in self.get_zones():
if zone_name == zone['name']:
return zone
raise RuntimeError("Unknown zone") | [
"def",
"get_zone",
"(",
"self",
",",
"zone_name",
")",
":",
"for",
"zone",
"in",
"self",
".",
"get_zones",
"(",
")",
":",
"if",
"zone_name",
"==",
"zone",
"[",
"'name'",
"]",
":",
"return",
"zone",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")"
]
| Get the information about a particular zone | [
"Get",
"the",
"information",
"about",
"a",
"particular",
"zone"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L190-L198 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone_temperature | def get_zone_temperature(self, zone_name):
"""
Get the temperature for a zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['currentTemperature'] | python | def get_zone_temperature(self, zone_name):
"""
Get the temperature for a zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['currentTemperature'] | [
"def",
"get_zone_temperature",
"(",
"self",
",",
"zone_name",
")",
":",
"zone",
"=",
"self",
".",
"get_zone",
"(",
"zone_name",
")",
"if",
"zone",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")",
"return",
"zone",
"[",
"'currentTemperature'",
"]"
]
| Get the temperature for a zone | [
"Get",
"the",
"temperature",
"for",
"a",
"zone"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L210-L219 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_target_temperature_by_id | def set_target_temperature_by_id(self, zone_id, target_temperature):
"""
Set the target temperature for a zone by id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"TargetTemperature": target_temperature
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/ZoneTargetTemperature"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
zone_change_data = response.json()
return zone_change_data.get("isSuccess", False) | python | def set_target_temperature_by_id(self, zone_id, target_temperature):
"""
Set the target temperature for a zone by id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"TargetTemperature": target_temperature
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/ZoneTargetTemperature"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
zone_change_data = response.json()
return zone_change_data.get("isSuccess", False) | [
"def",
"set_target_temperature_by_id",
"(",
"self",
",",
"zone_id",
",",
"target_temperature",
")",
":",
"if",
"not",
"self",
".",
"_do_auth",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to login\"",
")",
"data",
"=",
"{",
"\"ZoneId\"",
":",
"zone_id",
",",
"\"TargetTemperature\"",
":",
"target_temperature",
"}",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
",",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"'Authorization'",
":",
"'Bearer '",
"+",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'accessToken'",
"]",
"}",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"\"Home/ZoneTargetTemperature\"",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"10",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"return",
"False",
"zone_change_data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"zone_change_data",
".",
"get",
"(",
"\"isSuccess\"",
",",
"False",
")"
]
| Set the target temperature for a zone by id | [
"Set",
"the",
"target",
"temperature",
"for",
"a",
"zone",
"by",
"id"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L243-L272 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_target_temperture_by_name | def set_target_temperture_by_name(self, zone_name, target_temperature):
"""
Set the target temperature for a zone by name
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_target_temperature_by_id(zone["zoneId"],
target_temperature) | python | def set_target_temperture_by_name(self, zone_name, target_temperature):
"""
Set the target temperature for a zone by name
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_target_temperature_by_id(zone["zoneId"],
target_temperature) | [
"def",
"set_target_temperture_by_name",
"(",
"self",
",",
"zone_name",
",",
"target_temperature",
")",
":",
"zone",
"=",
"self",
".",
"get_zone",
"(",
"zone_name",
")",
"if",
"zone",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")",
"return",
"self",
".",
"set_target_temperature_by_id",
"(",
"zone",
"[",
"\"zoneId\"",
"]",
",",
"target_temperature",
")"
]
| Set the target temperature for a zone by name | [
"Set",
"the",
"target",
"temperature",
"for",
"a",
"zone",
"by",
"name"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L274-L284 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.activate_boost_by_id | def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1):
"""
Activate boost for a zone based on the numeric id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
zones = [zone_id]
data = {
"ZoneIds": zones,
"NumberOfHours": num_hours,
"TargetTemperature": target_temperature
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/ActivateZoneBoost"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
boost_data = response.json()
return boost_data.get("isSuccess", False) | python | def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1):
"""
Activate boost for a zone based on the numeric id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
zones = [zone_id]
data = {
"ZoneIds": zones,
"NumberOfHours": num_hours,
"TargetTemperature": target_temperature
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/ActivateZoneBoost"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
boost_data = response.json()
return boost_data.get("isSuccess", False) | [
"def",
"activate_boost_by_id",
"(",
"self",
",",
"zone_id",
",",
"target_temperature",
",",
"num_hours",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"_do_auth",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to login\"",
")",
"zones",
"=",
"[",
"zone_id",
"]",
"data",
"=",
"{",
"\"ZoneIds\"",
":",
"zones",
",",
"\"NumberOfHours\"",
":",
"num_hours",
",",
"\"TargetTemperature\"",
":",
"target_temperature",
"}",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
",",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"'Authorization'",
":",
"'Bearer '",
"+",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'accessToken'",
"]",
"}",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"\"Home/ActivateZoneBoost\"",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"10",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"return",
"False",
"boost_data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"boost_data",
".",
"get",
"(",
"\"isSuccess\"",
",",
"False",
")"
]
| Activate boost for a zone based on the numeric id | [
"Activate",
"boost",
"for",
"a",
"zone",
"based",
"on",
"the",
"numeric",
"id"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L286-L317 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.activate_boost_by_name | def activate_boost_by_name(self,
zone_name,
target_temperature,
num_hours=1):
"""
Activate boost by the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.activate_boost_by_id(zone["zoneId"],
target_temperature, num_hours) | python | def activate_boost_by_name(self,
zone_name,
target_temperature,
num_hours=1):
"""
Activate boost by the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.activate_boost_by_id(zone["zoneId"],
target_temperature, num_hours) | [
"def",
"activate_boost_by_name",
"(",
"self",
",",
"zone_name",
",",
"target_temperature",
",",
"num_hours",
"=",
"1",
")",
":",
"zone",
"=",
"self",
".",
"get_zone",
"(",
"zone_name",
")",
"if",
"zone",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")",
"return",
"self",
".",
"activate_boost_by_id",
"(",
"zone",
"[",
"\"zoneId\"",
"]",
",",
"target_temperature",
",",
"num_hours",
")"
]
| Activate boost by the name of the zone | [
"Activate",
"boost",
"by",
"the",
"name",
"of",
"the",
"zone"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L319-L332 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.deactivate_boost_by_name | def deactivate_boost_by_name(self, zone_name):
"""
Deactivate boost by the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.deactivate_boost_by_id(zone["zoneId"]) | python | def deactivate_boost_by_name(self, zone_name):
"""
Deactivate boost by the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.deactivate_boost_by_id(zone["zoneId"]) | [
"def",
"deactivate_boost_by_name",
"(",
"self",
",",
"zone_name",
")",
":",
"zone",
"=",
"self",
".",
"get_zone",
"(",
"zone_name",
")",
"if",
"zone",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")",
"return",
"self",
".",
"deactivate_boost_by_id",
"(",
"zone",
"[",
"\"zoneId\"",
"]",
")"
]
| Deactivate boost by the name of the zone | [
"Deactivate",
"boost",
"by",
"the",
"name",
"of",
"the",
"zone"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L362-L371 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_mode_by_id | def set_mode_by_id(self, zone_id, mode):
"""
Set the mode by using the zone id
Supported zones are available in the enum Mode
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"mode": mode.value
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/SetZoneMode"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
mode_data = response.json()
return mode_data.get("isSuccess", False) | python | def set_mode_by_id(self, zone_id, mode):
"""
Set the mode by using the zone id
Supported zones are available in the enum Mode
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"mode": mode.value
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/SetZoneMode"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
mode_data = response.json()
return mode_data.get("isSuccess", False) | [
"def",
"set_mode_by_id",
"(",
"self",
",",
"zone_id",
",",
"mode",
")",
":",
"if",
"not",
"self",
".",
"_do_auth",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to login\"",
")",
"data",
"=",
"{",
"\"ZoneId\"",
":",
"zone_id",
",",
"\"mode\"",
":",
"mode",
".",
"value",
"}",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
",",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"'Authorization'",
":",
"'Bearer '",
"+",
"self",
".",
"login_data",
"[",
"'token'",
"]",
"[",
"'accessToken'",
"]",
"}",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"\"Home/SetZoneMode\"",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"10",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"return",
"False",
"mode_data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"mode_data",
".",
"get",
"(",
"\"isSuccess\"",
",",
"False",
")"
]
| Set the mode by using the zone id
Supported zones are available in the enum Mode | [
"Set",
"the",
"mode",
"by",
"using",
"the",
"zone",
"id",
"Supported",
"zones",
"are",
"available",
"in",
"the",
"enum",
"Mode"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L373-L402 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_mode_by_name | def set_mode_by_name(self, zone_name, mode):
"""
Set the mode by using the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_mode_by_id(zone["zoneId"], mode) | python | def set_mode_by_name(self, zone_name, mode):
"""
Set the mode by using the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_mode_by_id(zone["zoneId"], mode) | [
"def",
"set_mode_by_name",
"(",
"self",
",",
"zone_name",
",",
"mode",
")",
":",
"zone",
"=",
"self",
".",
"get_zone",
"(",
"zone_name",
")",
"if",
"zone",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")",
"return",
"self",
".",
"set_mode_by_id",
"(",
"zone",
"[",
"\"zoneId\"",
"]",
",",
"mode",
")"
]
| Set the mode by using the name of the zone | [
"Set",
"the",
"mode",
"by",
"using",
"the",
"name",
"of",
"the",
"zone"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L404-L412 | train |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone_mode | def get_zone_mode(self, zone_name):
"""
Get the mode for a zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return ZoneMode(zone['mode']) | python | def get_zone_mode(self, zone_name):
"""
Get the mode for a zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return ZoneMode(zone['mode']) | [
"def",
"get_zone_mode",
"(",
"self",
",",
"zone_name",
")",
":",
"zone",
"=",
"self",
".",
"get_zone",
"(",
"zone_name",
")",
"if",
"zone",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")",
"return",
"ZoneMode",
"(",
"zone",
"[",
"'mode'",
"]",
")"
]
| Get the mode for a zone | [
"Get",
"the",
"mode",
"for",
"a",
"zone"
]
| 3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4 | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L414-L423 | train |
ABI-Software/MeshParser | src/meshparser/vrmlparser/parser.py | _convertToElementList | def _convertToElementList(elements_list):
"""
Take a list of element node indexes deliminated by -1 and convert
it into a list element node indexes list.
"""
elements = []
current_element = []
for node_index in elements_list:
if node_index == -1:
elements.append(current_element)
current_element = []
else:
current_element.append(node_index)
return elements | python | def _convertToElementList(elements_list):
"""
Take a list of element node indexes deliminated by -1 and convert
it into a list element node indexes list.
"""
elements = []
current_element = []
for node_index in elements_list:
if node_index == -1:
elements.append(current_element)
current_element = []
else:
current_element.append(node_index)
return elements | [
"def",
"_convertToElementList",
"(",
"elements_list",
")",
":",
"elements",
"=",
"[",
"]",
"current_element",
"=",
"[",
"]",
"for",
"node_index",
"in",
"elements_list",
":",
"if",
"node_index",
"==",
"-",
"1",
":",
"elements",
".",
"append",
"(",
"current_element",
")",
"current_element",
"=",
"[",
"]",
"else",
":",
"current_element",
".",
"append",
"(",
"node_index",
")",
"return",
"elements"
]
| Take a list of element node indexes deliminated by -1 and convert
it into a list element node indexes list. | [
"Take",
"a",
"list",
"of",
"element",
"node",
"indexes",
"deliminated",
"by",
"-",
"1",
"and",
"convert",
"it",
"into",
"a",
"list",
"element",
"node",
"indexes",
"list",
"."
]
| 08dc0ce7c44d0149b443261ff6d3708e28a928e7 | https://github.com/ABI-Software/MeshParser/blob/08dc0ce7c44d0149b443261ff6d3708e28a928e7/src/meshparser/vrmlparser/parser.py#L561-L575 | train |
projectshift/shift-boiler | boiler/jinja/filters.py | LocalizableFilterSet.get_locale | def get_locale(self):
"""
Get locale
Will extract locale from application, trying to get one from babel
first, then, if not available, will get one from app config
"""
if not self.locale:
try:
import flask_babel as babel
self.locale = str(babel.get_locale()).lower()
except ImportError:
from flask import current_app
self.locale = current_app.config['DEFAULT_LOCALE'].lower
return self.locale | python | def get_locale(self):
"""
Get locale
Will extract locale from application, trying to get one from babel
first, then, if not available, will get one from app config
"""
if not self.locale:
try:
import flask_babel as babel
self.locale = str(babel.get_locale()).lower()
except ImportError:
from flask import current_app
self.locale = current_app.config['DEFAULT_LOCALE'].lower
return self.locale | [
"def",
"get_locale",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"locale",
":",
"try",
":",
"import",
"flask_babel",
"as",
"babel",
"self",
".",
"locale",
"=",
"str",
"(",
"babel",
".",
"get_locale",
"(",
")",
")",
".",
"lower",
"(",
")",
"except",
"ImportError",
":",
"from",
"flask",
"import",
"current_app",
"self",
".",
"locale",
"=",
"current_app",
".",
"config",
"[",
"'DEFAULT_LOCALE'",
"]",
".",
"lower",
"return",
"self",
".",
"locale"
]
| Get locale
Will extract locale from application, trying to get one from babel
first, then, if not available, will get one from app config | [
"Get",
"locale",
"Will",
"extract",
"locale",
"from",
"application",
"trying",
"to",
"get",
"one",
"from",
"babel",
"first",
"then",
"if",
"not",
"available",
"will",
"get",
"one",
"from",
"app",
"config"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/jinja/filters.py#L15-L29 | train |
projectshift/shift-boiler | boiler/jinja/filters.py | LocalizableFilterSet.get_language | def get_language(self):
"""
Get language
If locale contains region, will cut that off. Returns just
the language code
"""
locale = self.get_locale()
language = locale
if '_' in locale:
language = locale[0:locale.index('_')]
return language | python | def get_language(self):
"""
Get language
If locale contains region, will cut that off. Returns just
the language code
"""
locale = self.get_locale()
language = locale
if '_' in locale:
language = locale[0:locale.index('_')]
return language | [
"def",
"get_language",
"(",
"self",
")",
":",
"locale",
"=",
"self",
".",
"get_locale",
"(",
")",
"language",
"=",
"locale",
"if",
"'_'",
"in",
"locale",
":",
"language",
"=",
"locale",
"[",
"0",
":",
"locale",
".",
"index",
"(",
"'_'",
")",
"]",
"return",
"language"
]
| Get language
If locale contains region, will cut that off. Returns just
the language code | [
"Get",
"language",
"If",
"locale",
"contains",
"region",
"will",
"cut",
"that",
"off",
".",
"Returns",
"just",
"the",
"language",
"code"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/jinja/filters.py#L31-L41 | train |
projectshift/shift-boiler | boiler/jinja/filters.py | HumanizeFilters.localize_humanize | def localize_humanize(self):
""" Setts current language to humanize """
import humanize
language = self.get_language()
if language != 'en':
humanize.i18n.activate(language) | python | def localize_humanize(self):
""" Setts current language to humanize """
import humanize
language = self.get_language()
if language != 'en':
humanize.i18n.activate(language) | [
"def",
"localize_humanize",
"(",
"self",
")",
":",
"import",
"humanize",
"language",
"=",
"self",
".",
"get_language",
"(",
")",
"if",
"language",
"!=",
"'en'",
":",
"humanize",
".",
"i18n",
".",
"activate",
"(",
"language",
")"
]
| Setts current language to humanize | [
"Setts",
"current",
"language",
"to",
"humanize"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/jinja/filters.py#L62-L67 | train |
projectshift/shift-boiler | boiler/jinja/filters.py | HumanizeFilters.get_filters | def get_filters(self):
""" Returns a dictionary of filters """
filters = dict()
for filter in self.get_filter_names():
filters[filter] = getattr(self, filter)
return filters | python | def get_filters(self):
""" Returns a dictionary of filters """
filters = dict()
for filter in self.get_filter_names():
filters[filter] = getattr(self, filter)
return filters | [
"def",
"get_filters",
"(",
"self",
")",
":",
"filters",
"=",
"dict",
"(",
")",
"for",
"filter",
"in",
"self",
".",
"get_filter_names",
"(",
")",
":",
"filters",
"[",
"filter",
"]",
"=",
"getattr",
"(",
"self",
",",
"filter",
")",
"return",
"filters"
]
| Returns a dictionary of filters | [
"Returns",
"a",
"dictionary",
"of",
"filters"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/jinja/filters.py#L80-L85 | train |
projectshift/shift-boiler | boiler/jinja/filters.py | MomentJsFilters._render | def _render(self, value, format):
""" Writes javascript to call momentjs function """
template = '<script>\ndocument.write(moment(\"{t}\").{f});\n</script>'
return Markup(template.format(t=value, f=format)) | python | def _render(self, value, format):
""" Writes javascript to call momentjs function """
template = '<script>\ndocument.write(moment(\"{t}\").{f});\n</script>'
return Markup(template.format(t=value, f=format)) | [
"def",
"_render",
"(",
"self",
",",
"value",
",",
"format",
")",
":",
"template",
"=",
"'<script>\\ndocument.write(moment(\\\"{t}\\\").{f});\\n</script>'",
"return",
"Markup",
"(",
"template",
".",
"format",
"(",
"t",
"=",
"value",
",",
"f",
"=",
"format",
")",
")"
]
| Writes javascript to call momentjs function | [
"Writes",
"javascript",
"to",
"call",
"momentjs",
"function"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/jinja/filters.py#L132-L135 | train |
projectshift/shift-boiler | boiler/jinja/filters.py | MomentJsFilters.get_filters | def get_filters(self):
""" Returns a collection of momentjs filters """
return dict(
moment_format=self.format,
moment_calendar=self.calendar,
moment_fromnow=self.from_now,
) | python | def get_filters(self):
""" Returns a collection of momentjs filters """
return dict(
moment_format=self.format,
moment_calendar=self.calendar,
moment_fromnow=self.from_now,
) | [
"def",
"get_filters",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"moment_format",
"=",
"self",
".",
"format",
",",
"moment_calendar",
"=",
"self",
".",
"calendar",
",",
"moment_fromnow",
"=",
"self",
".",
"from_now",
",",
")"
]
| Returns a collection of momentjs filters | [
"Returns",
"a",
"collection",
"of",
"momentjs",
"filters"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/jinja/filters.py#L146-L152 | train |
adaptive-learning/proso-apps | proso_concepts/views.py | user_stats | def user_stats(request):
"""
JSON of user stats of the user
GET parameters:
html (bool):
turn on the HTML version of the API, defaults to false
user (int):
identifier of the user, defaults to logged user
concepts (list):
list of identifiers of concepts, defaults to all concepts
lang (str):
language of requested concepts, defaults to language from django
"""
user = get_user_id(request)
language = get_language(request)
concepts = None # meaning all concept
if "concepts" in request.GET:
concepts = Concept.objects.filter(lang=language, active=True,
identifier__in=load_query_json(request.GET, "concepts"))
data = UserStat.objects.get_user_stats(user, language, concepts)
return render_json(request, data, template='concepts_json.html', help_text=user_stats.__doc__) | python | def user_stats(request):
"""
JSON of user stats of the user
GET parameters:
html (bool):
turn on the HTML version of the API, defaults to false
user (int):
identifier of the user, defaults to logged user
concepts (list):
list of identifiers of concepts, defaults to all concepts
lang (str):
language of requested concepts, defaults to language from django
"""
user = get_user_id(request)
language = get_language(request)
concepts = None # meaning all concept
if "concepts" in request.GET:
concepts = Concept.objects.filter(lang=language, active=True,
identifier__in=load_query_json(request.GET, "concepts"))
data = UserStat.objects.get_user_stats(user, language, concepts)
return render_json(request, data, template='concepts_json.html', help_text=user_stats.__doc__) | [
"def",
"user_stats",
"(",
"request",
")",
":",
"user",
"=",
"get_user_id",
"(",
"request",
")",
"language",
"=",
"get_language",
"(",
"request",
")",
"concepts",
"=",
"None",
"# meaning all concept",
"if",
"\"concepts\"",
"in",
"request",
".",
"GET",
":",
"concepts",
"=",
"Concept",
".",
"objects",
".",
"filter",
"(",
"lang",
"=",
"language",
",",
"active",
"=",
"True",
",",
"identifier__in",
"=",
"load_query_json",
"(",
"request",
".",
"GET",
",",
"\"concepts\"",
")",
")",
"data",
"=",
"UserStat",
".",
"objects",
".",
"get_user_stats",
"(",
"user",
",",
"language",
",",
"concepts",
")",
"return",
"render_json",
"(",
"request",
",",
"data",
",",
"template",
"=",
"'concepts_json.html'",
",",
"help_text",
"=",
"user_stats",
".",
"__doc__",
")"
]
| JSON of user stats of the user
GET parameters:
html (bool):
turn on the HTML version of the API, defaults to false
user (int):
identifier of the user, defaults to logged user
concepts (list):
list of identifiers of concepts, defaults to all concepts
lang (str):
language of requested concepts, defaults to language from django | [
"JSON",
"of",
"user",
"stats",
"of",
"the",
"user"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_concepts/views.py#L47-L69 | train |
adaptive-learning/proso-apps | proso_concepts/views.py | user_stats_bulk | def user_stats_bulk(request):
"""
Get statistics for selected users and concepts
since:
time as timestamp - get stats changed since
users:
list of identifiers of users
concepts (Optional):
list of identifiers of concepts
language:
language of concepts
"""
language = get_language(request)
users = load_query_json(request.GET, "users")
if request.user.is_staff:
if not hasattr(request.user, 'userprofile') or User.objects.filter(pk__in=users,
userprofile__classes__owner=request.user.userprofile).count() < len(users):
return render_json(request, {
'error': _('Some requested users are not in owned classes'),
'error_type': 'permission_denied'
}, template='concepts_json.html', status=401)
since = None
if 'since' in request.GET:
since = datetime.datetime.fromtimestamp(int(request.GET['since']))
concepts = None
if "concepts" in request.GET:
concepts = Concept.objects.filter(lang=language, active=True,
identifier__in=load_query_json(request.GET, "concepts"))
stats = UserStat.objects.get_user_stats(users, language, concepts=concepts, since=since)
data = {"users": []}
for user, s in stats.items():
data["users"].append({
"user_id": user,
"concepts": s,
})
return render_json(request, data, template='concepts_json.html', help_text=user_stats_bulk.__doc__) | python | def user_stats_bulk(request):
"""
Get statistics for selected users and concepts
since:
time as timestamp - get stats changed since
users:
list of identifiers of users
concepts (Optional):
list of identifiers of concepts
language:
language of concepts
"""
language = get_language(request)
users = load_query_json(request.GET, "users")
if request.user.is_staff:
if not hasattr(request.user, 'userprofile') or User.objects.filter(pk__in=users,
userprofile__classes__owner=request.user.userprofile).count() < len(users):
return render_json(request, {
'error': _('Some requested users are not in owned classes'),
'error_type': 'permission_denied'
}, template='concepts_json.html', status=401)
since = None
if 'since' in request.GET:
since = datetime.datetime.fromtimestamp(int(request.GET['since']))
concepts = None
if "concepts" in request.GET:
concepts = Concept.objects.filter(lang=language, active=True,
identifier__in=load_query_json(request.GET, "concepts"))
stats = UserStat.objects.get_user_stats(users, language, concepts=concepts, since=since)
data = {"users": []}
for user, s in stats.items():
data["users"].append({
"user_id": user,
"concepts": s,
})
return render_json(request, data, template='concepts_json.html', help_text=user_stats_bulk.__doc__) | [
"def",
"user_stats_bulk",
"(",
"request",
")",
":",
"language",
"=",
"get_language",
"(",
"request",
")",
"users",
"=",
"load_query_json",
"(",
"request",
".",
"GET",
",",
"\"users\"",
")",
"if",
"request",
".",
"user",
".",
"is_staff",
":",
"if",
"not",
"hasattr",
"(",
"request",
".",
"user",
",",
"'userprofile'",
")",
"or",
"User",
".",
"objects",
".",
"filter",
"(",
"pk__in",
"=",
"users",
",",
"userprofile__classes__owner",
"=",
"request",
".",
"user",
".",
"userprofile",
")",
".",
"count",
"(",
")",
"<",
"len",
"(",
"users",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Some requested users are not in owned classes'",
")",
",",
"'error_type'",
":",
"'permission_denied'",
"}",
",",
"template",
"=",
"'concepts_json.html'",
",",
"status",
"=",
"401",
")",
"since",
"=",
"None",
"if",
"'since'",
"in",
"request",
".",
"GET",
":",
"since",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"request",
".",
"GET",
"[",
"'since'",
"]",
")",
")",
"concepts",
"=",
"None",
"if",
"\"concepts\"",
"in",
"request",
".",
"GET",
":",
"concepts",
"=",
"Concept",
".",
"objects",
".",
"filter",
"(",
"lang",
"=",
"language",
",",
"active",
"=",
"True",
",",
"identifier__in",
"=",
"load_query_json",
"(",
"request",
".",
"GET",
",",
"\"concepts\"",
")",
")",
"stats",
"=",
"UserStat",
".",
"objects",
".",
"get_user_stats",
"(",
"users",
",",
"language",
",",
"concepts",
"=",
"concepts",
",",
"since",
"=",
"since",
")",
"data",
"=",
"{",
"\"users\"",
":",
"[",
"]",
"}",
"for",
"user",
",",
"s",
"in",
"stats",
".",
"items",
"(",
")",
":",
"data",
"[",
"\"users\"",
"]",
".",
"append",
"(",
"{",
"\"user_id\"",
":",
"user",
",",
"\"concepts\"",
":",
"s",
",",
"}",
")",
"return",
"render_json",
"(",
"request",
",",
"data",
",",
"template",
"=",
"'concepts_json.html'",
",",
"help_text",
"=",
"user_stats_bulk",
".",
"__doc__",
")"
]
| Get statistics for selected users and concepts
since:
time as timestamp - get stats changed since
users:
list of identifiers of users
concepts (Optional):
list of identifiers of concepts
language:
language of concepts | [
"Get",
"statistics",
"for",
"selected",
"users",
"and",
"concepts"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_concepts/views.py#L72-L109 | train |
adaptive-learning/proso-apps | proso_concepts/views.py | user_stats_api | def user_stats_api(request, provider):
"""
Get statistics for selected Edookit users
key:
api key
since:
time as timestamp - get stats changed since
"""
if 'key' not in request.GET or provider not in settings.USER_STATS_API_KEY \
or request.GET['key'] != settings.USER_STATS_API_KEY[provider]:
return HttpResponse('Unauthorized', status=401)
since = None
if 'since' in request.GET:
since = datetime.datetime.fromtimestamp(int(request.GET['since']))
social_users = list(UserSocialAuth.objects.filter(provider=provider).select_related('user'))
user_map = {u.user.id: u for u in social_users}
stats = UserStat.objects.get_user_stats([u.user for u in social_users], lang=None, since=since, recalculate=False)
data = {"users": []}
for user, s in stats.items():
data["users"].append({
"user_id": user_map[user].uid,
"concepts": s,
})
return render_json(request, data, template='concepts_json.html', help_text=user_stats_bulk.__doc__) | python | def user_stats_api(request, provider):
"""
Get statistics for selected Edookit users
key:
api key
since:
time as timestamp - get stats changed since
"""
if 'key' not in request.GET or provider not in settings.USER_STATS_API_KEY \
or request.GET['key'] != settings.USER_STATS_API_KEY[provider]:
return HttpResponse('Unauthorized', status=401)
since = None
if 'since' in request.GET:
since = datetime.datetime.fromtimestamp(int(request.GET['since']))
social_users = list(UserSocialAuth.objects.filter(provider=provider).select_related('user'))
user_map = {u.user.id: u for u in social_users}
stats = UserStat.objects.get_user_stats([u.user for u in social_users], lang=None, since=since, recalculate=False)
data = {"users": []}
for user, s in stats.items():
data["users"].append({
"user_id": user_map[user].uid,
"concepts": s,
})
return render_json(request, data, template='concepts_json.html', help_text=user_stats_bulk.__doc__) | [
"def",
"user_stats_api",
"(",
"request",
",",
"provider",
")",
":",
"if",
"'key'",
"not",
"in",
"request",
".",
"GET",
"or",
"provider",
"not",
"in",
"settings",
".",
"USER_STATS_API_KEY",
"or",
"request",
".",
"GET",
"[",
"'key'",
"]",
"!=",
"settings",
".",
"USER_STATS_API_KEY",
"[",
"provider",
"]",
":",
"return",
"HttpResponse",
"(",
"'Unauthorized'",
",",
"status",
"=",
"401",
")",
"since",
"=",
"None",
"if",
"'since'",
"in",
"request",
".",
"GET",
":",
"since",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"request",
".",
"GET",
"[",
"'since'",
"]",
")",
")",
"social_users",
"=",
"list",
"(",
"UserSocialAuth",
".",
"objects",
".",
"filter",
"(",
"provider",
"=",
"provider",
")",
".",
"select_related",
"(",
"'user'",
")",
")",
"user_map",
"=",
"{",
"u",
".",
"user",
".",
"id",
":",
"u",
"for",
"u",
"in",
"social_users",
"}",
"stats",
"=",
"UserStat",
".",
"objects",
".",
"get_user_stats",
"(",
"[",
"u",
".",
"user",
"for",
"u",
"in",
"social_users",
"]",
",",
"lang",
"=",
"None",
",",
"since",
"=",
"since",
",",
"recalculate",
"=",
"False",
")",
"data",
"=",
"{",
"\"users\"",
":",
"[",
"]",
"}",
"for",
"user",
",",
"s",
"in",
"stats",
".",
"items",
"(",
")",
":",
"data",
"[",
"\"users\"",
"]",
".",
"append",
"(",
"{",
"\"user_id\"",
":",
"user_map",
"[",
"user",
"]",
".",
"uid",
",",
"\"concepts\"",
":",
"s",
",",
"}",
")",
"return",
"render_json",
"(",
"request",
",",
"data",
",",
"template",
"=",
"'concepts_json.html'",
",",
"help_text",
"=",
"user_stats_bulk",
".",
"__doc__",
")"
]
| Get statistics for selected Edookit users
key:
api key
since:
time as timestamp - get stats changed since | [
"Get",
"statistics",
"for",
"selected",
"Edookit",
"users"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_concepts/views.py#L112-L138 | train |
adaptive-learning/proso-apps | proso_concepts/views.py | tag_values | def tag_values(request):
"""
Get tags types and values with localized names
language:
language of tags
"""
data = defaultdict(lambda: {"values": {}})
for tag in Tag.objects.filter(lang=get_language(request)):
data[tag.type]["name"] = tag.type_name
data[tag.type]["values"][tag.value] = tag.value_name
return render_json(request, data, template='concepts_json.html', help_text=tag_values.__doc__) | python | def tag_values(request):
"""
Get tags types and values with localized names
language:
language of tags
"""
data = defaultdict(lambda: {"values": {}})
for tag in Tag.objects.filter(lang=get_language(request)):
data[tag.type]["name"] = tag.type_name
data[tag.type]["values"][tag.value] = tag.value_name
return render_json(request, data, template='concepts_json.html', help_text=tag_values.__doc__) | [
"def",
"tag_values",
"(",
"request",
")",
":",
"data",
"=",
"defaultdict",
"(",
"lambda",
":",
"{",
"\"values\"",
":",
"{",
"}",
"}",
")",
"for",
"tag",
"in",
"Tag",
".",
"objects",
".",
"filter",
"(",
"lang",
"=",
"get_language",
"(",
"request",
")",
")",
":",
"data",
"[",
"tag",
".",
"type",
"]",
"[",
"\"name\"",
"]",
"=",
"tag",
".",
"type_name",
"data",
"[",
"tag",
".",
"type",
"]",
"[",
"\"values\"",
"]",
"[",
"tag",
".",
"value",
"]",
"=",
"tag",
".",
"value_name",
"return",
"render_json",
"(",
"request",
",",
"data",
",",
"template",
"=",
"'concepts_json.html'",
",",
"help_text",
"=",
"tag_values",
".",
"__doc__",
")"
]
| Get tags types and values with localized names
language:
language of tags | [
"Get",
"tags",
"types",
"and",
"values",
"with",
"localized",
"names"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_concepts/views.py#L141-L154 | train |
assamite/creamas | creamas/grid.py | GridEnvironment.add_to_grid | def add_to_grid(self, agent):
'''Add agent to the next available spot in the grid.
:returns:
(x,y) of the agent in the grid. This is the agent's overall
coordinate in the grand grid (i.e. the actual coordinate of the
agent w.t.r **origin**).
:raises: `ValueError` if the grid is full.
'''
for i in range(len(self.grid)):
for j in range(len(self.grid[0])):
if self.grid[i][j] is None:
x = self.origin[0] + i
y = self.origin[1] + j
self.grid[i][j] = agent
return (x, y)
raise ValueError("Trying to add an agent to a full grid."
.format(len(self._grid[0]), len(self._grid[1]))) | python | def add_to_grid(self, agent):
'''Add agent to the next available spot in the grid.
:returns:
(x,y) of the agent in the grid. This is the agent's overall
coordinate in the grand grid (i.e. the actual coordinate of the
agent w.t.r **origin**).
:raises: `ValueError` if the grid is full.
'''
for i in range(len(self.grid)):
for j in range(len(self.grid[0])):
if self.grid[i][j] is None:
x = self.origin[0] + i
y = self.origin[1] + j
self.grid[i][j] = agent
return (x, y)
raise ValueError("Trying to add an agent to a full grid."
.format(len(self._grid[0]), len(self._grid[1]))) | [
"def",
"add_to_grid",
"(",
"self",
",",
"agent",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"grid",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"grid",
"[",
"0",
"]",
")",
")",
":",
"if",
"self",
".",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
"is",
"None",
":",
"x",
"=",
"self",
".",
"origin",
"[",
"0",
"]",
"+",
"i",
"y",
"=",
"self",
".",
"origin",
"[",
"1",
"]",
"+",
"j",
"self",
".",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"agent",
"return",
"(",
"x",
",",
"y",
")",
"raise",
"ValueError",
"(",
"\"Trying to add an agent to a full grid.\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_grid",
"[",
"0",
"]",
")",
",",
"len",
"(",
"self",
".",
"_grid",
"[",
"1",
"]",
")",
")",
")"
]
| Add agent to the next available spot in the grid.
:returns:
(x,y) of the agent in the grid. This is the agent's overall
coordinate in the grand grid (i.e. the actual coordinate of the
agent w.t.r **origin**).
:raises: `ValueError` if the grid is full. | [
"Add",
"agent",
"to",
"the",
"next",
"available",
"spot",
"in",
"the",
"grid",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/grid.py#L203-L222 | train |
assamite/creamas | creamas/grid.py | GridEnvironment.set_agent_neighbors | async def set_agent_neighbors(self):
'''Set neighbors for each agent in each cardinal direction.
This method assumes that the neighboring :class:`GridEnvironment` of
this grid environment have already been set.
'''
for i in range(len(self.grid)):
for j in range(len(self.grid[0])):
agent = self.grid[i][j]
xy = (self.origin[0] + i, self.origin[1] + j)
nxy = _get_neighbor_xy('N', xy)
exy = _get_neighbor_xy('E', xy)
sxy = _get_neighbor_xy('S', xy)
wxy = _get_neighbor_xy('W', xy)
if j == 0:
naddr = await self._get_xy_address_from_neighbor('N', nxy)
else:
naddr = self.get_xy(nxy, addr=True)
if i == 0:
waddr = await self._get_xy_address_from_neighbor('W', wxy)
else:
waddr = self.get_xy(wxy, addr=True)
if j == len(self.grid[0]) - 1:
saddr = await self._get_xy_address_from_neighbor('S', sxy)
else:
saddr = self.get_xy(sxy, addr=True)
if i == len(self.grid) - 1:
eaddr = await self._get_xy_address_from_neighbor('E', exy)
else:
eaddr = self.get_xy(exy, addr=True)
agent.neighbors['N'] = naddr
agent.neighbors['E'] = eaddr
agent.neighbors['S'] = saddr
agent.neighbors['W'] = waddr | python | async def set_agent_neighbors(self):
'''Set neighbors for each agent in each cardinal direction.
This method assumes that the neighboring :class:`GridEnvironment` of
this grid environment have already been set.
'''
for i in range(len(self.grid)):
for j in range(len(self.grid[0])):
agent = self.grid[i][j]
xy = (self.origin[0] + i, self.origin[1] + j)
nxy = _get_neighbor_xy('N', xy)
exy = _get_neighbor_xy('E', xy)
sxy = _get_neighbor_xy('S', xy)
wxy = _get_neighbor_xy('W', xy)
if j == 0:
naddr = await self._get_xy_address_from_neighbor('N', nxy)
else:
naddr = self.get_xy(nxy, addr=True)
if i == 0:
waddr = await self._get_xy_address_from_neighbor('W', wxy)
else:
waddr = self.get_xy(wxy, addr=True)
if j == len(self.grid[0]) - 1:
saddr = await self._get_xy_address_from_neighbor('S', sxy)
else:
saddr = self.get_xy(sxy, addr=True)
if i == len(self.grid) - 1:
eaddr = await self._get_xy_address_from_neighbor('E', exy)
else:
eaddr = self.get_xy(exy, addr=True)
agent.neighbors['N'] = naddr
agent.neighbors['E'] = eaddr
agent.neighbors['S'] = saddr
agent.neighbors['W'] = waddr | [
"async",
"def",
"set_agent_neighbors",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"grid",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"grid",
"[",
"0",
"]",
")",
")",
":",
"agent",
"=",
"self",
".",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
"xy",
"=",
"(",
"self",
".",
"origin",
"[",
"0",
"]",
"+",
"i",
",",
"self",
".",
"origin",
"[",
"1",
"]",
"+",
"j",
")",
"nxy",
"=",
"_get_neighbor_xy",
"(",
"'N'",
",",
"xy",
")",
"exy",
"=",
"_get_neighbor_xy",
"(",
"'E'",
",",
"xy",
")",
"sxy",
"=",
"_get_neighbor_xy",
"(",
"'S'",
",",
"xy",
")",
"wxy",
"=",
"_get_neighbor_xy",
"(",
"'W'",
",",
"xy",
")",
"if",
"j",
"==",
"0",
":",
"naddr",
"=",
"await",
"self",
".",
"_get_xy_address_from_neighbor",
"(",
"'N'",
",",
"nxy",
")",
"else",
":",
"naddr",
"=",
"self",
".",
"get_xy",
"(",
"nxy",
",",
"addr",
"=",
"True",
")",
"if",
"i",
"==",
"0",
":",
"waddr",
"=",
"await",
"self",
".",
"_get_xy_address_from_neighbor",
"(",
"'W'",
",",
"wxy",
")",
"else",
":",
"waddr",
"=",
"self",
".",
"get_xy",
"(",
"wxy",
",",
"addr",
"=",
"True",
")",
"if",
"j",
"==",
"len",
"(",
"self",
".",
"grid",
"[",
"0",
"]",
")",
"-",
"1",
":",
"saddr",
"=",
"await",
"self",
".",
"_get_xy_address_from_neighbor",
"(",
"'S'",
",",
"sxy",
")",
"else",
":",
"saddr",
"=",
"self",
".",
"get_xy",
"(",
"sxy",
",",
"addr",
"=",
"True",
")",
"if",
"i",
"==",
"len",
"(",
"self",
".",
"grid",
")",
"-",
"1",
":",
"eaddr",
"=",
"await",
"self",
".",
"_get_xy_address_from_neighbor",
"(",
"'E'",
",",
"exy",
")",
"else",
":",
"eaddr",
"=",
"self",
".",
"get_xy",
"(",
"exy",
",",
"addr",
"=",
"True",
")",
"agent",
".",
"neighbors",
"[",
"'N'",
"]",
"=",
"naddr",
"agent",
".",
"neighbors",
"[",
"'E'",
"]",
"=",
"eaddr",
"agent",
".",
"neighbors",
"[",
"'S'",
"]",
"=",
"saddr",
"agent",
".",
"neighbors",
"[",
"'W'",
"]",
"=",
"waddr"
]
| Set neighbors for each agent in each cardinal direction.
This method assumes that the neighboring :class:`GridEnvironment` of
this grid environment have already been set. | [
"Set",
"neighbors",
"for",
"each",
"agent",
"in",
"each",
"cardinal",
"direction",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/grid.py#L254-L287 | train |
assamite/creamas | creamas/grid.py | GridMultiEnvironment.set_slave_params | async def set_slave_params(self):
'''Set origin and grid size for each slave environment.
This method needs to be called before slave environments are populated
and agents' and slave environments' neighbors are set.
'''
self._slave_origins = []
cur_x = self.origin[0]
for addr in self.addrs:
new_origin = (cur_x, self.origin[1])
await self.set_origin(addr, new_origin)
await self.set_gs(addr, self._gs)
self._slave_origins.append((new_origin, addr))
new_x = cur_x + self.gs[0]
cur_x = new_x | python | async def set_slave_params(self):
'''Set origin and grid size for each slave environment.
This method needs to be called before slave environments are populated
and agents' and slave environments' neighbors are set.
'''
self._slave_origins = []
cur_x = self.origin[0]
for addr in self.addrs:
new_origin = (cur_x, self.origin[1])
await self.set_origin(addr, new_origin)
await self.set_gs(addr, self._gs)
self._slave_origins.append((new_origin, addr))
new_x = cur_x + self.gs[0]
cur_x = new_x | [
"async",
"def",
"set_slave_params",
"(",
"self",
")",
":",
"self",
".",
"_slave_origins",
"=",
"[",
"]",
"cur_x",
"=",
"self",
".",
"origin",
"[",
"0",
"]",
"for",
"addr",
"in",
"self",
".",
"addrs",
":",
"new_origin",
"=",
"(",
"cur_x",
",",
"self",
".",
"origin",
"[",
"1",
"]",
")",
"await",
"self",
".",
"set_origin",
"(",
"addr",
",",
"new_origin",
")",
"await",
"self",
".",
"set_gs",
"(",
"addr",
",",
"self",
".",
"_gs",
")",
"self",
".",
"_slave_origins",
".",
"append",
"(",
"(",
"new_origin",
",",
"addr",
")",
")",
"new_x",
"=",
"cur_x",
"+",
"self",
".",
"gs",
"[",
"0",
"]",
"cur_x",
"=",
"new_x"
]
| Set origin and grid size for each slave environment.
This method needs to be called before slave environments are populated
and agents' and slave environments' neighbors are set. | [
"Set",
"origin",
"and",
"grid",
"size",
"for",
"each",
"slave",
"environment",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/grid.py#L387-L401 | train |
assamite/creamas | creamas/grid.py | GridMultiEnvironment.set_agent_neighbors | async def set_agent_neighbors(self):
'''Set neighbors for all the agents in all the slave environments.
Assumes that all the slave environments have their neighbors set.
'''
for addr in self.addrs:
r_manager = await self.env.connect(addr)
await r_manager.set_agent_neighbors() | python | async def set_agent_neighbors(self):
'''Set neighbors for all the agents in all the slave environments.
Assumes that all the slave environments have their neighbors set.
'''
for addr in self.addrs:
r_manager = await self.env.connect(addr)
await r_manager.set_agent_neighbors() | [
"async",
"def",
"set_agent_neighbors",
"(",
"self",
")",
":",
"for",
"addr",
"in",
"self",
".",
"addrs",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"await",
"r_manager",
".",
"set_agent_neighbors",
"(",
")"
]
| Set neighbors for all the agents in all the slave environments.
Assumes that all the slave environments have their neighbors set. | [
"Set",
"neighbors",
"for",
"all",
"the",
"agents",
"in",
"all",
"the",
"slave",
"environments",
".",
"Assumes",
"that",
"all",
"the",
"slave",
"environments",
"have",
"their",
"neighbors",
"set",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/grid.py#L504-L510 | train |
assamite/creamas | creamas/grid.py | GridMultiEnvironment.populate | async def populate(self, agent_cls, *args, **kwargs):
'''Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.)
'''
n = self.gs[0] * self.gs[1]
tasks = []
for addr in self.addrs:
task = asyncio.ensure_future(self._populate_slave(addr, agent_cls,
n, *args,
**kwargs))
tasks.append(task)
rets = await asyncio.gather(*tasks)
return rets | python | async def populate(self, agent_cls, *args, **kwargs):
'''Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.)
'''
n = self.gs[0] * self.gs[1]
tasks = []
for addr in self.addrs:
task = asyncio.ensure_future(self._populate_slave(addr, agent_cls,
n, *args,
**kwargs))
tasks.append(task)
rets = await asyncio.gather(*tasks)
return rets | [
"async",
"def",
"populate",
"(",
"self",
",",
"agent_cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"n",
"=",
"self",
".",
"gs",
"[",
"0",
"]",
"*",
"self",
".",
"gs",
"[",
"1",
"]",
"tasks",
"=",
"[",
"]",
"for",
"addr",
"in",
"self",
".",
"addrs",
":",
"task",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"_populate_slave",
"(",
"addr",
",",
"agent_cls",
",",
"n",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"tasks",
".",
"append",
"(",
"task",
")",
"rets",
"=",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")",
"return",
"rets"
]
| Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.) | [
"Populate",
"all",
"the",
"slave",
"grid",
"environments",
"with",
"agents",
".",
"Assumes",
"that",
"no",
"agents",
"have",
"been",
"spawned",
"yet",
"to",
"the",
"slave",
"environment",
"grids",
".",
"This",
"excludes",
"the",
"slave",
"environment",
"managers",
"as",
"they",
"are",
"not",
"in",
"the",
"grids",
".",
")"
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/grid.py#L527-L540 | train |
safarijv/sbo-sphinx | sbo_sphinx/jsdoc.py | generate_docs | def generate_docs(app):
""" Generate the reST documentation files for the JavaScript code """
# Figure out the correct directories to use
config = app.config
config_dir = app.env.srcdir
javascript_root = os.path.join(config_dir, config.jsdoc_source_root)
if javascript_root[-1] != os.path.sep:
javascript_root += os.path.sep
if not javascript_root:
return
output_root = os.path.join(config_dir, config.jsdoc_output_root)
execution_dir = os.path.join(config_dir, '..')
exclude = config.jsdoc_exclude
# Remove any files generated by earlier builds
cleanup(output_root)
# Generate the actual reST files
jsdoc_toolkit_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit')
jsdoc_rst_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit-rst-template')
build_xml_path = os.path.join(jsdoc_rst_dir, 'build.xml')
command = ['ant', '-f', build_xml_path,
'-Djsdoc-toolkit.dir=%s' % jsdoc_toolkit_dir,
'-Djs.src.dir=%s' % javascript_root,
'-Djs.rst.dir=%s' % output_root]
if exclude:
exclude_args = ['--exclude=\\"%s\\"' % path for path in exclude]
command.append('-Djs.exclude="%s"' % ' '.join(exclude_args))
try:
process = Popen(command, cwd=execution_dir)
process.wait()
except OSError:
raise JSDocError('Error running ant; is it installed?')
# Convert the absolute paths in the file listing to relative ones
path = os.path.join(output_root, 'files.rst')
with open(path, 'r') as f:
content = f.read()
content = content.replace(javascript_root, '')
with open(path, 'w') as f:
f.write(content) | python | def generate_docs(app):
""" Generate the reST documentation files for the JavaScript code """
# Figure out the correct directories to use
config = app.config
config_dir = app.env.srcdir
javascript_root = os.path.join(config_dir, config.jsdoc_source_root)
if javascript_root[-1] != os.path.sep:
javascript_root += os.path.sep
if not javascript_root:
return
output_root = os.path.join(config_dir, config.jsdoc_output_root)
execution_dir = os.path.join(config_dir, '..')
exclude = config.jsdoc_exclude
# Remove any files generated by earlier builds
cleanup(output_root)
# Generate the actual reST files
jsdoc_toolkit_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit')
jsdoc_rst_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit-rst-template')
build_xml_path = os.path.join(jsdoc_rst_dir, 'build.xml')
command = ['ant', '-f', build_xml_path,
'-Djsdoc-toolkit.dir=%s' % jsdoc_toolkit_dir,
'-Djs.src.dir=%s' % javascript_root,
'-Djs.rst.dir=%s' % output_root]
if exclude:
exclude_args = ['--exclude=\\"%s\\"' % path for path in exclude]
command.append('-Djs.exclude="%s"' % ' '.join(exclude_args))
try:
process = Popen(command, cwd=execution_dir)
process.wait()
except OSError:
raise JSDocError('Error running ant; is it installed?')
# Convert the absolute paths in the file listing to relative ones
path = os.path.join(output_root, 'files.rst')
with open(path, 'r') as f:
content = f.read()
content = content.replace(javascript_root, '')
with open(path, 'w') as f:
f.write(content) | [
"def",
"generate_docs",
"(",
"app",
")",
":",
"# Figure out the correct directories to use",
"config",
"=",
"app",
".",
"config",
"config_dir",
"=",
"app",
".",
"env",
".",
"srcdir",
"javascript_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_dir",
",",
"config",
".",
"jsdoc_source_root",
")",
"if",
"javascript_root",
"[",
"-",
"1",
"]",
"!=",
"os",
".",
"path",
".",
"sep",
":",
"javascript_root",
"+=",
"os",
".",
"path",
".",
"sep",
"if",
"not",
"javascript_root",
":",
"return",
"output_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_dir",
",",
"config",
".",
"jsdoc_output_root",
")",
"execution_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_dir",
",",
"'..'",
")",
"exclude",
"=",
"config",
".",
"jsdoc_exclude",
"# Remove any files generated by earlier builds",
"cleanup",
"(",
"output_root",
")",
"# Generate the actual reST files",
"jsdoc_toolkit_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SOURCE_PATH",
",",
"'jsdoc-toolkit'",
")",
"jsdoc_rst_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SOURCE_PATH",
",",
"'jsdoc-toolkit-rst-template'",
")",
"build_xml_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"jsdoc_rst_dir",
",",
"'build.xml'",
")",
"command",
"=",
"[",
"'ant'",
",",
"'-f'",
",",
"build_xml_path",
",",
"'-Djsdoc-toolkit.dir=%s'",
"%",
"jsdoc_toolkit_dir",
",",
"'-Djs.src.dir=%s'",
"%",
"javascript_root",
",",
"'-Djs.rst.dir=%s'",
"%",
"output_root",
"]",
"if",
"exclude",
":",
"exclude_args",
"=",
"[",
"'--exclude=\\\\\"%s\\\\\"'",
"%",
"path",
"for",
"path",
"in",
"exclude",
"]",
"command",
".",
"append",
"(",
"'-Djs.exclude=\"%s\"'",
"%",
"' '",
".",
"join",
"(",
"exclude_args",
")",
")",
"try",
":",
"process",
"=",
"Popen",
"(",
"command",
",",
"cwd",
"=",
"execution_dir",
")",
"process",
".",
"wait",
"(",
")",
"except",
"OSError",
":",
"raise",
"JSDocError",
"(",
"'Error running ant; is it installed?'",
")",
"# Convert the absolute paths in the file listing to relative ones",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_root",
",",
"'files.rst'",
")",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"content",
"=",
"content",
".",
"replace",
"(",
"javascript_root",
",",
"''",
")",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")"
]
| Generate the reST documentation files for the JavaScript code | [
"Generate",
"the",
"reST",
"documentation",
"files",
"for",
"the",
"JavaScript",
"code"
]
| 7a8efb7c49488131c90c19ef1a1563f595630a36 | https://github.com/safarijv/sbo-sphinx/blob/7a8efb7c49488131c90c19ef1a1563f595630a36/sbo_sphinx/jsdoc.py#L42-L82 | train |
safarijv/sbo-sphinx | sbo_sphinx/jsdoc.py | setup | def setup(app):
"""Sphinx extension entry point"""
app.add_config_value('jsdoc_source_root', '..', 'env')
app.add_config_value('jsdoc_output_root', 'javascript', 'env')
app.add_config_value('jsdoc_exclude', [], 'env')
app.connect('builder-inited', generate_docs) | python | def setup(app):
"""Sphinx extension entry point"""
app.add_config_value('jsdoc_source_root', '..', 'env')
app.add_config_value('jsdoc_output_root', 'javascript', 'env')
app.add_config_value('jsdoc_exclude', [], 'env')
app.connect('builder-inited', generate_docs) | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_config_value",
"(",
"'jsdoc_source_root'",
",",
"'..'",
",",
"'env'",
")",
"app",
".",
"add_config_value",
"(",
"'jsdoc_output_root'",
",",
"'javascript'",
",",
"'env'",
")",
"app",
".",
"add_config_value",
"(",
"'jsdoc_exclude'",
",",
"[",
"]",
",",
"'env'",
")",
"app",
".",
"connect",
"(",
"'builder-inited'",
",",
"generate_docs",
")"
]
| Sphinx extension entry point | [
"Sphinx",
"extension",
"entry",
"point"
]
| 7a8efb7c49488131c90c19ef1a1563f595630a36 | https://github.com/safarijv/sbo-sphinx/blob/7a8efb7c49488131c90c19ef1a1563f595630a36/sbo_sphinx/jsdoc.py#L94-L99 | train |
projectshift/shift-boiler | boiler/cli/user.py | find_user | def find_user(search_params):
"""
Find user
Attempts to find a user by a set of search params. You must be in
application context.
"""
user = None
params = {prop: value for prop, value in search_params.items() if value}
if 'id' in params or 'email' in params:
user = user_service.first(**params)
return user | python | def find_user(search_params):
"""
Find user
Attempts to find a user by a set of search params. You must be in
application context.
"""
user = None
params = {prop: value for prop, value in search_params.items() if value}
if 'id' in params or 'email' in params:
user = user_service.first(**params)
return user | [
"def",
"find_user",
"(",
"search_params",
")",
":",
"user",
"=",
"None",
"params",
"=",
"{",
"prop",
":",
"value",
"for",
"prop",
",",
"value",
"in",
"search_params",
".",
"items",
"(",
")",
"if",
"value",
"}",
"if",
"'id'",
"in",
"params",
"or",
"'email'",
"in",
"params",
":",
"user",
"=",
"user_service",
".",
"first",
"(",
"*",
"*",
"params",
")",
"return",
"user"
]
| Find user
Attempts to find a user by a set of search params. You must be in
application context. | [
"Find",
"user",
"Attempts",
"to",
"find",
"a",
"user",
"by",
"a",
"set",
"of",
"search",
"params",
".",
"You",
"must",
"be",
"in",
"application",
"context",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/user.py#L19-L29 | train |
projectshift/shift-boiler | boiler/cli/user.py | create | def create(email, password):
""" Creates a new user record """
with get_app().app_context():
user = User(email=email, password=password)
result = user_service.save(user)
if not isinstance(result, User):
print_validation_errors(result)
return
click.echo(green('\nUser created:'))
click.echo(green('-' * 40))
click.echo(str(user) + '\n') | python | def create(email, password):
""" Creates a new user record """
with get_app().app_context():
user = User(email=email, password=password)
result = user_service.save(user)
if not isinstance(result, User):
print_validation_errors(result)
return
click.echo(green('\nUser created:'))
click.echo(green('-' * 40))
click.echo(str(user) + '\n') | [
"def",
"create",
"(",
"email",
",",
"password",
")",
":",
"with",
"get_app",
"(",
")",
".",
"app_context",
"(",
")",
":",
"user",
"=",
"User",
"(",
"email",
"=",
"email",
",",
"password",
"=",
"password",
")",
"result",
"=",
"user_service",
".",
"save",
"(",
"user",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"User",
")",
":",
"print_validation_errors",
"(",
"result",
")",
"return",
"click",
".",
"echo",
"(",
"green",
"(",
"'\\nUser created:'",
")",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
")",
"click",
".",
"echo",
"(",
"str",
"(",
"user",
")",
"+",
"'\\n'",
")"
]
| Creates a new user record | [
"Creates",
"a",
"new",
"user",
"record"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/user.py#L48-L59 | train |
projectshift/shift-boiler | boiler/cli/user.py | change_password | def change_password(*_, user_id=None, password=None):
""" Change user password """
click.echo(green('\nChange password:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
return
result = user_service.change_password(user, password)
if isinstance(result, User):
msg = 'Changed password for user {} \n'.format(user.email)
click.echo(green(msg))
return
print_validation_errors(result)
return | python | def change_password(*_, user_id=None, password=None):
""" Change user password """
click.echo(green('\nChange password:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
return
result = user_service.change_password(user, password)
if isinstance(result, User):
msg = 'Changed password for user {} \n'.format(user.email)
click.echo(green(msg))
return
print_validation_errors(result)
return | [
"def",
"change_password",
"(",
"*",
"_",
",",
"user_id",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"click",
".",
"echo",
"(",
"green",
"(",
"'\\nChange password:'",
")",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
")",
"with",
"get_app",
"(",
")",
".",
"app_context",
"(",
")",
":",
"user",
"=",
"find_user",
"(",
"dict",
"(",
"id",
"=",
"user_id",
")",
")",
"if",
"not",
"user",
":",
"click",
".",
"echo",
"(",
"red",
"(",
"'User not found\\n'",
")",
")",
"return",
"result",
"=",
"user_service",
".",
"change_password",
"(",
"user",
",",
"password",
")",
"if",
"isinstance",
"(",
"result",
",",
"User",
")",
":",
"msg",
"=",
"'Changed password for user {} \\n'",
".",
"format",
"(",
"user",
".",
"email",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"msg",
")",
")",
"return",
"print_validation_errors",
"(",
"result",
")",
"return"
]
| Change user password | [
"Change",
"user",
"password"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/user.py#L84-L102 | train |
projectshift/shift-boiler | boiler/cli/user.py | change_email | def change_email(*_, user_id=None, new_email=None):
""" Change email for a user """
click.echo(green('\nChange email:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
return
user.email = new_email
result = user_service.save(user)
if not isinstance(result, User):
print_validation_errors(result)
return
user.confirm_email()
user_service.save(user)
msg = 'Change email for user {} to {} \n'
click.echo(green(msg.format(user.email, new_email))) | python | def change_email(*_, user_id=None, new_email=None):
""" Change email for a user """
click.echo(green('\nChange email:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
return
user.email = new_email
result = user_service.save(user)
if not isinstance(result, User):
print_validation_errors(result)
return
user.confirm_email()
user_service.save(user)
msg = 'Change email for user {} to {} \n'
click.echo(green(msg.format(user.email, new_email))) | [
"def",
"change_email",
"(",
"*",
"_",
",",
"user_id",
"=",
"None",
",",
"new_email",
"=",
"None",
")",
":",
"click",
".",
"echo",
"(",
"green",
"(",
"'\\nChange email:'",
")",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
")",
"with",
"get_app",
"(",
")",
".",
"app_context",
"(",
")",
":",
"user",
"=",
"find_user",
"(",
"dict",
"(",
"id",
"=",
"user_id",
")",
")",
"if",
"not",
"user",
":",
"click",
".",
"echo",
"(",
"red",
"(",
"'User not found\\n'",
")",
")",
"return",
"user",
".",
"email",
"=",
"new_email",
"result",
"=",
"user_service",
".",
"save",
"(",
"user",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"User",
")",
":",
"print_validation_errors",
"(",
"result",
")",
"return",
"user",
".",
"confirm_email",
"(",
")",
"user_service",
".",
"save",
"(",
"user",
")",
"msg",
"=",
"'Change email for user {} to {} \\n'",
"click",
".",
"echo",
"(",
"green",
"(",
"msg",
".",
"format",
"(",
"user",
".",
"email",
",",
"new_email",
")",
")",
")"
]
| Change email for a user | [
"Change",
"email",
"for",
"a",
"user"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/user.py#L108-L128 | train |
projectshift/shift-boiler | boiler/cli/user.py | create_role | def create_role(*_, **kwargs):
""" Create user role """
click.echo(green('\nCreating new role:'))
click.echo(green('-' * 40))
with get_app().app_context():
role = Role(**kwargs)
result = role_service.save(role)
if not isinstance(result, Role):
print_validation_errors(result)
click.echo(green('Created: ') + str(role) + '\n') | python | def create_role(*_, **kwargs):
""" Create user role """
click.echo(green('\nCreating new role:'))
click.echo(green('-' * 40))
with get_app().app_context():
role = Role(**kwargs)
result = role_service.save(role)
if not isinstance(result, Role):
print_validation_errors(result)
click.echo(green('Created: ') + str(role) + '\n') | [
"def",
"create_role",
"(",
"*",
"_",
",",
"*",
"*",
"kwargs",
")",
":",
"click",
".",
"echo",
"(",
"green",
"(",
"'\\nCreating new role:'",
")",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
")",
"with",
"get_app",
"(",
")",
".",
"app_context",
"(",
")",
":",
"role",
"=",
"Role",
"(",
"*",
"*",
"kwargs",
")",
"result",
"=",
"role_service",
".",
"save",
"(",
"role",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"Role",
")",
":",
"print_validation_errors",
"(",
"result",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'Created: '",
")",
"+",
"str",
"(",
"role",
")",
"+",
"'\\n'",
")"
]
| Create user role | [
"Create",
"user",
"role"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/user.py#L135-L146 | train |
projectshift/shift-boiler | boiler/cli/user.py | list_roles | def list_roles():
""" List existing roles """
click.echo(green('\nListing roles:'))
click.echo(green('-' * 40))
with get_app().app_context():
roles = Role.query.all()
if not roles:
click.echo(red('No roles found'))
return
for index,role in enumerate(roles):
click.echo('{}. {}: {}'.format(
index + 1,
yellow(role.handle),
role.title
))
click.echo() | python | def list_roles():
""" List existing roles """
click.echo(green('\nListing roles:'))
click.echo(green('-' * 40))
with get_app().app_context():
roles = Role.query.all()
if not roles:
click.echo(red('No roles found'))
return
for index,role in enumerate(roles):
click.echo('{}. {}: {}'.format(
index + 1,
yellow(role.handle),
role.title
))
click.echo() | [
"def",
"list_roles",
"(",
")",
":",
"click",
".",
"echo",
"(",
"green",
"(",
"'\\nListing roles:'",
")",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
")",
"with",
"get_app",
"(",
")",
".",
"app_context",
"(",
")",
":",
"roles",
"=",
"Role",
".",
"query",
".",
"all",
"(",
")",
"if",
"not",
"roles",
":",
"click",
".",
"echo",
"(",
"red",
"(",
"'No roles found'",
")",
")",
"return",
"for",
"index",
",",
"role",
"in",
"enumerate",
"(",
"roles",
")",
":",
"click",
".",
"echo",
"(",
"'{}. {}: {}'",
".",
"format",
"(",
"index",
"+",
"1",
",",
"yellow",
"(",
"role",
".",
"handle",
")",
",",
"role",
".",
"title",
")",
")",
"click",
".",
"echo",
"(",
")"
]
| List existing roles | [
"List",
"existing",
"roles"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/user.py#L150-L167 | train |
projectshift/shift-boiler | boiler/cli/user.py | list_user_roles | def list_user_roles(*_, user_id):
""" List user roles """
click.echo(green('\nListing user roles:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
return
for index,role in enumerate(user.roles):
click.echo('{}. {}: {}'.format(
index + 1,
yellow(role.handle),
role.title
))
click.echo() | python | def list_user_roles(*_, user_id):
""" List user roles """
click.echo(green('\nListing user roles:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
return
for index,role in enumerate(user.roles):
click.echo('{}. {}: {}'.format(
index + 1,
yellow(role.handle),
role.title
))
click.echo() | [
"def",
"list_user_roles",
"(",
"*",
"_",
",",
"user_id",
")",
":",
"click",
".",
"echo",
"(",
"green",
"(",
"'\\nListing user roles:'",
")",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
")",
"with",
"get_app",
"(",
")",
".",
"app_context",
"(",
")",
":",
"user",
"=",
"find_user",
"(",
"dict",
"(",
"id",
"=",
"user_id",
")",
")",
"if",
"not",
"user",
":",
"click",
".",
"echo",
"(",
"red",
"(",
"'User not found\\n'",
")",
")",
"return",
"for",
"index",
",",
"role",
"in",
"enumerate",
"(",
"user",
".",
"roles",
")",
":",
"click",
".",
"echo",
"(",
"'{}. {}: {}'",
".",
"format",
"(",
"index",
"+",
"1",
",",
"yellow",
"(",
"role",
".",
"handle",
")",
",",
"role",
".",
"title",
")",
")",
"click",
".",
"echo",
"(",
")"
]
| List user roles | [
"List",
"user",
"roles"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/user.py#L172-L189 | train |
cgrok/cr-async | crasync/models.py | Base.update | async def update(self):
'''Update an object with current info.'''
if self.client.session.closed:
async with core.Client() as client:
data = await client.request(self.url)
else:
data = await self.client.request(self.url)
self.raw_data = data
self.from_data(data)
return self | python | async def update(self):
'''Update an object with current info.'''
if self.client.session.closed:
async with core.Client() as client:
data = await client.request(self.url)
else:
data = await self.client.request(self.url)
self.raw_data = data
self.from_data(data)
return self | [
"async",
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"client",
".",
"session",
".",
"closed",
":",
"async",
"with",
"core",
".",
"Client",
"(",
")",
"as",
"client",
":",
"data",
"=",
"await",
"client",
".",
"request",
"(",
"self",
".",
"url",
")",
"else",
":",
"data",
"=",
"await",
"self",
".",
"client",
".",
"request",
"(",
"self",
".",
"url",
")",
"self",
".",
"raw_data",
"=",
"data",
"self",
".",
"from_data",
"(",
"data",
")",
"return",
"self"
]
| Update an object with current info. | [
"Update",
"an",
"object",
"with",
"current",
"info",
"."
]
| f65a968e54704168706d137d1ba662f55f8ab852 | https://github.com/cgrok/cr-async/blob/f65a968e54704168706d137d1ba662f55f8ab852/crasync/models.py#L57-L68 | train |
cgrok/cr-async | crasync/models.py | Profile.clan_badge_url | def clan_badge_url(self):
'''Returns clan badge url'''
if self.clan_tag is None:
return None
url = self.raw_data.get('clan').get('badge').get('url')
if not url:
return None
return "http://api.cr-api.com" + url | python | def clan_badge_url(self):
'''Returns clan badge url'''
if self.clan_tag is None:
return None
url = self.raw_data.get('clan').get('badge').get('url')
if not url:
return None
return "http://api.cr-api.com" + url | [
"def",
"clan_badge_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"clan_tag",
"is",
"None",
":",
"return",
"None",
"url",
"=",
"self",
".",
"raw_data",
".",
"get",
"(",
"'clan'",
")",
".",
"get",
"(",
"'badge'",
")",
".",
"get",
"(",
"'url'",
")",
"if",
"not",
"url",
":",
"return",
"None",
"return",
"\"http://api.cr-api.com\"",
"+",
"url"
]
| Returns clan badge url | [
"Returns",
"clan",
"badge",
"url"
]
| f65a968e54704168706d137d1ba662f55f8ab852 | https://github.com/cgrok/cr-async/blob/f65a968e54704168706d137d1ba662f55f8ab852/crasync/models.py#L344-L351 | train |
cgrok/cr-async | crasync/models.py | Profile.get_chest | def get_chest(self, index=0):
'''Get your current chest +- the index'''
index += self.chest_cycle.position
if index == self.chest_cycle.super_magical:
return 'Super Magical'
if index == self.chest_cycle.epic:
return 'Epic'
if index == self.chest_cycle.legendary:
return 'Legendary'
return CHESTS[index % len(CHESTS)] | python | def get_chest(self, index=0):
'''Get your current chest +- the index'''
index += self.chest_cycle.position
if index == self.chest_cycle.super_magical:
return 'Super Magical'
if index == self.chest_cycle.epic:
return 'Epic'
if index == self.chest_cycle.legendary:
return 'Legendary'
return CHESTS[index % len(CHESTS)] | [
"def",
"get_chest",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"index",
"+=",
"self",
".",
"chest_cycle",
".",
"position",
"if",
"index",
"==",
"self",
".",
"chest_cycle",
".",
"super_magical",
":",
"return",
"'Super Magical'",
"if",
"index",
"==",
"self",
".",
"chest_cycle",
".",
"epic",
":",
"return",
"'Epic'",
"if",
"index",
"==",
"self",
".",
"chest_cycle",
".",
"legendary",
":",
"return",
"'Legendary'",
"return",
"CHESTS",
"[",
"index",
"%",
"len",
"(",
"CHESTS",
")",
"]"
]
| Get your current chest +- the index | [
"Get",
"your",
"current",
"chest",
"+",
"-",
"the",
"index"
]
| f65a968e54704168706d137d1ba662f55f8ab852 | https://github.com/cgrok/cr-async/blob/f65a968e54704168706d137d1ba662f55f8ab852/crasync/models.py#L353-L365 | train |
ronhanson/python-tbx | fabfile/virtualenv.py | update | def update():
"""Update virtual env with requirements packages."""
with settings(warn_only=True):
print(cyan('\nInstalling/Updating required packages...'))
pip = local('venv/bin/pip install -U --allow-all-external --src libs -r requirements.txt', capture=True)
if pip.failed:
print(red(pip))
abort("pip exited with return code %i" % pip.return_code)
print(green('Packages requirements updated.')) | python | def update():
"""Update virtual env with requirements packages."""
with settings(warn_only=True):
print(cyan('\nInstalling/Updating required packages...'))
pip = local('venv/bin/pip install -U --allow-all-external --src libs -r requirements.txt', capture=True)
if pip.failed:
print(red(pip))
abort("pip exited with return code %i" % pip.return_code)
print(green('Packages requirements updated.')) | [
"def",
"update",
"(",
")",
":",
"with",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"print",
"(",
"cyan",
"(",
"'\\nInstalling/Updating required packages...'",
")",
")",
"pip",
"=",
"local",
"(",
"'venv/bin/pip install -U --allow-all-external --src libs -r requirements.txt'",
",",
"capture",
"=",
"True",
")",
"if",
"pip",
".",
"failed",
":",
"print",
"(",
"red",
"(",
"pip",
")",
")",
"abort",
"(",
"\"pip exited with return code %i\"",
"%",
"pip",
".",
"return_code",
")",
"print",
"(",
"green",
"(",
"'Packages requirements updated.'",
")",
")"
]
| Update virtual env with requirements packages. | [
"Update",
"virtual",
"env",
"with",
"requirements",
"packages",
"."
]
| 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/fabfile/virtualenv.py#L22-L32 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver._detect_devices | def _detect_devices(self) -> None:
'''Detect whether devices connected.'''
devices_num = len(self.devices_list)
if devices_num == 0:
raise DeviceConnectionException(
'No devices are connected. Please connect the device with USB or via WLAN and turn on the USB debugging option.')
elif not self.device_sn and devices_num > 1:
raise DeviceConnectionException(
f"Multiple devices detected: {' | '.join(self.devices_list)}, please specify device serial number or host.")
else:
self.device_sn = self.devices_list[0]
if self.get_state() == 'offline':
raise DeviceConnectionException(
'The device is offline. Please reconnect.') | python | def _detect_devices(self) -> None:
'''Detect whether devices connected.'''
devices_num = len(self.devices_list)
if devices_num == 0:
raise DeviceConnectionException(
'No devices are connected. Please connect the device with USB or via WLAN and turn on the USB debugging option.')
elif not self.device_sn and devices_num > 1:
raise DeviceConnectionException(
f"Multiple devices detected: {' | '.join(self.devices_list)}, please specify device serial number or host.")
else:
self.device_sn = self.devices_list[0]
if self.get_state() == 'offline':
raise DeviceConnectionException(
'The device is offline. Please reconnect.') | [
"def",
"_detect_devices",
"(",
"self",
")",
"->",
"None",
":",
"devices_num",
"=",
"len",
"(",
"self",
".",
"devices_list",
")",
"if",
"devices_num",
"==",
"0",
":",
"raise",
"DeviceConnectionException",
"(",
"'No devices are connected. Please connect the device with USB or via WLAN and turn on the USB debugging option.'",
")",
"elif",
"not",
"self",
".",
"device_sn",
"and",
"devices_num",
">",
"1",
":",
"raise",
"DeviceConnectionException",
"(",
"f\"Multiple devices detected: {' | '.join(self.devices_list)}, please specify device serial number or host.\"",
")",
"else",
":",
"self",
".",
"device_sn",
"=",
"self",
".",
"devices_list",
"[",
"0",
"]",
"if",
"self",
".",
"get_state",
"(",
")",
"==",
"'offline'",
":",
"raise",
"DeviceConnectionException",
"(",
"'The device is offline. Please reconnect.'",
")"
]
| Detect whether devices connected. | [
"Detect",
"whether",
"devices",
"connected",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L77-L90 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_device_model | def get_device_model(self) -> str:
'''Show device model.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.product.model')
return output.strip() | python | def get_device_model(self) -> str:
'''Show device model.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.product.model')
return output.strip() | [
"def",
"get_device_model",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'getprop'",
",",
"'ro.product.model'",
")",
"return",
"output",
".",
"strip",
"(",
")"
]
| Show device model. | [
"Show",
"device",
"model",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L131-L135 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_battery_info | def get_battery_info(self) -> dict:
'''Show device battery information.
Returns:
A dict. For example:
{'AC powered': 'false',
'Charge counter': '0',
'Max charging current': '0',
'Max charging voltage': '0',
'USB powered': 'false',
'Wireless powered': 'false',
'health': '2',
'level': '67',
'present': 'true',
'scale': '100',
'status': '3',
'technology': 'Li-poly',
'temperature': '310',
'voltage': '3965'}
'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'battery')
battery_status = re.split('\n |: ', output[33:].strip())
return dict(zip(battery_status[::2], battery_status[1::2])) | python | def get_battery_info(self) -> dict:
'''Show device battery information.
Returns:
A dict. For example:
{'AC powered': 'false',
'Charge counter': '0',
'Max charging current': '0',
'Max charging voltage': '0',
'USB powered': 'false',
'Wireless powered': 'false',
'health': '2',
'level': '67',
'present': 'true',
'scale': '100',
'status': '3',
'technology': 'Li-poly',
'temperature': '310',
'voltage': '3965'}
'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'battery')
battery_status = re.split('\n |: ', output[33:].strip())
return dict(zip(battery_status[::2], battery_status[1::2])) | [
"def",
"get_battery_info",
"(",
"self",
")",
"->",
"dict",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'battery'",
")",
"battery_status",
"=",
"re",
".",
"split",
"(",
"'\\n |: '",
",",
"output",
"[",
"33",
":",
"]",
".",
"strip",
"(",
")",
")",
"return",
"dict",
"(",
"zip",
"(",
"battery_status",
"[",
":",
":",
"2",
"]",
",",
"battery_status",
"[",
"1",
":",
":",
"2",
"]",
")",
")"
]
| Show device battery information.
Returns:
A dict. For example:
{'AC powered': 'false',
'Charge counter': '0',
'Max charging current': '0',
'Max charging voltage': '0',
'USB powered': 'false',
'Wireless powered': 'false',
'health': '2',
'level': '67',
'present': 'true',
'scale': '100',
'status': '3',
'technology': 'Li-poly',
'temperature': '310',
'voltage': '3965'} | [
"Show",
"device",
"battery",
"information",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L137-L161 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_resolution | def get_resolution(self) -> list:
'''Show device resolution.'''
output, _ = self._execute('-s', self.device_sn, 'shell', 'wm', 'size')
return output.split()[2].split('x') | python | def get_resolution(self) -> list:
'''Show device resolution.'''
output, _ = self._execute('-s', self.device_sn, 'shell', 'wm', 'size')
return output.split()[2].split('x') | [
"def",
"get_resolution",
"(",
"self",
")",
"->",
"list",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'wm'",
",",
"'size'",
")",
"return",
"output",
".",
"split",
"(",
")",
"[",
"2",
"]",
".",
"split",
"(",
"'x'",
")"
]
| Show device resolution. | [
"Show",
"device",
"resolution",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L163-L166 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_displays_params | def get_displays_params(self) -> str:
'''Show displays parameters.'''
output, error = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'displays')
return output | python | def get_displays_params(self) -> str:
'''Show displays parameters.'''
output, error = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'displays')
return output | [
"def",
"get_displays_params",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"error",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'window'",
",",
"'displays'",
")",
"return",
"output"
]
| Show displays parameters. | [
"Show",
"displays",
"parameters",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L174-L178 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_android_id | def get_android_id(self) -> str:
'''Show Android ID.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'settings', 'get', 'secure', 'android_id')
return output.strip() | python | def get_android_id(self) -> str:
'''Show Android ID.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'settings', 'get', 'secure', 'android_id')
return output.strip() | [
"def",
"get_android_id",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'settings'",
",",
"'get'",
",",
"'secure'",
",",
"'android_id'",
")",
"return",
"output",
".",
"strip",
"(",
")"
]
| Show Android ID. | [
"Show",
"Android",
"ID",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L180-L184 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_android_version | def get_android_version(self) -> str:
'''Show Android version.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.build.version.release')
return output.strip() | python | def get_android_version(self) -> str:
'''Show Android version.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.build.version.release')
return output.strip() | [
"def",
"get_android_version",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'getprop'",
",",
"'ro.build.version.release'",
")",
"return",
"output",
".",
"strip",
"(",
")"
]
| Show Android version. | [
"Show",
"Android",
"version",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L186-L190 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_device_mac | def get_device_mac(self) -> str:
'''Show device MAC.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/sys/class/net/wlan0/address')
return output.strip() | python | def get_device_mac(self) -> str:
'''Show device MAC.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/sys/class/net/wlan0/address')
return output.strip() | [
"def",
"get_device_mac",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'cat'",
",",
"'/sys/class/net/wlan0/address'",
")",
"return",
"output",
".",
"strip",
"(",
")"
]
| Show device MAC. | [
"Show",
"device",
"MAC",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L192-L196 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_cpu_info | def get_cpu_info(self) -> str:
'''Show device CPU information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/proc/cpuinfo')
return output | python | def get_cpu_info(self) -> str:
'''Show device CPU information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/proc/cpuinfo')
return output | [
"def",
"get_cpu_info",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'cat'",
",",
"'/proc/cpuinfo'",
")",
"return",
"output"
]
| Show device CPU information. | [
"Show",
"device",
"CPU",
"information",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L198-L202 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_memory_info | def get_memory_info(self) -> str:
'''Show device memory information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/proc/meminfo')
return output | python | def get_memory_info(self) -> str:
'''Show device memory information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/proc/meminfo')
return output | [
"def",
"get_memory_info",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'cat'",
",",
"'/proc/meminfo'",
")",
"return",
"output"
]
| Show device memory information. | [
"Show",
"device",
"memory",
"information",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L204-L208 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_sdk_version | def get_sdk_version(self) -> str:
'''Show Android SDK version.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.build.version.sdk')
return output.strip() | python | def get_sdk_version(self) -> str:
'''Show Android SDK version.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.build.version.sdk')
return output.strip() | [
"def",
"get_sdk_version",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'getprop'",
",",
"'ro.build.version.sdk'",
")",
"return",
"output",
".",
"strip",
"(",
")"
]
| Show Android SDK version. | [
"Show",
"Android",
"SDK",
"version",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L210-L214 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.root | def root(self) -> None:
'''Restart adbd with root permissions.'''
output, _ = self._execute('-s', self.device_sn, 'root')
if not output:
raise PermissionError(
f'{self.device_sn!r} does not have root permission.') | python | def root(self) -> None:
'''Restart adbd with root permissions.'''
output, _ = self._execute('-s', self.device_sn, 'root')
if not output:
raise PermissionError(
f'{self.device_sn!r} does not have root permission.') | [
"def",
"root",
"(",
"self",
")",
"->",
"None",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'root'",
")",
"if",
"not",
"output",
":",
"raise",
"PermissionError",
"(",
"f'{self.device_sn!r} does not have root permission.'",
")"
]
| Restart adbd with root permissions. | [
"Restart",
"adbd",
"with",
"root",
"permissions",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L216-L221 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.tcpip | def tcpip(self, port: int or str = 5555) -> None:
'''Restart adb server listening on TCP on PORT.'''
self._execute('-s', self.device_sn, 'tcpip', str(port)) | python | def tcpip(self, port: int or str = 5555) -> None:
'''Restart adb server listening on TCP on PORT.'''
self._execute('-s', self.device_sn, 'tcpip', str(port)) | [
"def",
"tcpip",
"(",
"self",
",",
"port",
":",
"int",
"or",
"str",
"=",
"5555",
")",
"->",
"None",
":",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'tcpip'",
",",
"str",
"(",
"port",
")",
")"
]
| Restart adb server listening on TCP on PORT. | [
"Restart",
"adb",
"server",
"listening",
"on",
"TCP",
"on",
"PORT",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L227-L229 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.get_ip_addr | def get_ip_addr(self) -> str:
'''Show IP Address.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'ip', '-f', 'inet', 'addr', 'show', 'wlan0')
ip_addr = re.findall(
r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", output)
if not ip_addr:
raise ConnectionError(
'The device is not connected to WLAN or not connected via USB.')
return ip_addr[0] | python | def get_ip_addr(self) -> str:
'''Show IP Address.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'ip', '-f', 'inet', 'addr', 'show', 'wlan0')
ip_addr = re.findall(
r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", output)
if not ip_addr:
raise ConnectionError(
'The device is not connected to WLAN or not connected via USB.')
return ip_addr[0] | [
"def",
"get_ip_addr",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'ip'",
",",
"'-f'",
",",
"'inet'",
",",
"'addr'",
",",
"'show'",
",",
"'wlan0'",
")",
"ip_addr",
"=",
"re",
".",
"findall",
"(",
"r\"\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\"",
",",
"output",
")",
"if",
"not",
"ip_addr",
":",
"raise",
"ConnectionError",
"(",
"'The device is not connected to WLAN or not connected via USB.'",
")",
"return",
"ip_addr",
"[",
"0",
"]"
]
| Show IP Address. | [
"Show",
"IP",
"Address",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L231-L240 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.sync_l | def sync_l(self, option: str = 'all') -> None:
'''List but don't copy.
Args:
option: 'system', 'vendor', 'oem', 'data', 'all'
'''
if option in ['system', 'vendor', 'oem', 'data', 'all']:
self._execute('-s', self.device_sn, 'sync', '-l', option)
else:
raise ValueError('There is no option named: {!r}.'.format(option)) | python | def sync_l(self, option: str = 'all') -> None:
'''List but don't copy.
Args:
option: 'system', 'vendor', 'oem', 'data', 'all'
'''
if option in ['system', 'vendor', 'oem', 'data', 'all']:
self._execute('-s', self.device_sn, 'sync', '-l', option)
else:
raise ValueError('There is no option named: {!r}.'.format(option)) | [
"def",
"sync_l",
"(",
"self",
",",
"option",
":",
"str",
"=",
"'all'",
")",
"->",
"None",
":",
"if",
"option",
"in",
"[",
"'system'",
",",
"'vendor'",
",",
"'oem'",
",",
"'data'",
",",
"'all'",
"]",
":",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'sync'",
",",
"'-l'",
",",
"option",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'There is no option named: {!r}.'",
".",
"format",
"(",
"option",
")",
")"
]
| List but don't copy.
Args:
option: 'system', 'vendor', 'oem', 'data', 'all' | [
"List",
"but",
"don",
"t",
"copy",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L285-L294 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.install | def install(self, package: str, option: str = '-r') -> None:
'''Push package to the device and install it.
Args:
option:
-l: forward lock application
-r: replace existing application
-t: allow test packages
-s: install application on sdcard
-d: allow version code downgrade (debuggable packages only)
-g: grant all runtime permissions
'''
if not os.path.isfile(package):
raise FileNotFoundError(f'{package!r} does not exist.')
for i in option:
if i not in '-lrtsdg':
raise ValueError(f'There is no option named: {option!r}.')
self._execute('-s', self.device_sn, 'install', option, package) | python | def install(self, package: str, option: str = '-r') -> None:
'''Push package to the device and install it.
Args:
option:
-l: forward lock application
-r: replace existing application
-t: allow test packages
-s: install application on sdcard
-d: allow version code downgrade (debuggable packages only)
-g: grant all runtime permissions
'''
if not os.path.isfile(package):
raise FileNotFoundError(f'{package!r} does not exist.')
for i in option:
if i not in '-lrtsdg':
raise ValueError(f'There is no option named: {option!r}.')
self._execute('-s', self.device_sn, 'install', option, package) | [
"def",
"install",
"(",
"self",
",",
"package",
":",
"str",
",",
"option",
":",
"str",
"=",
"'-r'",
")",
"->",
"None",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"package",
")",
":",
"raise",
"FileNotFoundError",
"(",
"f'{package!r} does not exist.'",
")",
"for",
"i",
"in",
"option",
":",
"if",
"i",
"not",
"in",
"'-lrtsdg'",
":",
"raise",
"ValueError",
"(",
"f'There is no option named: {option!r}.'",
")",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'install'",
",",
"option",
",",
"package",
")"
]
| Push package to the device and install it.
Args:
option:
-l: forward lock application
-r: replace existing application
-t: allow test packages
-s: install application on sdcard
-d: allow version code downgrade (debuggable packages only)
-g: grant all runtime permissions | [
"Push",
"package",
"to",
"the",
"device",
"and",
"install",
"it",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L297-L314 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.uninstall | def uninstall(self, package: str) -> None:
'''Remove this app package from the device.'''
if package not in self.view_packgets_list():
raise NoSuchPackageException(
f'There is no such package {package!r}.')
self._execute('-s', self.device_sn, 'uninstall', package) | python | def uninstall(self, package: str) -> None:
'''Remove this app package from the device.'''
if package not in self.view_packgets_list():
raise NoSuchPackageException(
f'There is no such package {package!r}.')
self._execute('-s', self.device_sn, 'uninstall', package) | [
"def",
"uninstall",
"(",
"self",
",",
"package",
":",
"str",
")",
"->",
"None",
":",
"if",
"package",
"not",
"in",
"self",
".",
"view_packgets_list",
"(",
")",
":",
"raise",
"NoSuchPackageException",
"(",
"f'There is no such package {package!r}.'",
")",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'uninstall'",
",",
"package",
")"
]
| Remove this app package from the device. | [
"Remove",
"this",
"app",
"package",
"from",
"the",
"device",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L338-L343 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.view_packgets_list | def view_packgets_list(self, option: str = '-e', keyword: str = '') -> list:
'''Show all packages.
Args:
option:
-f see their associated file
-d filter to only show disabled packages
-e filter to only show enabled packages
-s filter to only show system packages
-3 filter to only show third party packages
-i see the installer for the packages
-u also include uninstalled packages
-keyword: optionally only those whose name contains the text in keyword
'''
if option not in ['-f', '-d', '-e', '-s', '-3', '-i', '-u']:
raise ValueError(f'There is no option called {option!r}.')
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'pm', 'list', 'packages', option, keyword)
return list(map(lambda x: x[8:], output.splitlines())) | python | def view_packgets_list(self, option: str = '-e', keyword: str = '') -> list:
'''Show all packages.
Args:
option:
-f see their associated file
-d filter to only show disabled packages
-e filter to only show enabled packages
-s filter to only show system packages
-3 filter to only show third party packages
-i see the installer for the packages
-u also include uninstalled packages
-keyword: optionally only those whose name contains the text in keyword
'''
if option not in ['-f', '-d', '-e', '-s', '-3', '-i', '-u']:
raise ValueError(f'There is no option called {option!r}.')
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'pm', 'list', 'packages', option, keyword)
return list(map(lambda x: x[8:], output.splitlines())) | [
"def",
"view_packgets_list",
"(",
"self",
",",
"option",
":",
"str",
"=",
"'-e'",
",",
"keyword",
":",
"str",
"=",
"''",
")",
"->",
"list",
":",
"if",
"option",
"not",
"in",
"[",
"'-f'",
",",
"'-d'",
",",
"'-e'",
",",
"'-s'",
",",
"'-3'",
",",
"'-i'",
",",
"'-u'",
"]",
":",
"raise",
"ValueError",
"(",
"f'There is no option called {option!r}.'",
")",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'pm'",
",",
"'list'",
",",
"'packages'",
",",
"option",
",",
"keyword",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"8",
":",
"]",
",",
"output",
".",
"splitlines",
"(",
")",
")",
")"
]
| Show all packages.
Args:
option:
-f see their associated file
-d filter to only show disabled packages
-e filter to only show enabled packages
-s filter to only show system packages
-3 filter to only show third party packages
-i see the installer for the packages
-u also include uninstalled packages
-keyword: optionally only those whose name contains the text in keyword | [
"Show",
"all",
"packages",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L352-L370 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.