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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.set_conditions | def set_conditions(self, trigger_id, conditions, trigger_mode=None):
"""
Set the conditions for the trigger.
This sets the conditions for all trigger modes, replacing existing conditions for all trigger modes.
:param trigger_id: The relevant Trigger definition id
:param trigger_mode: Optional Trigger mode
:param conditions: Collection of Conditions to set.
:type trigger_mode: TriggerMode
:type conditions: List of Condition
:return: The new conditions.
"""
data = self._serialize_object(conditions)
if trigger_mode is not None:
url = self._service_url(['triggers', trigger_id, 'conditions', trigger_mode])
else:
url = self._service_url(['triggers', trigger_id, 'conditions'])
response = self._put(url, data)
return Condition.list_to_object_list(response) | python | def set_conditions(self, trigger_id, conditions, trigger_mode=None):
"""
Set the conditions for the trigger.
This sets the conditions for all trigger modes, replacing existing conditions for all trigger modes.
:param trigger_id: The relevant Trigger definition id
:param trigger_mode: Optional Trigger mode
:param conditions: Collection of Conditions to set.
:type trigger_mode: TriggerMode
:type conditions: List of Condition
:return: The new conditions.
"""
data = self._serialize_object(conditions)
if trigger_mode is not None:
url = self._service_url(['triggers', trigger_id, 'conditions', trigger_mode])
else:
url = self._service_url(['triggers', trigger_id, 'conditions'])
response = self._put(url, data)
return Condition.list_to_object_list(response) | [
"def",
"set_conditions",
"(",
"self",
",",
"trigger_id",
",",
"conditions",
",",
"trigger_mode",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"_serialize_object",
"(",
"conditions",
")",
"if",
"trigger_mode",
"is",
"not",
"None",
":",
"url",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"trigger_id",
",",
"'conditions'",
",",
"trigger_mode",
"]",
")",
"else",
":",
"url",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"trigger_id",
",",
"'conditions'",
"]",
")",
"response",
"=",
"self",
".",
"_put",
"(",
"url",
",",
"data",
")",
"return",
"Condition",
".",
"list_to_object_list",
"(",
"response",
")"
] | Set the conditions for the trigger.
This sets the conditions for all trigger modes, replacing existing conditions for all trigger modes.
:param trigger_id: The relevant Trigger definition id
:param trigger_mode: Optional Trigger mode
:param conditions: Collection of Conditions to set.
:type trigger_mode: TriggerMode
:type conditions: List of Condition
:return: The new conditions. | [
"Set",
"the",
"conditions",
"for",
"the",
"trigger",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L279-L299 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.conditions | def conditions(self, trigger_id):
"""
Get all conditions for a specific trigger.
:param trigger_id: Trigger definition id to be retrieved
:return: list of condition objects
"""
response = self._get(self._service_url(['triggers', trigger_id, 'conditions']))
return Condition.list_to_object_list(response) | python | def conditions(self, trigger_id):
"""
Get all conditions for a specific trigger.
:param trigger_id: Trigger definition id to be retrieved
:return: list of condition objects
"""
response = self._get(self._service_url(['triggers', trigger_id, 'conditions']))
return Condition.list_to_object_list(response) | [
"def",
"conditions",
"(",
"self",
",",
"trigger_id",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"trigger_id",
",",
"'conditions'",
"]",
")",
")",
"return",
"Condition",
".",
"list_to_object_list",
"(",
"response",
")"
] | Get all conditions for a specific trigger.
:param trigger_id: Trigger definition id to be retrieved
:return: list of condition objects | [
"Get",
"all",
"conditions",
"for",
"a",
"specific",
"trigger",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L301-L309 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.create_dampening | def create_dampening(self, trigger_id, dampening):
"""
Create a new dampening.
:param trigger_id: TriggerId definition attached to the dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Created dampening
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', trigger_id, 'dampenings'])
return Dampening(self._post(url, data)) | python | def create_dampening(self, trigger_id, dampening):
"""
Create a new dampening.
:param trigger_id: TriggerId definition attached to the dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Created dampening
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', trigger_id, 'dampenings'])
return Dampening(self._post(url, data)) | [
"def",
"create_dampening",
"(",
"self",
",",
"trigger_id",
",",
"dampening",
")",
":",
"data",
"=",
"self",
".",
"_serialize_object",
"(",
"dampening",
")",
"url",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"trigger_id",
",",
"'dampenings'",
"]",
")",
"return",
"Dampening",
"(",
"self",
".",
"_post",
"(",
"url",
",",
"data",
")",
")"
] | Create a new dampening.
:param trigger_id: TriggerId definition attached to the dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Created dampening | [
"Create",
"a",
"new",
"dampening",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L328-L339 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.delete_dampening | def delete_dampening(self, trigger_id, dampening_id):
"""
Delete an existing dampening definition.
:param trigger_id: Trigger definition id for deletion.
:param dampening_id: Dampening definition id to be deleted.
"""
self._delete(self._service_url(['triggers', trigger_id, 'dampenings', dampening_id])) | python | def delete_dampening(self, trigger_id, dampening_id):
"""
Delete an existing dampening definition.
:param trigger_id: Trigger definition id for deletion.
:param dampening_id: Dampening definition id to be deleted.
"""
self._delete(self._service_url(['triggers', trigger_id, 'dampenings', dampening_id])) | [
"def",
"delete_dampening",
"(",
"self",
",",
"trigger_id",
",",
"dampening_id",
")",
":",
"self",
".",
"_delete",
"(",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"trigger_id",
",",
"'dampenings'",
",",
"dampening_id",
"]",
")",
")"
] | Delete an existing dampening definition.
:param trigger_id: Trigger definition id for deletion.
:param dampening_id: Dampening definition id to be deleted. | [
"Delete",
"an",
"existing",
"dampening",
"definition",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L341-L348 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.update_dampening | def update_dampening(self, trigger_id, dampening_id):
"""
Update an existing dampening definition.
Note that the trigger mode can not be changed using this method.
:param trigger_id: Trigger definition id targeted for update.
:param dampening_id: Dampening definition id to be updated.
:return: Updated Dampening
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', trigger_id, 'dampenings', dampening_id])
return Dampening(self._put(url, data)) | python | def update_dampening(self, trigger_id, dampening_id):
"""
Update an existing dampening definition.
Note that the trigger mode can not be changed using this method.
:param trigger_id: Trigger definition id targeted for update.
:param dampening_id: Dampening definition id to be updated.
:return: Updated Dampening
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', trigger_id, 'dampenings', dampening_id])
return Dampening(self._put(url, data)) | [
"def",
"update_dampening",
"(",
"self",
",",
"trigger_id",
",",
"dampening_id",
")",
":",
"data",
"=",
"self",
".",
"_serialize_object",
"(",
"dampening",
")",
"url",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"trigger_id",
",",
"'dampenings'",
",",
"dampening_id",
"]",
")",
"return",
"Dampening",
"(",
"self",
".",
"_put",
"(",
"url",
",",
"data",
")",
")"
] | Update an existing dampening definition.
Note that the trigger mode can not be changed using this method.
:param trigger_id: Trigger definition id targeted for update.
:param dampening_id: Dampening definition id to be updated.
:return: Updated Dampening | [
"Update",
"an",
"existing",
"dampening",
"definition",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L350-L361 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.create_group_dampening | def create_group_dampening(self, group_id, dampening):
"""
Create a new group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Group Dampening created
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', 'groups', group_id, 'dampenings'])
return Dampening(self._post(url, data)) | python | def create_group_dampening(self, group_id, dampening):
"""
Create a new group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Group Dampening created
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', 'groups', group_id, 'dampenings'])
return Dampening(self._post(url, data)) | [
"def",
"create_group_dampening",
"(",
"self",
",",
"group_id",
",",
"dampening",
")",
":",
"data",
"=",
"self",
".",
"_serialize_object",
"(",
"dampening",
")",
"url",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"'groups'",
",",
"group_id",
",",
"'dampenings'",
"]",
")",
"return",
"Dampening",
"(",
"self",
".",
"_post",
"(",
"url",
",",
"data",
")",
")"
] | Create a new group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Group Dampening created | [
"Create",
"a",
"new",
"group",
"dampening"
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L363-L374 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.update_group_dampening | def update_group_dampening(self, group_id, dampening_id, dampening):
"""
Update an existing group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening_id: id of the dampening to be updated
:return: Group Dampening created
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', 'groups', group_id, 'dampenings', dampening_id])
return Dampening(self._put(url, data)) | python | def update_group_dampening(self, group_id, dampening_id, dampening):
"""
Update an existing group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening_id: id of the dampening to be updated
:return: Group Dampening created
"""
data = self._serialize_object(dampening)
url = self._service_url(['triggers', 'groups', group_id, 'dampenings', dampening_id])
return Dampening(self._put(url, data)) | [
"def",
"update_group_dampening",
"(",
"self",
",",
"group_id",
",",
"dampening_id",
",",
"dampening",
")",
":",
"data",
"=",
"self",
".",
"_serialize_object",
"(",
"dampening",
")",
"url",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"'groups'",
",",
"group_id",
",",
"'dampenings'",
",",
"dampening_id",
"]",
")",
"return",
"Dampening",
"(",
"self",
".",
"_put",
"(",
"url",
",",
"data",
")",
")"
] | Update an existing group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening_id: id of the dampening to be updated
:return: Group Dampening created | [
"Update",
"an",
"existing",
"group",
"dampening"
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L376-L386 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.delete_group_dampening | def delete_group_dampening(self, group_id, dampening_id):
"""
Delete an existing group dampening
:param group_id: Group Trigger id to be retrieved
:param dampening_id: id of the Dampening to be deleted
"""
self._delete(self._service_url(['triggers', 'groups', group_id, 'dampenings', dampening_id])) | python | def delete_group_dampening(self, group_id, dampening_id):
"""
Delete an existing group dampening
:param group_id: Group Trigger id to be retrieved
:param dampening_id: id of the Dampening to be deleted
"""
self._delete(self._service_url(['triggers', 'groups', group_id, 'dampenings', dampening_id])) | [
"def",
"delete_group_dampening",
"(",
"self",
",",
"group_id",
",",
"dampening_id",
")",
":",
"self",
".",
"_delete",
"(",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"'groups'",
",",
"group_id",
",",
"'dampenings'",
",",
"dampening_id",
"]",
")",
")"
] | Delete an existing group dampening
:param group_id: Group Trigger id to be retrieved
:param dampening_id: id of the Dampening to be deleted | [
"Delete",
"an",
"existing",
"group",
"dampening"
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L388-L395 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.set_group_member_orphan | def set_group_member_orphan(self, member_id):
"""
Make a non-orphan member trigger into an orphan.
:param member_id: Member Trigger id to be made an orphan.
"""
self._put(self._service_url(['triggers', 'groups', 'members', member_id, 'orphan']), data=None, parse_json=False) | python | def set_group_member_orphan(self, member_id):
"""
Make a non-orphan member trigger into an orphan.
:param member_id: Member Trigger id to be made an orphan.
"""
self._put(self._service_url(['triggers', 'groups', 'members', member_id, 'orphan']), data=None, parse_json=False) | [
"def",
"set_group_member_orphan",
"(",
"self",
",",
"member_id",
")",
":",
"self",
".",
"_put",
"(",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"'groups'",
",",
"'members'",
",",
"member_id",
",",
"'orphan'",
"]",
")",
",",
"data",
"=",
"None",
",",
"parse_json",
"=",
"False",
")"
] | Make a non-orphan member trigger into an orphan.
:param member_id: Member Trigger id to be made an orphan. | [
"Make",
"a",
"non",
"-",
"orphan",
"member",
"trigger",
"into",
"an",
"orphan",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L397-L403 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.set_group_member_unorphan | def set_group_member_unorphan(self, member_id, unorphan_info):
"""
Make an orphan member trigger into an group trigger.
:param member_id: Orphan Member Trigger id to be assigned into a group trigger
:param unorphan_info: Only context and dataIdMap are used when changing back to a non-orphan.
:type unorphan_info: UnorphanMemberInfo
:return: Trigger for the group
"""
data = self._serialize_object(unorphan_info)
data = self._service_url(['triggers', 'groups', 'members', member_id, 'unorphan'])
return Trigger(self._put(url, data)) | python | def set_group_member_unorphan(self, member_id, unorphan_info):
"""
Make an orphan member trigger into an group trigger.
:param member_id: Orphan Member Trigger id to be assigned into a group trigger
:param unorphan_info: Only context and dataIdMap are used when changing back to a non-orphan.
:type unorphan_info: UnorphanMemberInfo
:return: Trigger for the group
"""
data = self._serialize_object(unorphan_info)
data = self._service_url(['triggers', 'groups', 'members', member_id, 'unorphan'])
return Trigger(self._put(url, data)) | [
"def",
"set_group_member_unorphan",
"(",
"self",
",",
"member_id",
",",
"unorphan_info",
")",
":",
"data",
"=",
"self",
".",
"_serialize_object",
"(",
"unorphan_info",
")",
"data",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"'groups'",
",",
"'members'",
",",
"member_id",
",",
"'unorphan'",
"]",
")",
"return",
"Trigger",
"(",
"self",
".",
"_put",
"(",
"url",
",",
"data",
")",
")"
] | Make an orphan member trigger into an group trigger.
:param member_id: Orphan Member Trigger id to be assigned into a group trigger
:param unorphan_info: Only context and dataIdMap are used when changing back to a non-orphan.
:type unorphan_info: UnorphanMemberInfo
:return: Trigger for the group | [
"Make",
"an",
"orphan",
"member",
"trigger",
"into",
"an",
"group",
"trigger",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L405-L416 | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | AlertsTriggerClient.enable | def enable(self, trigger_ids=[]):
"""
Enable triggers.
:param trigger_ids: List of trigger definition ids to enable
"""
trigger_ids = ','.join(trigger_ids)
url = self._service_url(['triggers', 'enabled'], params={'triggerIds': trigger_ids, 'enabled': 'true'})
self._put(url, data=None, parse_json=False) | python | def enable(self, trigger_ids=[]):
"""
Enable triggers.
:param trigger_ids: List of trigger definition ids to enable
"""
trigger_ids = ','.join(trigger_ids)
url = self._service_url(['triggers', 'enabled'], params={'triggerIds': trigger_ids, 'enabled': 'true'})
self._put(url, data=None, parse_json=False) | [
"def",
"enable",
"(",
"self",
",",
"trigger_ids",
"=",
"[",
"]",
")",
":",
"trigger_ids",
"=",
"','",
".",
"join",
"(",
"trigger_ids",
")",
"url",
"=",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"'enabled'",
"]",
",",
"params",
"=",
"{",
"'triggerIds'",
":",
"trigger_ids",
",",
"'enabled'",
":",
"'true'",
"}",
")",
"self",
".",
"_put",
"(",
"url",
",",
"data",
"=",
"None",
",",
"parse_json",
"=",
"False",
")"
] | Enable triggers.
:param trigger_ids: List of trigger definition ids to enable | [
"Enable",
"triggers",
"."
] | 52371f9ebabbe310efee2a8ff8eb735ccc0654bb | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L418-L426 | train |
totalgood/twip | twip/tweets.py | get_twitter | def get_twitter(app_key=None, app_secret=None, search='python', location='', **kwargs):
"""Location may be specified with a string name or latitude, longitude, radius"""
if not app_key:
from settings_secret import TWITTER_API_KEY as app_key
if not app_secret:
from settings_secret import TWITTER_API_SECRET as app_secret
twitter = Twython(app_key, app_secret, oauth_version=2)
return Twython(app_key, access_token=twitter.obtain_access_token()) | python | def get_twitter(app_key=None, app_secret=None, search='python', location='', **kwargs):
"""Location may be specified with a string name or latitude, longitude, radius"""
if not app_key:
from settings_secret import TWITTER_API_KEY as app_key
if not app_secret:
from settings_secret import TWITTER_API_SECRET as app_secret
twitter = Twython(app_key, app_secret, oauth_version=2)
return Twython(app_key, access_token=twitter.obtain_access_token()) | [
"def",
"get_twitter",
"(",
"app_key",
"=",
"None",
",",
"app_secret",
"=",
"None",
",",
"search",
"=",
"'python'",
",",
"location",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"app_key",
":",
"from",
"settings_secret",
"import",
"TWITTER_API_KEY",
"as",
"app_key",
"if",
"not",
"app_secret",
":",
"from",
"settings_secret",
"import",
"TWITTER_API_SECRET",
"as",
"app_secret",
"twitter",
"=",
"Twython",
"(",
"app_key",
",",
"app_secret",
",",
"oauth_version",
"=",
"2",
")",
"return",
"Twython",
"(",
"app_key",
",",
"access_token",
"=",
"twitter",
".",
"obtain_access_token",
"(",
")",
")"
] | Location may be specified with a string name or latitude, longitude, radius | [
"Location",
"may",
"be",
"specified",
"with",
"a",
"string",
"name",
"or",
"latitude",
"longitude",
"radius"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/tweets.py#L69-L76 | train |
totalgood/twip | twip/tweets.py | limitted_dump | def limitted_dump(cursor=None, twitter=None, path='tweets.json', limit=450, rate=TWITTER_SEARCH_RATE_LIMIT, indent=-1):
"""Dump a limitted number of json.dump-able objects to the indicated file
rate (int): Number of queries per 15 minute twitter window
"""
if not twitter:
twitter = get_twitter()
cursor = cursor or 'python'
if isinstance(cursor, basestring):
cursor = get_cursor(twitter, search=cursor)
newline = '\n' if indent is not None else ''
if indent < 0:
indent = None
# TODO: keep track of T0 for the optimal "reset" sleep duration
with (open(path, 'w') if not isinstance(path, file) else path) as f:
f.write('[\n')
for i, obj in enumerate(cursor):
f.write(json.dumps(obj, indent=indent))
if i < limit - 1:
f.write(',' + newline)
else:
break
remaining = int(twitter.get_lastfunction_header('x-rate-limit-remaining'))
if remaining > 0:
sleep(1. / rate)
else:
sleep(15 * 60)
f.write('\n]\n') | python | def limitted_dump(cursor=None, twitter=None, path='tweets.json', limit=450, rate=TWITTER_SEARCH_RATE_LIMIT, indent=-1):
"""Dump a limitted number of json.dump-able objects to the indicated file
rate (int): Number of queries per 15 minute twitter window
"""
if not twitter:
twitter = get_twitter()
cursor = cursor or 'python'
if isinstance(cursor, basestring):
cursor = get_cursor(twitter, search=cursor)
newline = '\n' if indent is not None else ''
if indent < 0:
indent = None
# TODO: keep track of T0 for the optimal "reset" sleep duration
with (open(path, 'w') if not isinstance(path, file) else path) as f:
f.write('[\n')
for i, obj in enumerate(cursor):
f.write(json.dumps(obj, indent=indent))
if i < limit - 1:
f.write(',' + newline)
else:
break
remaining = int(twitter.get_lastfunction_header('x-rate-limit-remaining'))
if remaining > 0:
sleep(1. / rate)
else:
sleep(15 * 60)
f.write('\n]\n') | [
"def",
"limitted_dump",
"(",
"cursor",
"=",
"None",
",",
"twitter",
"=",
"None",
",",
"path",
"=",
"'tweets.json'",
",",
"limit",
"=",
"450",
",",
"rate",
"=",
"TWITTER_SEARCH_RATE_LIMIT",
",",
"indent",
"=",
"-",
"1",
")",
":",
"if",
"not",
"twitter",
":",
"twitter",
"=",
"get_twitter",
"(",
")",
"cursor",
"=",
"cursor",
"or",
"'python'",
"if",
"isinstance",
"(",
"cursor",
",",
"basestring",
")",
":",
"cursor",
"=",
"get_cursor",
"(",
"twitter",
",",
"search",
"=",
"cursor",
")",
"newline",
"=",
"'\\n'",
"if",
"indent",
"is",
"not",
"None",
"else",
"''",
"if",
"indent",
"<",
"0",
":",
"indent",
"=",
"None",
"# TODO: keep track of T0 for the optimal \"reset\" sleep duration",
"with",
"(",
"open",
"(",
"path",
",",
"'w'",
")",
"if",
"not",
"isinstance",
"(",
"path",
",",
"file",
")",
"else",
"path",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'[\\n'",
")",
"for",
"i",
",",
"obj",
"in",
"enumerate",
"(",
"cursor",
")",
":",
"f",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"obj",
",",
"indent",
"=",
"indent",
")",
")",
"if",
"i",
"<",
"limit",
"-",
"1",
":",
"f",
".",
"write",
"(",
"','",
"+",
"newline",
")",
"else",
":",
"break",
"remaining",
"=",
"int",
"(",
"twitter",
".",
"get_lastfunction_header",
"(",
"'x-rate-limit-remaining'",
")",
")",
"if",
"remaining",
">",
"0",
":",
"sleep",
"(",
"1.",
"/",
"rate",
")",
"else",
":",
"sleep",
"(",
"15",
"*",
"60",
")",
"f",
".",
"write",
"(",
"'\\n]\\n'",
")"
] | Dump a limitted number of json.dump-able objects to the indicated file
rate (int): Number of queries per 15 minute twitter window | [
"Dump",
"a",
"limitted",
"number",
"of",
"json",
".",
"dump",
"-",
"able",
"objects",
"to",
"the",
"indicated",
"file"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/tweets.py#L87-L114 | train |
SHDShim/pytheos | pytheos/eqn_therm_Dorogokupets2007.py | altshuler_grun | def altshuler_grun(v, v0, gamma0, gamma_inf, beta):
"""
calculate Gruneisen parameter for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:return: Gruneisen parameter
"""
x = v / v0
return gamma_inf + (gamma0 - gamma_inf) * np.power(x, beta) | python | def altshuler_grun(v, v0, gamma0, gamma_inf, beta):
"""
calculate Gruneisen parameter for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:return: Gruneisen parameter
"""
x = v / v0
return gamma_inf + (gamma0 - gamma_inf) * np.power(x, beta) | [
"def",
"altshuler_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
")",
":",
"x",
"=",
"v",
"/",
"v0",
"return",
"gamma_inf",
"+",
"(",
"gamma0",
"-",
"gamma_inf",
")",
"*",
"np",
".",
"power",
"(",
"x",
",",
"beta",
")"
] | calculate Gruneisen parameter for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:return: Gruneisen parameter | [
"calculate",
"Gruneisen",
"parameter",
"for",
"Altshuler",
"equation"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2007.py#L9-L21 | train |
SHDShim/pytheos | pytheos/eqn_therm_Dorogokupets2007.py | altshuler_debyetemp | def altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta0):
"""
calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K
"""
x = v / v0
if isuncertainties([v, v0, gamma0, gamma_inf, beta, theta0]):
theta = theta0 * np.power(x, -1. * gamma_inf) *\
unp.exp((gamma0 - gamma_inf) / beta * (1. - np.power(x, beta)))
else:
theta = theta0 * np.power(x, -1. * gamma_inf) *\
np.exp((gamma0 - gamma_inf) / beta * (1. - np.power(x, beta)))
return theta | python | def altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta0):
"""
calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K
"""
x = v / v0
if isuncertainties([v, v0, gamma0, gamma_inf, beta, theta0]):
theta = theta0 * np.power(x, -1. * gamma_inf) *\
unp.exp((gamma0 - gamma_inf) / beta * (1. - np.power(x, beta)))
else:
theta = theta0 * np.power(x, -1. * gamma_inf) *\
np.exp((gamma0 - gamma_inf) / beta * (1. - np.power(x, beta)))
return theta | [
"def",
"altshuler_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
",",
"theta0",
")",
":",
"x",
"=",
"v",
"/",
"v0",
"if",
"isuncertainties",
"(",
"[",
"v",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
",",
"theta0",
"]",
")",
":",
"theta",
"=",
"theta0",
"*",
"np",
".",
"power",
"(",
"x",
",",
"-",
"1.",
"*",
"gamma_inf",
")",
"*",
"unp",
".",
"exp",
"(",
"(",
"gamma0",
"-",
"gamma_inf",
")",
"/",
"beta",
"*",
"(",
"1.",
"-",
"np",
".",
"power",
"(",
"x",
",",
"beta",
")",
")",
")",
"else",
":",
"theta",
"=",
"theta0",
"*",
"np",
".",
"power",
"(",
"x",
",",
"-",
"1.",
"*",
"gamma_inf",
")",
"*",
"np",
".",
"exp",
"(",
"(",
"gamma0",
"-",
"gamma_inf",
")",
"/",
"beta",
"*",
"(",
"1.",
"-",
"np",
".",
"power",
"(",
"x",
",",
"beta",
")",
")",
")",
"return",
"theta"
] | calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K | [
"calculate",
"Debye",
"temperature",
"for",
"Altshuler",
"equation"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2007.py#L24-L43 | train |
SHDShim/pytheos | pytheos/eqn_therm_Dorogokupets2007.py | dorogokupets2007_pth | def dorogokupets2007_pth(v, temp, v0, gamma0, gamma_inf, beta, theta0, n, z,
three_r=3. * constants.R, t_ref=300.):
"""
calculate thermal pressure for Dorogokupets 2007 EOS
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: thermal pressure in GPa
"""
v_mol = vol_uc2mol(v, z)
# x = v_mol / v0_mol
gamma = altshuler_grun(v, v0, gamma0, gamma_inf, beta)
theta = altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta0)
def f(t):
xx = theta / t
debye = debye_E(xx)
Eth = three_r * n * t * debye
return (gamma / v_mol * Eth) * 1.e-9
return f(temp) - f(t_ref) | python | def dorogokupets2007_pth(v, temp, v0, gamma0, gamma_inf, beta, theta0, n, z,
three_r=3. * constants.R, t_ref=300.):
"""
calculate thermal pressure for Dorogokupets 2007 EOS
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: thermal pressure in GPa
"""
v_mol = vol_uc2mol(v, z)
# x = v_mol / v0_mol
gamma = altshuler_grun(v, v0, gamma0, gamma_inf, beta)
theta = altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta0)
def f(t):
xx = theta / t
debye = debye_E(xx)
Eth = three_r * n * t * debye
return (gamma / v_mol * Eth) * 1.e-9
return f(temp) - f(t_ref) | [
"def",
"dorogokupets2007_pth",
"(",
"v",
",",
"temp",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
",",
"theta0",
",",
"n",
",",
"z",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
",",
"t_ref",
"=",
"300.",
")",
":",
"v_mol",
"=",
"vol_uc2mol",
"(",
"v",
",",
"z",
")",
"# x = v_mol / v0_mol",
"gamma",
"=",
"altshuler_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
")",
"theta",
"=",
"altshuler_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
",",
"theta0",
")",
"def",
"f",
"(",
"t",
")",
":",
"xx",
"=",
"theta",
"/",
"t",
"debye",
"=",
"debye_E",
"(",
"xx",
")",
"Eth",
"=",
"three_r",
"*",
"n",
"*",
"t",
"*",
"debye",
"return",
"(",
"gamma",
"/",
"v_mol",
"*",
"Eth",
")",
"*",
"1.e-9",
"return",
"f",
"(",
"temp",
")",
"-",
"f",
"(",
"t_ref",
")"
] | calculate thermal pressure for Dorogokupets 2007 EOS
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: thermal pressure in GPa | [
"calculate",
"thermal",
"pressure",
"for",
"Dorogokupets",
"2007",
"EOS"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2007.py#L46-L75 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.bind | def bind(cls, app, *paths, methods=None, name=None, view=None):
"""Connect to admin interface and application."""
# Register self in admin
if view is None:
app.ps.admin.register(cls)
if not paths:
paths = ('%s/%s' % (app.ps.admin.cfg.prefix, name or cls.name),)
cls.url = paths[0]
return super(AdminHandler, cls).bind(app, *paths, methods=methods, name=name, view=view) | python | def bind(cls, app, *paths, methods=None, name=None, view=None):
"""Connect to admin interface and application."""
# Register self in admin
if view is None:
app.ps.admin.register(cls)
if not paths:
paths = ('%s/%s' % (app.ps.admin.cfg.prefix, name or cls.name),)
cls.url = paths[0]
return super(AdminHandler, cls).bind(app, *paths, methods=methods, name=name, view=view) | [
"def",
"bind",
"(",
"cls",
",",
"app",
",",
"*",
"paths",
",",
"methods",
"=",
"None",
",",
"name",
"=",
"None",
",",
"view",
"=",
"None",
")",
":",
"# Register self in admin",
"if",
"view",
"is",
"None",
":",
"app",
".",
"ps",
".",
"admin",
".",
"register",
"(",
"cls",
")",
"if",
"not",
"paths",
":",
"paths",
"=",
"(",
"'%s/%s'",
"%",
"(",
"app",
".",
"ps",
".",
"admin",
".",
"cfg",
".",
"prefix",
",",
"name",
"or",
"cls",
".",
"name",
")",
",",
")",
"cls",
".",
"url",
"=",
"paths",
"[",
"0",
"]",
"return",
"super",
"(",
"AdminHandler",
",",
"cls",
")",
".",
"bind",
"(",
"app",
",",
"*",
"paths",
",",
"methods",
"=",
"methods",
",",
"name",
"=",
"name",
",",
"view",
"=",
"view",
")"
] | Connect to admin interface and application. | [
"Connect",
"to",
"admin",
"interface",
"and",
"application",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L70-L78 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.action | def action(cls, view):
"""Register admin view action."""
name = "%s:%s" % (cls.name, view.__name__)
path = "%s/%s" % (cls.url, view.__name__)
cls.actions.append((view.__doc__, path))
return cls.register(path, name=name)(view) | python | def action(cls, view):
"""Register admin view action."""
name = "%s:%s" % (cls.name, view.__name__)
path = "%s/%s" % (cls.url, view.__name__)
cls.actions.append((view.__doc__, path))
return cls.register(path, name=name)(view) | [
"def",
"action",
"(",
"cls",
",",
"view",
")",
":",
"name",
"=",
"\"%s:%s\"",
"%",
"(",
"cls",
".",
"name",
",",
"view",
".",
"__name__",
")",
"path",
"=",
"\"%s/%s\"",
"%",
"(",
"cls",
".",
"url",
",",
"view",
".",
"__name__",
")",
"cls",
".",
"actions",
".",
"append",
"(",
"(",
"view",
".",
"__doc__",
",",
"path",
")",
")",
"return",
"cls",
".",
"register",
"(",
"path",
",",
"name",
"=",
"name",
")",
"(",
"view",
")"
] | Register admin view action. | [
"Register",
"admin",
"view",
"action",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L81-L86 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.dispatch | async def dispatch(self, request, **kwargs):
"""Dispatch a request."""
# Authorize request
self.auth = await self.authorize(request)
# Load collection
self.collection = await self.load_many(request)
# Load resource
self.resource = await self.load_one(request)
if request.method == 'GET' and self.resource is None:
# Filter collection
self.collection = await self.filter(request)
# Sort collection
self.columns_sort = request.query.get('ap-sort', self.columns_sort)
if self.columns_sort:
reverse = self.columns_sort.startswith('-')
self.columns_sort = self.columns_sort.lstrip('+-')
self.collection = await self.sort(request, reverse=reverse)
# Paginate collection
try:
self.offset = int(request.query.get('ap-offset', 0))
if self.limit:
self.count = await self.count(request)
self.collection = await self.paginate(request)
except ValueError:
pass
return await super(AdminHandler, self).dispatch(request, **kwargs) | python | async def dispatch(self, request, **kwargs):
"""Dispatch a request."""
# Authorize request
self.auth = await self.authorize(request)
# Load collection
self.collection = await self.load_many(request)
# Load resource
self.resource = await self.load_one(request)
if request.method == 'GET' and self.resource is None:
# Filter collection
self.collection = await self.filter(request)
# Sort collection
self.columns_sort = request.query.get('ap-sort', self.columns_sort)
if self.columns_sort:
reverse = self.columns_sort.startswith('-')
self.columns_sort = self.columns_sort.lstrip('+-')
self.collection = await self.sort(request, reverse=reverse)
# Paginate collection
try:
self.offset = int(request.query.get('ap-offset', 0))
if self.limit:
self.count = await self.count(request)
self.collection = await self.paginate(request)
except ValueError:
pass
return await super(AdminHandler, self).dispatch(request, **kwargs) | [
"async",
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# Authorize request",
"self",
".",
"auth",
"=",
"await",
"self",
".",
"authorize",
"(",
"request",
")",
"# Load collection",
"self",
".",
"collection",
"=",
"await",
"self",
".",
"load_many",
"(",
"request",
")",
"# Load resource",
"self",
".",
"resource",
"=",
"await",
"self",
".",
"load_one",
"(",
"request",
")",
"if",
"request",
".",
"method",
"==",
"'GET'",
"and",
"self",
".",
"resource",
"is",
"None",
":",
"# Filter collection",
"self",
".",
"collection",
"=",
"await",
"self",
".",
"filter",
"(",
"request",
")",
"# Sort collection",
"self",
".",
"columns_sort",
"=",
"request",
".",
"query",
".",
"get",
"(",
"'ap-sort'",
",",
"self",
".",
"columns_sort",
")",
"if",
"self",
".",
"columns_sort",
":",
"reverse",
"=",
"self",
".",
"columns_sort",
".",
"startswith",
"(",
"'-'",
")",
"self",
".",
"columns_sort",
"=",
"self",
".",
"columns_sort",
".",
"lstrip",
"(",
"'+-'",
")",
"self",
".",
"collection",
"=",
"await",
"self",
".",
"sort",
"(",
"request",
",",
"reverse",
"=",
"reverse",
")",
"# Paginate collection",
"try",
":",
"self",
".",
"offset",
"=",
"int",
"(",
"request",
".",
"query",
".",
"get",
"(",
"'ap-offset'",
",",
"0",
")",
")",
"if",
"self",
".",
"limit",
":",
"self",
".",
"count",
"=",
"await",
"self",
".",
"count",
"(",
"request",
")",
"self",
".",
"collection",
"=",
"await",
"self",
".",
"paginate",
"(",
"request",
")",
"except",
"ValueError",
":",
"pass",
"return",
"await",
"super",
"(",
"AdminHandler",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"*",
"kwargs",
")"
] | Dispatch a request. | [
"Dispatch",
"a",
"request",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L88-L120 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.sort | async def sort(self, request, reverse=False):
"""Sort collection."""
return sorted(
self.collection, key=lambda o: getattr(o, self.columns_sort, 0), reverse=reverse) | python | async def sort(self, request, reverse=False):
"""Sort collection."""
return sorted(
self.collection, key=lambda o: getattr(o, self.columns_sort, 0), reverse=reverse) | [
"async",
"def",
"sort",
"(",
"self",
",",
"request",
",",
"reverse",
"=",
"False",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"collection",
",",
"key",
"=",
"lambda",
"o",
":",
"getattr",
"(",
"o",
",",
"self",
".",
"columns_sort",
",",
"0",
")",
",",
"reverse",
"=",
"reverse",
")"
] | Sort collection. | [
"Sort",
"collection",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L152-L155 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.get_form | async def get_form(self, request):
"""Base point load resource."""
if not self.form:
return None
formdata = await request.post()
return self.form(formdata, obj=self.resource) | python | async def get_form(self, request):
"""Base point load resource."""
if not self.form:
return None
formdata = await request.post()
return self.form(formdata, obj=self.resource) | [
"async",
"def",
"get_form",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"self",
".",
"form",
":",
"return",
"None",
"formdata",
"=",
"await",
"request",
".",
"post",
"(",
")",
"return",
"self",
".",
"form",
"(",
"formdata",
",",
"obj",
"=",
"self",
".",
"resource",
")"
] | Base point load resource. | [
"Base",
"point",
"load",
"resource",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L161-L166 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.get | async def get(self, request):
"""Get collection of resources."""
form = await self.get_form(request)
ctx = dict(active=self, form=form, request=request)
if self.resource:
return self.app.ps.jinja2.render(self.template_item, **ctx)
return self.app.ps.jinja2.render(self.template_list, **ctx) | python | async def get(self, request):
"""Get collection of resources."""
form = await self.get_form(request)
ctx = dict(active=self, form=form, request=request)
if self.resource:
return self.app.ps.jinja2.render(self.template_item, **ctx)
return self.app.ps.jinja2.render(self.template_list, **ctx) | [
"async",
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"form",
"=",
"await",
"self",
".",
"get_form",
"(",
"request",
")",
"ctx",
"=",
"dict",
"(",
"active",
"=",
"self",
",",
"form",
"=",
"form",
",",
"request",
"=",
"request",
")",
"if",
"self",
".",
"resource",
":",
"return",
"self",
".",
"app",
".",
"ps",
".",
"jinja2",
".",
"render",
"(",
"self",
".",
"template_item",
",",
"*",
"*",
"ctx",
")",
"return",
"self",
".",
"app",
".",
"ps",
".",
"jinja2",
".",
"render",
"(",
"self",
".",
"template_list",
",",
"*",
"*",
"ctx",
")"
] | Get collection of resources. | [
"Get",
"collection",
"of",
"resources",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L184-L190 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.columns_formatter | def columns_formatter(cls, colname):
"""Decorator to mark a function as columns formatter."""
def wrapper(func):
cls.columns_formatters[colname] = func
return func
return wrapper | python | def columns_formatter(cls, colname):
"""Decorator to mark a function as columns formatter."""
def wrapper(func):
cls.columns_formatters[colname] = func
return func
return wrapper | [
"def",
"columns_formatter",
"(",
"cls",
",",
"colname",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"cls",
".",
"columns_formatters",
"[",
"colname",
"]",
"=",
"func",
"return",
"func",
"return",
"wrapper"
] | Decorator to mark a function as columns formatter. | [
"Decorator",
"to",
"mark",
"a",
"function",
"as",
"columns",
"formatter",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L202-L207 | train |
klen/muffin-admin | muffin_admin/handler.py | AdminHandler.render_value | def render_value(self, data, column):
"""Render value."""
renderer = self.columns_formatters.get(column, format_value)
return renderer(self, data, column) | python | def render_value(self, data, column):
"""Render value."""
renderer = self.columns_formatters.get(column, format_value)
return renderer(self, data, column) | [
"def",
"render_value",
"(",
"self",
",",
"data",
",",
"column",
")",
":",
"renderer",
"=",
"self",
".",
"columns_formatters",
".",
"get",
"(",
"column",
",",
"format_value",
")",
"return",
"renderer",
"(",
"self",
",",
"data",
",",
"column",
")"
] | Render value. | [
"Render",
"value",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L209-L212 | train |
crdoconnor/commandlib | commandlib/command.py | Command.env | def env(self):
"""
Dict of all environment variables that will be run with this command.
"""
env_vars = os.environ.copy()
env_vars.update(self._env)
new_path = ":".join(
self._paths + [env_vars["PATH"]] if "PATH" in env_vars else [] + self._paths
)
env_vars["PATH"] = new_path
for env_var in self._env_drop:
if env_var in env_vars:
del env_vars[env_var]
return env_vars | python | def env(self):
"""
Dict of all environment variables that will be run with this command.
"""
env_vars = os.environ.copy()
env_vars.update(self._env)
new_path = ":".join(
self._paths + [env_vars["PATH"]] if "PATH" in env_vars else [] + self._paths
)
env_vars["PATH"] = new_path
for env_var in self._env_drop:
if env_var in env_vars:
del env_vars[env_var]
return env_vars | [
"def",
"env",
"(",
"self",
")",
":",
"env_vars",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env_vars",
".",
"update",
"(",
"self",
".",
"_env",
")",
"new_path",
"=",
"\":\"",
".",
"join",
"(",
"self",
".",
"_paths",
"+",
"[",
"env_vars",
"[",
"\"PATH\"",
"]",
"]",
"if",
"\"PATH\"",
"in",
"env_vars",
"else",
"[",
"]",
"+",
"self",
".",
"_paths",
")",
"env_vars",
"[",
"\"PATH\"",
"]",
"=",
"new_path",
"for",
"env_var",
"in",
"self",
".",
"_env_drop",
":",
"if",
"env_var",
"in",
"env_vars",
":",
"del",
"env_vars",
"[",
"env_var",
"]",
"return",
"env_vars"
] | Dict of all environment variables that will be run with this command. | [
"Dict",
"of",
"all",
"environment",
"variables",
"that",
"will",
"be",
"run",
"with",
"this",
"command",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L72-L85 | train |
crdoconnor/commandlib | commandlib/command.py | Command.ignore_errors | def ignore_errors(self):
"""
Return new command object that will not raise an exception when
return code > 0.
"""
new_command = copy.deepcopy(self)
new_command._ignore_errors = True
return new_command | python | def ignore_errors(self):
"""
Return new command object that will not raise an exception when
return code > 0.
"""
new_command = copy.deepcopy(self)
new_command._ignore_errors = True
return new_command | [
"def",
"ignore_errors",
"(",
"self",
")",
":",
"new_command",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_command",
".",
"_ignore_errors",
"=",
"True",
"return",
"new_command"
] | Return new command object that will not raise an exception when
return code > 0. | [
"Return",
"new",
"command",
"object",
"that",
"will",
"not",
"raise",
"an",
"exception",
"when",
"return",
"code",
">",
"0",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L87-L94 | train |
crdoconnor/commandlib | commandlib/command.py | Command.with_env | def with_env(self, **environment_variables):
"""
Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022")
"""
new_env_vars = {
str(var): str(val) for var, val in environment_variables.items()
}
new_command = copy.deepcopy(self)
new_command._env.update(new_env_vars)
return new_command | python | def with_env(self, **environment_variables):
"""
Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022")
"""
new_env_vars = {
str(var): str(val) for var, val in environment_variables.items()
}
new_command = copy.deepcopy(self)
new_command._env.update(new_env_vars)
return new_command | [
"def",
"with_env",
"(",
"self",
",",
"*",
"*",
"environment_variables",
")",
":",
"new_env_vars",
"=",
"{",
"str",
"(",
"var",
")",
":",
"str",
"(",
"val",
")",
"for",
"var",
",",
"val",
"in",
"environment_variables",
".",
"items",
"(",
")",
"}",
"new_command",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_command",
".",
"_env",
".",
"update",
"(",
"new_env_vars",
")",
"return",
"new_command"
] | Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022") | [
"Return",
"new",
"Command",
"object",
"that",
"will",
"be",
"run",
"with",
"additional",
"environment",
"variables",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L115-L129 | train |
crdoconnor/commandlib | commandlib/command.py | Command.without_env | def without_env(self, environment_variable):
"""
Return new Command object that will drop a specified
environment variable if it is set.
new_cmd = old_cmd.without_env("PYTHON_PATH")
"""
new_command = copy.deepcopy(self)
new_command._env_drop.append(str(environment_variable))
return new_command | python | def without_env(self, environment_variable):
"""
Return new Command object that will drop a specified
environment variable if it is set.
new_cmd = old_cmd.without_env("PYTHON_PATH")
"""
new_command = copy.deepcopy(self)
new_command._env_drop.append(str(environment_variable))
return new_command | [
"def",
"without_env",
"(",
"self",
",",
"environment_variable",
")",
":",
"new_command",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_command",
".",
"_env_drop",
".",
"append",
"(",
"str",
"(",
"environment_variable",
")",
")",
"return",
"new_command"
] | Return new Command object that will drop a specified
environment variable if it is set.
new_cmd = old_cmd.without_env("PYTHON_PATH") | [
"Return",
"new",
"Command",
"object",
"that",
"will",
"drop",
"a",
"specified",
"environment",
"variable",
"if",
"it",
"is",
"set",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L131-L140 | train |
crdoconnor/commandlib | commandlib/command.py | Command.in_dir | def in_dir(self, directory):
"""
Return new Command object that will be run in specified
directory.
new_cmd = old_cmd.in_dir("/usr")
"""
new_command = copy.deepcopy(self)
new_command._directory = str(directory)
return new_command | python | def in_dir(self, directory):
"""
Return new Command object that will be run in specified
directory.
new_cmd = old_cmd.in_dir("/usr")
"""
new_command = copy.deepcopy(self)
new_command._directory = str(directory)
return new_command | [
"def",
"in_dir",
"(",
"self",
",",
"directory",
")",
":",
"new_command",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_command",
".",
"_directory",
"=",
"str",
"(",
"directory",
")",
"return",
"new_command"
] | Return new Command object that will be run in specified
directory.
new_cmd = old_cmd.in_dir("/usr") | [
"Return",
"new",
"Command",
"object",
"that",
"will",
"be",
"run",
"in",
"specified",
"directory",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L142-L151 | train |
crdoconnor/commandlib | commandlib/command.py | Command.with_shell | def with_shell(self):
"""
Return new Command object that will be run using shell.
"""
new_command = copy.deepcopy(self)
new_command._shell = True
return new_command | python | def with_shell(self):
"""
Return new Command object that will be run using shell.
"""
new_command = copy.deepcopy(self)
new_command._shell = True
return new_command | [
"def",
"with_shell",
"(",
"self",
")",
":",
"new_command",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_command",
".",
"_shell",
"=",
"True",
"return",
"new_command"
] | Return new Command object that will be run using shell. | [
"Return",
"new",
"Command",
"object",
"that",
"will",
"be",
"run",
"using",
"shell",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L153-L159 | train |
crdoconnor/commandlib | commandlib/command.py | Command.with_trailing_args | def with_trailing_args(self, *arguments):
"""
Return new Command object that will be run with specified
trailing arguments.
"""
new_command = copy.deepcopy(self)
new_command._trailing_args = [str(arg) for arg in arguments]
return new_command | python | def with_trailing_args(self, *arguments):
"""
Return new Command object that will be run with specified
trailing arguments.
"""
new_command = copy.deepcopy(self)
new_command._trailing_args = [str(arg) for arg in arguments]
return new_command | [
"def",
"with_trailing_args",
"(",
"self",
",",
"*",
"arguments",
")",
":",
"new_command",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_command",
".",
"_trailing_args",
"=",
"[",
"str",
"(",
"arg",
")",
"for",
"arg",
"in",
"arguments",
"]",
"return",
"new_command"
] | Return new Command object that will be run with specified
trailing arguments. | [
"Return",
"new",
"Command",
"object",
"that",
"will",
"be",
"run",
"with",
"specified",
"trailing",
"arguments",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L161-L168 | train |
crdoconnor/commandlib | commandlib/command.py | Command.with_path | def with_path(self, path):
"""
Return new Command object that will be run with a new addition
to the PATH environment variable that will be fed to the command.
"""
new_command = copy.deepcopy(self)
new_command._paths.append(str(path))
return new_command | python | def with_path(self, path):
"""
Return new Command object that will be run with a new addition
to the PATH environment variable that will be fed to the command.
"""
new_command = copy.deepcopy(self)
new_command._paths.append(str(path))
return new_command | [
"def",
"with_path",
"(",
"self",
",",
"path",
")",
":",
"new_command",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_command",
".",
"_paths",
".",
"append",
"(",
"str",
"(",
"path",
")",
")",
"return",
"new_command"
] | Return new Command object that will be run with a new addition
to the PATH environment variable that will be fed to the command. | [
"Return",
"new",
"Command",
"object",
"that",
"will",
"be",
"run",
"with",
"a",
"new",
"addition",
"to",
"the",
"PATH",
"environment",
"variable",
"that",
"will",
"be",
"fed",
"to",
"the",
"command",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L170-L177 | train |
crdoconnor/commandlib | commandlib/command.py | Command.pexpect | def pexpect(self):
"""
Run command and return pexpect process object.
NOTE: Requires you to pip install 'pexpect' or will fail.
"""
import pexpect
assert not self._ignore_errors
_check_directory(self.directory)
arguments = self.arguments
return pexpect.spawn(
arguments[0], args=arguments[1:], env=self.env, cwd=self.directory
) | python | def pexpect(self):
"""
Run command and return pexpect process object.
NOTE: Requires you to pip install 'pexpect' or will fail.
"""
import pexpect
assert not self._ignore_errors
_check_directory(self.directory)
arguments = self.arguments
return pexpect.spawn(
arguments[0], args=arguments[1:], env=self.env, cwd=self.directory
) | [
"def",
"pexpect",
"(",
"self",
")",
":",
"import",
"pexpect",
"assert",
"not",
"self",
".",
"_ignore_errors",
"_check_directory",
"(",
"self",
".",
"directory",
")",
"arguments",
"=",
"self",
".",
"arguments",
"return",
"pexpect",
".",
"spawn",
"(",
"arguments",
"[",
"0",
"]",
",",
"args",
"=",
"arguments",
"[",
"1",
":",
"]",
",",
"env",
"=",
"self",
".",
"env",
",",
"cwd",
"=",
"self",
".",
"directory",
")"
] | Run command and return pexpect process object.
NOTE: Requires you to pip install 'pexpect' or will fail. | [
"Run",
"command",
"and",
"return",
"pexpect",
"process",
"object",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L203-L219 | train |
crdoconnor/commandlib | commandlib/command.py | Command.run | def run(self):
"""Run command and wait until it finishes."""
_check_directory(self.directory)
with DirectoryContextManager(self.directory):
process = subprocess.Popen(self.arguments, shell=self._shell, env=self.env)
_, _ = process.communicate()
returncode = process.returncode
if returncode != 0 and not self._ignore_errors:
raise CommandError(
'"{0}" failed (err code {1})'.format(self.__repr__(), returncode)
) | python | def run(self):
"""Run command and wait until it finishes."""
_check_directory(self.directory)
with DirectoryContextManager(self.directory):
process = subprocess.Popen(self.arguments, shell=self._shell, env=self.env)
_, _ = process.communicate()
returncode = process.returncode
if returncode != 0 and not self._ignore_errors:
raise CommandError(
'"{0}" failed (err code {1})'.format(self.__repr__(), returncode)
) | [
"def",
"run",
"(",
"self",
")",
":",
"_check_directory",
"(",
"self",
".",
"directory",
")",
"with",
"DirectoryContextManager",
"(",
"self",
".",
"directory",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"arguments",
",",
"shell",
"=",
"self",
".",
"_shell",
",",
"env",
"=",
"self",
".",
"env",
")",
"_",
",",
"_",
"=",
"process",
".",
"communicate",
"(",
")",
"returncode",
"=",
"process",
".",
"returncode",
"if",
"returncode",
"!=",
"0",
"and",
"not",
"self",
".",
"_ignore_errors",
":",
"raise",
"CommandError",
"(",
"'\"{0}\" failed (err code {1})'",
".",
"format",
"(",
"self",
".",
"__repr__",
"(",
")",
",",
"returncode",
")",
")"
] | Run command and wait until it finishes. | [
"Run",
"command",
"and",
"wait",
"until",
"it",
"finishes",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L221-L235 | train |
aiidateam/aiida-codtools | aiida_codtools/workflows/functions/primitive_structure_from_cif.py | primitive_structure_from_cif | def primitive_structure_from_cif(cif, parse_engine, symprec, site_tolerance):
"""
This calcfunction will take a CifData node, attempt to create a StructureData object from it
using the 'parse_engine' and pass it through SeeKpath to try and get the primitive cell. Finally, it will
store several keys from the SeeKpath output parameters dictionary directly on the structure data as attributes,
which are otherwise difficult if not impossible to query for.
:param cif: the CifData node
:param parse_engine: the parsing engine, supported libraries 'ase' and 'pymatgen'
:param symprec: a Float node with symmetry precision for determining primitive cell in SeeKpath
:param site_tolerance: a Float node with the fractional coordinate distance tolerance for finding overlapping sites
This will only be used if the parse_engine is pymatgen
:returns: the primitive StructureData as determined by SeeKpath
"""
CifCleanWorkChain = WorkflowFactory('codtools.cif_clean') # pylint: disable=invalid-name
try:
structure = cif.get_structure(converter=parse_engine.value, site_tolerance=site_tolerance, store=False)
except exceptions.UnsupportedSpeciesError:
return CifCleanWorkChain.exit_codes.ERROR_CIF_HAS_UNKNOWN_SPECIES
except InvalidOccupationsError:
return CifCleanWorkChain.exit_codes.ERROR_CIF_HAS_INVALID_OCCUPANCIES
except Exception: # pylint: disable=broad-except
return CifCleanWorkChain.exit_codes.ERROR_CIF_STRUCTURE_PARSING_FAILED
try:
seekpath_results = get_kpoints_path(structure, symprec=symprec)
except ValueError:
return CifCleanWorkChain.exit_codes.ERROR_SEEKPATH_INCONSISTENT_SYMMETRY
except SymmetryDetectionError:
return CifCleanWorkChain.exit_codes.ERROR_SEEKPATH_SYMMETRY_DETECTION_FAILED
# Store important information that should be easily queryable as attributes in the StructureData
parameters = seekpath_results['parameters'].get_dict()
structure = seekpath_results['primitive_structure']
for key in ['spacegroup_international', 'spacegroup_number', 'bravais_lattice', 'bravais_lattice_extended']:
try:
value = parameters[key]
structure.set_extra(key, value)
except KeyError:
pass
# Store the formula as a string, in both hill as well as hill-compact notation, so it can be easily queried for
structure.set_extra('formula_hill', structure.get_formula(mode='hill'))
structure.set_extra('formula_hill_compact', structure.get_formula(mode='hill_compact'))
structure.set_extra('chemical_system', '-{}-'.format('-'.join(sorted(structure.get_symbols_set()))))
return structure | python | def primitive_structure_from_cif(cif, parse_engine, symprec, site_tolerance):
"""
This calcfunction will take a CifData node, attempt to create a StructureData object from it
using the 'parse_engine' and pass it through SeeKpath to try and get the primitive cell. Finally, it will
store several keys from the SeeKpath output parameters dictionary directly on the structure data as attributes,
which are otherwise difficult if not impossible to query for.
:param cif: the CifData node
:param parse_engine: the parsing engine, supported libraries 'ase' and 'pymatgen'
:param symprec: a Float node with symmetry precision for determining primitive cell in SeeKpath
:param site_tolerance: a Float node with the fractional coordinate distance tolerance for finding overlapping sites
This will only be used if the parse_engine is pymatgen
:returns: the primitive StructureData as determined by SeeKpath
"""
CifCleanWorkChain = WorkflowFactory('codtools.cif_clean') # pylint: disable=invalid-name
try:
structure = cif.get_structure(converter=parse_engine.value, site_tolerance=site_tolerance, store=False)
except exceptions.UnsupportedSpeciesError:
return CifCleanWorkChain.exit_codes.ERROR_CIF_HAS_UNKNOWN_SPECIES
except InvalidOccupationsError:
return CifCleanWorkChain.exit_codes.ERROR_CIF_HAS_INVALID_OCCUPANCIES
except Exception: # pylint: disable=broad-except
return CifCleanWorkChain.exit_codes.ERROR_CIF_STRUCTURE_PARSING_FAILED
try:
seekpath_results = get_kpoints_path(structure, symprec=symprec)
except ValueError:
return CifCleanWorkChain.exit_codes.ERROR_SEEKPATH_INCONSISTENT_SYMMETRY
except SymmetryDetectionError:
return CifCleanWorkChain.exit_codes.ERROR_SEEKPATH_SYMMETRY_DETECTION_FAILED
# Store important information that should be easily queryable as attributes in the StructureData
parameters = seekpath_results['parameters'].get_dict()
structure = seekpath_results['primitive_structure']
for key in ['spacegroup_international', 'spacegroup_number', 'bravais_lattice', 'bravais_lattice_extended']:
try:
value = parameters[key]
structure.set_extra(key, value)
except KeyError:
pass
# Store the formula as a string, in both hill as well as hill-compact notation, so it can be easily queried for
structure.set_extra('formula_hill', structure.get_formula(mode='hill'))
structure.set_extra('formula_hill_compact', structure.get_formula(mode='hill_compact'))
structure.set_extra('chemical_system', '-{}-'.format('-'.join(sorted(structure.get_symbols_set()))))
return structure | [
"def",
"primitive_structure_from_cif",
"(",
"cif",
",",
"parse_engine",
",",
"symprec",
",",
"site_tolerance",
")",
":",
"CifCleanWorkChain",
"=",
"WorkflowFactory",
"(",
"'codtools.cif_clean'",
")",
"# pylint: disable=invalid-name",
"try",
":",
"structure",
"=",
"cif",
".",
"get_structure",
"(",
"converter",
"=",
"parse_engine",
".",
"value",
",",
"site_tolerance",
"=",
"site_tolerance",
",",
"store",
"=",
"False",
")",
"except",
"exceptions",
".",
"UnsupportedSpeciesError",
":",
"return",
"CifCleanWorkChain",
".",
"exit_codes",
".",
"ERROR_CIF_HAS_UNKNOWN_SPECIES",
"except",
"InvalidOccupationsError",
":",
"return",
"CifCleanWorkChain",
".",
"exit_codes",
".",
"ERROR_CIF_HAS_INVALID_OCCUPANCIES",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"return",
"CifCleanWorkChain",
".",
"exit_codes",
".",
"ERROR_CIF_STRUCTURE_PARSING_FAILED",
"try",
":",
"seekpath_results",
"=",
"get_kpoints_path",
"(",
"structure",
",",
"symprec",
"=",
"symprec",
")",
"except",
"ValueError",
":",
"return",
"CifCleanWorkChain",
".",
"exit_codes",
".",
"ERROR_SEEKPATH_INCONSISTENT_SYMMETRY",
"except",
"SymmetryDetectionError",
":",
"return",
"CifCleanWorkChain",
".",
"exit_codes",
".",
"ERROR_SEEKPATH_SYMMETRY_DETECTION_FAILED",
"# Store important information that should be easily queryable as attributes in the StructureData",
"parameters",
"=",
"seekpath_results",
"[",
"'parameters'",
"]",
".",
"get_dict",
"(",
")",
"structure",
"=",
"seekpath_results",
"[",
"'primitive_structure'",
"]",
"for",
"key",
"in",
"[",
"'spacegroup_international'",
",",
"'spacegroup_number'",
",",
"'bravais_lattice'",
",",
"'bravais_lattice_extended'",
"]",
":",
"try",
":",
"value",
"=",
"parameters",
"[",
"key",
"]",
"structure",
".",
"set_extra",
"(",
"key",
",",
"value",
")",
"except",
"KeyError",
":",
"pass",
"# Store the formula as a string, in both hill as well as hill-compact notation, so it can be easily queried for",
"structure",
".",
"set_extra",
"(",
"'formula_hill'",
",",
"structure",
".",
"get_formula",
"(",
"mode",
"=",
"'hill'",
")",
")",
"structure",
".",
"set_extra",
"(",
"'formula_hill_compact'",
",",
"structure",
".",
"get_formula",
"(",
"mode",
"=",
"'hill_compact'",
")",
")",
"structure",
".",
"set_extra",
"(",
"'chemical_system'",
",",
"'-{}-'",
".",
"format",
"(",
"'-'",
".",
"join",
"(",
"sorted",
"(",
"structure",
".",
"get_symbols_set",
"(",
")",
")",
")",
")",
")",
"return",
"structure"
] | This calcfunction will take a CifData node, attempt to create a StructureData object from it
using the 'parse_engine' and pass it through SeeKpath to try and get the primitive cell. Finally, it will
store several keys from the SeeKpath output parameters dictionary directly on the structure data as attributes,
which are otherwise difficult if not impossible to query for.
:param cif: the CifData node
:param parse_engine: the parsing engine, supported libraries 'ase' and 'pymatgen'
:param symprec: a Float node with symmetry precision for determining primitive cell in SeeKpath
:param site_tolerance: a Float node with the fractional coordinate distance tolerance for finding overlapping sites
This will only be used if the parse_engine is pymatgen
:returns: the primitive StructureData as determined by SeeKpath | [
"This",
"calcfunction",
"will",
"take",
"a",
"CifData",
"node",
"attempt",
"to",
"create",
"a",
"StructureData",
"object",
"from",
"it",
"using",
"the",
"parse_engine",
"and",
"pass",
"it",
"through",
"SeeKpath",
"to",
"try",
"and",
"get",
"the",
"primitive",
"cell",
".",
"Finally",
"it",
"will",
"store",
"several",
"keys",
"from",
"the",
"SeeKpath",
"output",
"parameters",
"dictionary",
"directly",
"on",
"the",
"structure",
"data",
"as",
"attributes",
"which",
"are",
"otherwise",
"difficult",
"if",
"not",
"impossible",
"to",
"query",
"for",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/functions/primitive_structure_from_cif.py#L14-L62 | train |
Capitains/MyCapytain | MyCapytain/common/base.py | Exportable.export_capacities | def export_capacities(self):
""" List Mimetypes that current object can export to
"""
return [export for cls in getmro(type(self)) if hasattr(cls, "EXPORT_TO") for export in cls.EXPORT_TO] | python | def export_capacities(self):
""" List Mimetypes that current object can export to
"""
return [export for cls in getmro(type(self)) if hasattr(cls, "EXPORT_TO") for export in cls.EXPORT_TO] | [
"def",
"export_capacities",
"(",
"self",
")",
":",
"return",
"[",
"export",
"for",
"cls",
"in",
"getmro",
"(",
"type",
"(",
"self",
")",
")",
"if",
"hasattr",
"(",
"cls",
",",
"\"EXPORT_TO\"",
")",
"for",
"export",
"in",
"cls",
".",
"EXPORT_TO",
"]"
] | List Mimetypes that current object can export to | [
"List",
"Mimetypes",
"that",
"current",
"object",
"can",
"export",
"to"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/base.py#L21-L24 | train |
exosite-labs/pyonep | pyonep/provision.py | Provision._filter_options | def _filter_options(self, aliases=True, comments=True, historical=True):
"""Converts a set of boolean-valued options into the relevant HTTP values."""
options = []
if not aliases:
options.append('noaliases')
if not comments:
options.append('nocomments')
if not historical:
options.append('nohistorical')
return options | python | def _filter_options(self, aliases=True, comments=True, historical=True):
"""Converts a set of boolean-valued options into the relevant HTTP values."""
options = []
if not aliases:
options.append('noaliases')
if not comments:
options.append('nocomments')
if not historical:
options.append('nohistorical')
return options | [
"def",
"_filter_options",
"(",
"self",
",",
"aliases",
"=",
"True",
",",
"comments",
"=",
"True",
",",
"historical",
"=",
"True",
")",
":",
"options",
"=",
"[",
"]",
"if",
"not",
"aliases",
":",
"options",
".",
"append",
"(",
"'noaliases'",
")",
"if",
"not",
"comments",
":",
"options",
".",
"append",
"(",
"'nocomments'",
")",
"if",
"not",
"historical",
":",
"options",
".",
"append",
"(",
"'nohistorical'",
")",
"return",
"options"
] | Converts a set of boolean-valued options into the relevant HTTP values. | [
"Converts",
"a",
"set",
"of",
"boolean",
"-",
"valued",
"options",
"into",
"the",
"relevant",
"HTTP",
"values",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L109-L118 | train |
exosite-labs/pyonep | pyonep/provision.py | Provision._request | def _request(self, path, key, data, method, key_is_cik, extra_headers={}):
"""Generically shared HTTP request method.
Args:
path: The API endpoint to interact with.
key: A string for the key used by the device for the API. Either a CIK or token.
data: A string for the pre-encoded data to be sent with this request.
method: A string denoting the HTTP verb to use for the request (e.g. 'GET', 'POST')
key_is_cik: Whether or not the device key used is a CIK or token.
extra_headers: A dictionary of extra headers to include with the request.
Returns:
A ProvisionResponse containing the result of the HTTP request.
"""
if method == 'GET':
if len(data) > 0:
url = path + '?' + data
else:
url = path
body = None
else:
url = path
body = data
headers = {}
if key_is_cik:
headers['X-Exosite-CIK'] = key
else:
headers['X-Exosite-Token'] = key
if method == 'POST':
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
headers['Accept'] = 'text/plain, text/csv, application/x-www-form-urlencoded'
headers.update(extra_headers)
body, response = self._onephttp.request(method,
url,
body,
headers)
pr = ProvisionResponse(body, response)
if self._raise_api_exceptions and not pr.isok:
raise ProvisionException(pr)
return pr | python | def _request(self, path, key, data, method, key_is_cik, extra_headers={}):
"""Generically shared HTTP request method.
Args:
path: The API endpoint to interact with.
key: A string for the key used by the device for the API. Either a CIK or token.
data: A string for the pre-encoded data to be sent with this request.
method: A string denoting the HTTP verb to use for the request (e.g. 'GET', 'POST')
key_is_cik: Whether or not the device key used is a CIK or token.
extra_headers: A dictionary of extra headers to include with the request.
Returns:
A ProvisionResponse containing the result of the HTTP request.
"""
if method == 'GET':
if len(data) > 0:
url = path + '?' + data
else:
url = path
body = None
else:
url = path
body = data
headers = {}
if key_is_cik:
headers['X-Exosite-CIK'] = key
else:
headers['X-Exosite-Token'] = key
if method == 'POST':
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
headers['Accept'] = 'text/plain, text/csv, application/x-www-form-urlencoded'
headers.update(extra_headers)
body, response = self._onephttp.request(method,
url,
body,
headers)
pr = ProvisionResponse(body, response)
if self._raise_api_exceptions and not pr.isok:
raise ProvisionException(pr)
return pr | [
"def",
"_request",
"(",
"self",
",",
"path",
",",
"key",
",",
"data",
",",
"method",
",",
"key_is_cik",
",",
"extra_headers",
"=",
"{",
"}",
")",
":",
"if",
"method",
"==",
"'GET'",
":",
"if",
"len",
"(",
"data",
")",
">",
"0",
":",
"url",
"=",
"path",
"+",
"'?'",
"+",
"data",
"else",
":",
"url",
"=",
"path",
"body",
"=",
"None",
"else",
":",
"url",
"=",
"path",
"body",
"=",
"data",
"headers",
"=",
"{",
"}",
"if",
"key_is_cik",
":",
"headers",
"[",
"'X-Exosite-CIK'",
"]",
"=",
"key",
"else",
":",
"headers",
"[",
"'X-Exosite-Token'",
"]",
"=",
"key",
"if",
"method",
"==",
"'POST'",
":",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded; charset=utf-8'",
"headers",
"[",
"'Accept'",
"]",
"=",
"'text/plain, text/csv, application/x-www-form-urlencoded'",
"headers",
".",
"update",
"(",
"extra_headers",
")",
"body",
",",
"response",
"=",
"self",
".",
"_onephttp",
".",
"request",
"(",
"method",
",",
"url",
",",
"body",
",",
"headers",
")",
"pr",
"=",
"ProvisionResponse",
"(",
"body",
",",
"response",
")",
"if",
"self",
".",
"_raise_api_exceptions",
"and",
"not",
"pr",
".",
"isok",
":",
"raise",
"ProvisionException",
"(",
"pr",
")",
"return",
"pr"
] | Generically shared HTTP request method.
Args:
path: The API endpoint to interact with.
key: A string for the key used by the device for the API. Either a CIK or token.
data: A string for the pre-encoded data to be sent with this request.
method: A string denoting the HTTP verb to use for the request (e.g. 'GET', 'POST')
key_is_cik: Whether or not the device key used is a CIK or token.
extra_headers: A dictionary of extra headers to include with the request.
Returns:
A ProvisionResponse containing the result of the HTTP request. | [
"Generically",
"shared",
"HTTP",
"request",
"method",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L120-L162 | train |
exosite-labs/pyonep | pyonep/provision.py | Provision.content_create | def content_create(self, key, model, contentid, meta, protected=False):
"""Creates a content entity bucket with the given `contentid`.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bucket
meta:
protected: Whether or not this is restricted to certain device serial numbers only.
"""
params = {'id': contentid, 'meta': meta}
if protected is not False:
params['protected'] = 'true'
data = urlencode(params)
path = PROVISION_MANAGE_CONTENT + model + '/'
return self._request(path,
key, data, 'POST', self._manage_by_cik) | python | def content_create(self, key, model, contentid, meta, protected=False):
"""Creates a content entity bucket with the given `contentid`.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bucket
meta:
protected: Whether or not this is restricted to certain device serial numbers only.
"""
params = {'id': contentid, 'meta': meta}
if protected is not False:
params['protected'] = 'true'
data = urlencode(params)
path = PROVISION_MANAGE_CONTENT + model + '/'
return self._request(path,
key, data, 'POST', self._manage_by_cik) | [
"def",
"content_create",
"(",
"self",
",",
"key",
",",
"model",
",",
"contentid",
",",
"meta",
",",
"protected",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'id'",
":",
"contentid",
",",
"'meta'",
":",
"meta",
"}",
"if",
"protected",
"is",
"not",
"False",
":",
"params",
"[",
"'protected'",
"]",
"=",
"'true'",
"data",
"=",
"urlencode",
"(",
"params",
")",
"path",
"=",
"PROVISION_MANAGE_CONTENT",
"+",
"model",
"+",
"'/'",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"key",
",",
"data",
",",
"'POST'",
",",
"self",
".",
"_manage_by_cik",
")"
] | Creates a content entity bucket with the given `contentid`.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bucket
meta:
protected: Whether or not this is restricted to certain device serial numbers only. | [
"Creates",
"a",
"content",
"entity",
"bucket",
"with",
"the",
"given",
"contentid",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L172-L191 | train |
exosite-labs/pyonep | pyonep/provision.py | Provision.content_list | def content_list(self, key, model):
"""Returns the list of content IDs for a given model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#get---list-content-ids
Args:
key: The CIK or Token for the device
model:
"""
path = PROVISION_MANAGE_CONTENT + model + '/'
return self._request(path, key, '', 'GET', self._manage_by_cik) | python | def content_list(self, key, model):
"""Returns the list of content IDs for a given model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#get---list-content-ids
Args:
key: The CIK or Token for the device
model:
"""
path = PROVISION_MANAGE_CONTENT + model + '/'
return self._request(path, key, '', 'GET', self._manage_by_cik) | [
"def",
"content_list",
"(",
"self",
",",
"key",
",",
"model",
")",
":",
"path",
"=",
"PROVISION_MANAGE_CONTENT",
"+",
"model",
"+",
"'/'",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"key",
",",
"''",
",",
"'GET'",
",",
"self",
".",
"_manage_by_cik",
")"
] | Returns the list of content IDs for a given model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#get---list-content-ids
Args:
key: The CIK or Token for the device
model: | [
"Returns",
"the",
"list",
"of",
"content",
"IDs",
"for",
"a",
"given",
"model",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L237-L248 | train |
exosite-labs/pyonep | pyonep/provision.py | Provision.content_remove | def content_remove(self, key, model, contentid):
"""Deletes the information for the given contentid under the given model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#delete---delete-content
Args:
key: The CIK or Token for the device
model:
"""
path = PROVISION_MANAGE_CONTENT + model + '/' + contentid
return self._request(path, key, '', 'DELETE', self._manage_by_cik) | python | def content_remove(self, key, model, contentid):
"""Deletes the information for the given contentid under the given model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#delete---delete-content
Args:
key: The CIK or Token for the device
model:
"""
path = PROVISION_MANAGE_CONTENT + model + '/' + contentid
return self._request(path, key, '', 'DELETE', self._manage_by_cik) | [
"def",
"content_remove",
"(",
"self",
",",
"key",
",",
"model",
",",
"contentid",
")",
":",
"path",
"=",
"PROVISION_MANAGE_CONTENT",
"+",
"model",
"+",
"'/'",
"+",
"contentid",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"key",
",",
"''",
",",
"'DELETE'",
",",
"self",
".",
"_manage_by_cik",
")"
] | Deletes the information for the given contentid under the given model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#delete---delete-content
Args:
key: The CIK or Token for the device
model: | [
"Deletes",
"the",
"information",
"for",
"the",
"given",
"contentid",
"under",
"the",
"given",
"model",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L250-L261 | train |
exosite-labs/pyonep | pyonep/provision.py | Provision.content_upload | def content_upload(self, key, model, contentid, data, mimetype):
"""Store the given data as a result of a query for content id given the model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---upload-content
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bucket
data: The data blob to save
mimetype: The Content-Type to use when serving the blob later
"""
headers = {"Content-Type": mimetype}
path = PROVISION_MANAGE_CONTENT + model + '/' + contentid
return self._request(path, key, data, 'POST', self._manage_by_cik, headers) | python | def content_upload(self, key, model, contentid, data, mimetype):
"""Store the given data as a result of a query for content id given the model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---upload-content
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bucket
data: The data blob to save
mimetype: The Content-Type to use when serving the blob later
"""
headers = {"Content-Type": mimetype}
path = PROVISION_MANAGE_CONTENT + model + '/' + contentid
return self._request(path, key, data, 'POST', self._manage_by_cik, headers) | [
"def",
"content_upload",
"(",
"self",
",",
"key",
",",
"model",
",",
"contentid",
",",
"data",
",",
"mimetype",
")",
":",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"mimetype",
"}",
"path",
"=",
"PROVISION_MANAGE_CONTENT",
"+",
"model",
"+",
"'/'",
"+",
"contentid",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"key",
",",
"data",
",",
"'POST'",
",",
"self",
".",
"_manage_by_cik",
",",
"headers",
")"
] | Store the given data as a result of a query for content id given the model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---upload-content
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bucket
data: The data blob to save
mimetype: The Content-Type to use when serving the blob later | [
"Store",
"the",
"given",
"data",
"as",
"a",
"result",
"of",
"a",
"query",
"for",
"content",
"id",
"given",
"the",
"model",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L263-L278 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | url_should_be | def url_should_be(self, url):
"""Assert the absolute URL of the browser is as provided."""
if world.browser.current_url != url:
raise AssertionError(
"Browser URL expected to be {!r}, got {!r}.".format(
url, world.browser.current_url)) | python | def url_should_be(self, url):
"""Assert the absolute URL of the browser is as provided."""
if world.browser.current_url != url:
raise AssertionError(
"Browser URL expected to be {!r}, got {!r}.".format(
url, world.browser.current_url)) | [
"def",
"url_should_be",
"(",
"self",
",",
"url",
")",
":",
"if",
"world",
".",
"browser",
".",
"current_url",
"!=",
"url",
":",
"raise",
"AssertionError",
"(",
"\"Browser URL expected to be {!r}, got {!r}.\"",
".",
"format",
"(",
"url",
",",
"world",
".",
"browser",
".",
"current_url",
")",
")"
] | Assert the absolute URL of the browser is as provided. | [
"Assert",
"the",
"absolute",
"URL",
"of",
"the",
"browser",
"is",
"as",
"provided",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L75-L81 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | url_should_contain | def url_should_contain(self, url):
"""Assert the absolute URL of the browser contains the provided."""
if url not in world.browser.current_url:
raise AssertionError(
"Browser URL expected to contain {!r}, got {!r}.".format(
url, world.browser.current_url)) | python | def url_should_contain(self, url):
"""Assert the absolute URL of the browser contains the provided."""
if url not in world.browser.current_url:
raise AssertionError(
"Browser URL expected to contain {!r}, got {!r}.".format(
url, world.browser.current_url)) | [
"def",
"url_should_contain",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
"not",
"in",
"world",
".",
"browser",
".",
"current_url",
":",
"raise",
"AssertionError",
"(",
"\"Browser URL expected to contain {!r}, got {!r}.\"",
".",
"format",
"(",
"url",
",",
"world",
".",
"browser",
".",
"current_url",
")",
")"
] | Assert the absolute URL of the browser contains the provided. | [
"Assert",
"the",
"absolute",
"URL",
"of",
"the",
"browser",
"contains",
"the",
"provided",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L86-L92 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | url_should_not_contain | def url_should_not_contain(self, url):
"""Assert the absolute URL of the browser does not contain the provided."""
if url in world.browser.current_url:
raise AssertionError(
"Browser URL expected not to contain {!r}, got {!r}.".format(
url, world.browser.current_url)) | python | def url_should_not_contain(self, url):
"""Assert the absolute URL of the browser does not contain the provided."""
if url in world.browser.current_url:
raise AssertionError(
"Browser URL expected not to contain {!r}, got {!r}.".format(
url, world.browser.current_url)) | [
"def",
"url_should_not_contain",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
"in",
"world",
".",
"browser",
".",
"current_url",
":",
"raise",
"AssertionError",
"(",
"\"Browser URL expected not to contain {!r}, got {!r}.\"",
".",
"format",
"(",
"url",
",",
"world",
".",
"browser",
".",
"current_url",
")",
")"
] | Assert the absolute URL of the browser does not contain the provided. | [
"Assert",
"the",
"absolute",
"URL",
"of",
"the",
"browser",
"does",
"not",
"contain",
"the",
"provided",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L97-L103 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | page_title | def page_title(self, title):
"""
Assert the page title matches the given text.
"""
if world.browser.title != title:
raise AssertionError(
"Page title expected to be {!r}, got {!r}.".format(
title, world.browser.title)) | python | def page_title(self, title):
"""
Assert the page title matches the given text.
"""
if world.browser.title != title:
raise AssertionError(
"Page title expected to be {!r}, got {!r}.".format(
title, world.browser.title)) | [
"def",
"page_title",
"(",
"self",
",",
"title",
")",
":",
"if",
"world",
".",
"browser",
".",
"title",
"!=",
"title",
":",
"raise",
"AssertionError",
"(",
"\"Page title expected to be {!r}, got {!r}.\"",
".",
"format",
"(",
"title",
",",
"world",
".",
"browser",
".",
"title",
")",
")"
] | Assert the page title matches the given text. | [
"Assert",
"the",
"page",
"title",
"matches",
"the",
"given",
"text",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L109-L117 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | click | def click(self, name):
"""Click the link with the provided link text."""
try:
elem = world.browser.find_element_by_link_text(name)
except NoSuchElementException:
raise AssertionError(
"Cannot find the link with text '{}'.".format(name))
elem.click() | python | def click(self, name):
"""Click the link with the provided link text."""
try:
elem = world.browser.find_element_by_link_text(name)
except NoSuchElementException:
raise AssertionError(
"Cannot find the link with text '{}'.".format(name))
elem.click() | [
"def",
"click",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"elem",
"=",
"world",
".",
"browser",
".",
"find_element_by_link_text",
"(",
"name",
")",
"except",
"NoSuchElementException",
":",
"raise",
"AssertionError",
"(",
"\"Cannot find the link with text '{}'.\"",
".",
"format",
"(",
"name",
")",
")",
"elem",
".",
"click",
"(",
")"
] | Click the link with the provided link text. | [
"Click",
"the",
"link",
"with",
"the",
"provided",
"link",
"text",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L125-L132 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | should_see_link | def should_see_link(self, link_url):
"""Assert a link with the provided URL is visible on the page."""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"]' % link_url),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected link not found.") | python | def should_see_link(self, link_url):
"""Assert a link with the provided URL is visible on the page."""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"]' % link_url),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected link not found.") | [
"def",
"should_see_link",
"(",
"self",
",",
"link_url",
")",
":",
"elements",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'//a[@href=\"%s\"]'",
"%",
"link_url",
")",
",",
"filter_displayed",
"=",
"True",
",",
")",
"if",
"not",
"elements",
":",
"raise",
"AssertionError",
"(",
"\"Expected link not found.\"",
")"
] | Assert a link with the provided URL is visible on the page. | [
"Assert",
"a",
"link",
"with",
"the",
"provided",
"URL",
"is",
"visible",
"on",
"the",
"page",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L137-L146 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | should_see_link_text | def should_see_link_text(self, link_text, link_url):
"""Assert a link with the provided text points to the provided URL."""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"][./text()="%s"]' % (link_url, link_text)),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected link not found.") | python | def should_see_link_text(self, link_text, link_url):
"""Assert a link with the provided text points to the provided URL."""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"][./text()="%s"]' % (link_url, link_text)),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected link not found.") | [
"def",
"should_see_link_text",
"(",
"self",
",",
"link_text",
",",
"link_url",
")",
":",
"elements",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'//a[@href=\"%s\"][./text()=\"%s\"]'",
"%",
"(",
"link_url",
",",
"link_text",
")",
")",
",",
"filter_displayed",
"=",
"True",
",",
")",
"if",
"not",
"elements",
":",
"raise",
"AssertionError",
"(",
"\"Expected link not found.\"",
")"
] | Assert a link with the provided text points to the provided URL. | [
"Assert",
"a",
"link",
"with",
"the",
"provided",
"text",
"points",
"to",
"the",
"provided",
"URL",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L152-L161 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | should_include_link_text | def should_include_link_text(self, link_text, link_url):
"""
Assert a link containing the provided text points to the provided URL.
"""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"][contains(., %s)]' %
(link_url, string_literal(link_text))),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected link not found.") | python | def should_include_link_text(self, link_text, link_url):
"""
Assert a link containing the provided text points to the provided URL.
"""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"][contains(., %s)]' %
(link_url, string_literal(link_text))),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected link not found.") | [
"def",
"should_include_link_text",
"(",
"self",
",",
"link_text",
",",
"link_url",
")",
":",
"elements",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'//a[@href=\"%s\"][contains(., %s)]'",
"%",
"(",
"link_url",
",",
"string_literal",
"(",
"link_text",
")",
")",
")",
",",
"filter_displayed",
"=",
"True",
",",
")",
"if",
"not",
"elements",
":",
"raise",
"AssertionError",
"(",
"\"Expected link not found.\"",
")"
] | Assert a link containing the provided text points to the provided URL. | [
"Assert",
"a",
"link",
"containing",
"the",
"provided",
"text",
"points",
"to",
"the",
"provided",
"URL",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L169-L181 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | element_contains | def element_contains(self, element_id, value):
"""
Assert provided content is contained within an element found by ``id``.
"""
elements = ElementSelector(
world.browser,
str('id("{id}")[contains(., "{value}")]'.format(
id=element_id, value=value)),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected element not found.") | python | def element_contains(self, element_id, value):
"""
Assert provided content is contained within an element found by ``id``.
"""
elements = ElementSelector(
world.browser,
str('id("{id}")[contains(., "{value}")]'.format(
id=element_id, value=value)),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected element not found.") | [
"def",
"element_contains",
"(",
"self",
",",
"element_id",
",",
"value",
")",
":",
"elements",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'id(\"{id}\")[contains(., \"{value}\")]'",
".",
"format",
"(",
"id",
"=",
"element_id",
",",
"value",
"=",
"value",
")",
")",
",",
"filter_displayed",
"=",
"True",
",",
")",
"if",
"not",
"elements",
":",
"raise",
"AssertionError",
"(",
"\"Expected element not found.\"",
")"
] | Assert provided content is contained within an element found by ``id``. | [
"Assert",
"provided",
"content",
"is",
"contained",
"within",
"an",
"element",
"found",
"by",
"id",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L190-L202 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | element_not_contains | def element_not_contains(self, element_id, value):
"""
Assert provided content is not contained within an element found by ``id``.
"""
elem = world.browser.find_elements_by_xpath(str(
'id("{id}")[contains(., "{value}")]'.format(
id=element_id, value=value)))
assert not elem, \
"Expected element not to contain the given text." | python | def element_not_contains(self, element_id, value):
"""
Assert provided content is not contained within an element found by ``id``.
"""
elem = world.browser.find_elements_by_xpath(str(
'id("{id}")[contains(., "{value}")]'.format(
id=element_id, value=value)))
assert not elem, \
"Expected element not to contain the given text." | [
"def",
"element_not_contains",
"(",
"self",
",",
"element_id",
",",
"value",
")",
":",
"elem",
"=",
"world",
".",
"browser",
".",
"find_elements_by_xpath",
"(",
"str",
"(",
"'id(\"{id}\")[contains(., \"{value}\")]'",
".",
"format",
"(",
"id",
"=",
"element_id",
",",
"value",
"=",
"value",
")",
")",
")",
"assert",
"not",
"elem",
",",
"\"Expected element not to contain the given text.\""
] | Assert provided content is not contained within an element found by ``id``. | [
"Assert",
"provided",
"content",
"is",
"not",
"contained",
"within",
"an",
"element",
"found",
"by",
"id",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L208-L216 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | should_see_id_in_seconds | def should_see_id_in_seconds(self, element_id, timeout):
"""
Assert an element with the given ``id`` is visible within n seconds.
"""
def check_element():
"""Check for the element with the given id."""
assert ElementSelector(
world.browser,
'id("%s")' % element_id,
filter_displayed=True,
), "Expected element with given id."
wait_for(check_element)(timeout=int(timeout)) | python | def should_see_id_in_seconds(self, element_id, timeout):
"""
Assert an element with the given ``id`` is visible within n seconds.
"""
def check_element():
"""Check for the element with the given id."""
assert ElementSelector(
world.browser,
'id("%s")' % element_id,
filter_displayed=True,
), "Expected element with given id."
wait_for(check_element)(timeout=int(timeout)) | [
"def",
"should_see_id_in_seconds",
"(",
"self",
",",
"element_id",
",",
"timeout",
")",
":",
"def",
"check_element",
"(",
")",
":",
"\"\"\"Check for the element with the given id.\"\"\"",
"assert",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"'id(\"%s\")'",
"%",
"element_id",
",",
"filter_displayed",
"=",
"True",
",",
")",
",",
"\"Expected element with given id.\"",
"wait_for",
"(",
"check_element",
")",
"(",
"timeout",
"=",
"int",
"(",
"timeout",
")",
")"
] | Assert an element with the given ``id`` is visible within n seconds. | [
"Assert",
"an",
"element",
"with",
"the",
"given",
"id",
"is",
"visible",
"within",
"n",
"seconds",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L220-L234 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | should_see_id | def should_see_id(self, element_id):
"""
Assert an element with the given ``id`` is visible.
"""
elements = ElementSelector(
world.browser,
'id("%s")' % element_id,
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected element with given id.") | python | def should_see_id(self, element_id):
"""
Assert an element with the given ``id`` is visible.
"""
elements = ElementSelector(
world.browser,
'id("%s")' % element_id,
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected element with given id.") | [
"def",
"should_see_id",
"(",
"self",
",",
"element_id",
")",
":",
"elements",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"'id(\"%s\")'",
"%",
"element_id",
",",
"filter_displayed",
"=",
"True",
",",
")",
"if",
"not",
"elements",
":",
"raise",
"AssertionError",
"(",
"\"Expected element with given id.\"",
")"
] | Assert an element with the given ``id`` is visible. | [
"Assert",
"an",
"element",
"with",
"the",
"given",
"id",
"is",
"visible",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L239-L250 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | element_focused | def element_focused(self, id_):
"""
Assert the element is focused.
"""
try:
elem = world.browser.find_element_by_id(id_)
except NoSuchElementException:
raise AssertionError("Element with ID '{}' not found.".format(id_))
focused = world.browser.switch_to.active_element
# Elements don't have __ne__ defined, cannot test for inequality
if not elem == focused:
raise AssertionError("Expected element to be focused.") | python | def element_focused(self, id_):
"""
Assert the element is focused.
"""
try:
elem = world.browser.find_element_by_id(id_)
except NoSuchElementException:
raise AssertionError("Element with ID '{}' not found.".format(id_))
focused = world.browser.switch_to.active_element
# Elements don't have __ne__ defined, cannot test for inequality
if not elem == focused:
raise AssertionError("Expected element to be focused.") | [
"def",
"element_focused",
"(",
"self",
",",
"id_",
")",
":",
"try",
":",
"elem",
"=",
"world",
".",
"browser",
".",
"find_element_by_id",
"(",
"id_",
")",
"except",
"NoSuchElementException",
":",
"raise",
"AssertionError",
"(",
"\"Element with ID '{}' not found.\"",
".",
"format",
"(",
"id_",
")",
")",
"focused",
"=",
"world",
".",
"browser",
".",
"switch_to",
".",
"active_element",
"# Elements don't have __ne__ defined, cannot test for inequality",
"if",
"not",
"elem",
"==",
"focused",
":",
"raise",
"AssertionError",
"(",
"\"Expected element to be focused.\"",
")"
] | Assert the element is focused. | [
"Assert",
"the",
"element",
"is",
"focused",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L271-L285 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | should_see_in_seconds | def should_see_in_seconds(self, text, timeout):
"""
Assert provided text is visible within n seconds.
Be aware this text could be anywhere on the screen. Also be aware that
it might cross several HTML nodes. No determination is made between
block and inline nodes. Whitespace can be affected.
"""
def check_element():
"""Check for an element with the given content."""
assert contains_content(world.browser, text), \
"Expected element with the given text."
wait_for(check_element)(timeout=int(timeout)) | python | def should_see_in_seconds(self, text, timeout):
"""
Assert provided text is visible within n seconds.
Be aware this text could be anywhere on the screen. Also be aware that
it might cross several HTML nodes. No determination is made between
block and inline nodes. Whitespace can be affected.
"""
def check_element():
"""Check for an element with the given content."""
assert contains_content(world.browser, text), \
"Expected element with the given text."
wait_for(check_element)(timeout=int(timeout)) | [
"def",
"should_see_in_seconds",
"(",
"self",
",",
"text",
",",
"timeout",
")",
":",
"def",
"check_element",
"(",
")",
":",
"\"\"\"Check for an element with the given content.\"\"\"",
"assert",
"contains_content",
"(",
"world",
".",
"browser",
",",
"text",
")",
",",
"\"Expected element with the given text.\"",
"wait_for",
"(",
"check_element",
")",
"(",
"timeout",
"=",
"int",
"(",
"timeout",
")",
")"
] | Assert provided text is visible within n seconds.
Be aware this text could be anywhere on the screen. Also be aware that
it might cross several HTML nodes. No determination is made between
block and inline nodes. Whitespace can be affected. | [
"Assert",
"provided",
"text",
"is",
"visible",
"within",
"n",
"seconds",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L312-L327 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | see_form | def see_form(self, url):
"""
Assert the existence of a HTML form that submits to the given URL.
"""
elements = ElementSelector(
world.browser,
str('//form[@action="%s"]' % url),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected form not found.") | python | def see_form(self, url):
"""
Assert the existence of a HTML form that submits to the given URL.
"""
elements = ElementSelector(
world.browser,
str('//form[@action="%s"]' % url),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected form not found.") | [
"def",
"see_form",
"(",
"self",
",",
"url",
")",
":",
"elements",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'//form[@action=\"%s\"]'",
"%",
"url",
")",
",",
"filter_displayed",
"=",
"True",
",",
")",
"if",
"not",
"elements",
":",
"raise",
"AssertionError",
"(",
"\"Expected form not found.\"",
")"
] | Assert the existence of a HTML form that submits to the given URL. | [
"Assert",
"the",
"existence",
"of",
"a",
"HTML",
"form",
"that",
"submits",
"to",
"the",
"given",
"URL",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L366-L377 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | press_button | def press_button(self, value):
"""
Click the button with the given label.
"""
button = find_button(world.browser, value)
if not button:
raise AssertionError(
"Cannot find a button named '{}'.".format(value))
button.click() | python | def press_button(self, value):
"""
Click the button with the given label.
"""
button = find_button(world.browser, value)
if not button:
raise AssertionError(
"Cannot find a button named '{}'.".format(value))
button.click() | [
"def",
"press_button",
"(",
"self",
",",
"value",
")",
":",
"button",
"=",
"find_button",
"(",
"world",
".",
"browser",
",",
"value",
")",
"if",
"not",
"button",
":",
"raise",
"AssertionError",
"(",
"\"Cannot find a button named '{}'.\"",
".",
"format",
"(",
"value",
")",
")",
"button",
".",
"click",
"(",
")"
] | Click the button with the given label. | [
"Click",
"the",
"button",
"with",
"the",
"given",
"label",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L440-L448 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | click_on_label | def click_on_label(self, label):
"""
Click on the given label.
On a correctly set up form this will highlight the appropriate field.
"""
elem = ElementSelector(
world.browser,
str('//label[normalize-space(text())=%s]' % string_literal(label)),
filter_displayed=True,
)
if not elem:
raise AssertionError(
"Cannot find a label with text '{}'.".format(label))
elem.click() | python | def click_on_label(self, label):
"""
Click on the given label.
On a correctly set up form this will highlight the appropriate field.
"""
elem = ElementSelector(
world.browser,
str('//label[normalize-space(text())=%s]' % string_literal(label)),
filter_displayed=True,
)
if not elem:
raise AssertionError(
"Cannot find a label with text '{}'.".format(label))
elem.click() | [
"def",
"click_on_label",
"(",
"self",
",",
"label",
")",
":",
"elem",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'//label[normalize-space(text())=%s]'",
"%",
"string_literal",
"(",
"label",
")",
")",
",",
"filter_displayed",
"=",
"True",
",",
")",
"if",
"not",
"elem",
":",
"raise",
"AssertionError",
"(",
"\"Cannot find a label with text '{}'.\"",
".",
"format",
"(",
"label",
")",
")",
"elem",
".",
"click",
"(",
")"
] | Click on the given label.
On a correctly set up form this will highlight the appropriate field. | [
"Click",
"on",
"the",
"given",
"label",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L454-L469 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | submit_the_only_form | def submit_the_only_form(self):
"""
Look for a form on the page and submit it.
Asserts if more than one form exists.
"""
form = ElementSelector(world.browser, str('//form'))
assert form, "Cannot find a form on the page."
form.submit() | python | def submit_the_only_form(self):
"""
Look for a form on the page and submit it.
Asserts if more than one form exists.
"""
form = ElementSelector(world.browser, str('//form'))
assert form, "Cannot find a form on the page."
form.submit() | [
"def",
"submit_the_only_form",
"(",
"self",
")",
":",
"form",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'//form'",
")",
")",
"assert",
"form",
",",
"\"Cannot find a form on the page.\"",
"form",
".",
"submit",
"(",
")"
] | Look for a form on the page and submit it.
Asserts if more than one form exists. | [
"Look",
"for",
"a",
"form",
"on",
"the",
"page",
"and",
"submit",
"it",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L495-L503 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | check_alert | def check_alert(self, text):
"""
Assert an alert is showing with the given text.
"""
try:
alert = Alert(world.browser)
if alert.text != text:
raise AssertionError(
"Alert text expected to be {!r}, got {!r}.".format(
text, alert.text))
except WebDriverException:
# PhantomJS is kinda poor
pass | python | def check_alert(self, text):
"""
Assert an alert is showing with the given text.
"""
try:
alert = Alert(world.browser)
if alert.text != text:
raise AssertionError(
"Alert text expected to be {!r}, got {!r}.".format(
text, alert.text))
except WebDriverException:
# PhantomJS is kinda poor
pass | [
"def",
"check_alert",
"(",
"self",
",",
"text",
")",
":",
"try",
":",
"alert",
"=",
"Alert",
"(",
"world",
".",
"browser",
")",
"if",
"alert",
".",
"text",
"!=",
"text",
":",
"raise",
"AssertionError",
"(",
"\"Alert text expected to be {!r}, got {!r}.\"",
".",
"format",
"(",
"text",
",",
"alert",
".",
"text",
")",
")",
"except",
"WebDriverException",
":",
"# PhantomJS is kinda poor",
"pass"
] | Assert an alert is showing with the given text. | [
"Assert",
"an",
"alert",
"is",
"showing",
"with",
"the",
"given",
"text",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L762-L775 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | check_no_alert | def check_no_alert(self):
"""
Assert there is no alert.
"""
try:
alert = Alert(world.browser)
raise AssertionError("Should not see an alert. Alert '%s' shown." %
alert.text)
except NoAlertPresentException:
pass | python | def check_no_alert(self):
"""
Assert there is no alert.
"""
try:
alert = Alert(world.browser)
raise AssertionError("Should not see an alert. Alert '%s' shown." %
alert.text)
except NoAlertPresentException:
pass | [
"def",
"check_no_alert",
"(",
"self",
")",
":",
"try",
":",
"alert",
"=",
"Alert",
"(",
"world",
".",
"browser",
")",
"raise",
"AssertionError",
"(",
"\"Should not see an alert. Alert '%s' shown.\"",
"%",
"alert",
".",
"text",
")",
"except",
"NoAlertPresentException",
":",
"pass"
] | Assert there is no alert. | [
"Assert",
"there",
"is",
"no",
"alert",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L779-L789 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | find_by_tooltip | def find_by_tooltip(browser, tooltip):
"""
Find elements with the given tooltip.
:param browser: ``world.browser``
:param tooltip: Tooltip to search for
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
world.browser,
str('//*[@title=%(tooltip)s or @data-original-title=%(tooltip)s]' %
dict(tooltip=string_literal(tooltip))),
filter_displayed=True,
) | python | def find_by_tooltip(browser, tooltip):
"""
Find elements with the given tooltip.
:param browser: ``world.browser``
:param tooltip: Tooltip to search for
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
world.browser,
str('//*[@title=%(tooltip)s or @data-original-title=%(tooltip)s]' %
dict(tooltip=string_literal(tooltip))),
filter_displayed=True,
) | [
"def",
"find_by_tooltip",
"(",
"browser",
",",
"tooltip",
")",
":",
"return",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'//*[@title=%(tooltip)s or @data-original-title=%(tooltip)s]'",
"%",
"dict",
"(",
"tooltip",
"=",
"string_literal",
"(",
"tooltip",
")",
")",
")",
",",
"filter_displayed",
"=",
"True",
",",
")"
] | Find elements with the given tooltip.
:param browser: ``world.browser``
:param tooltip: Tooltip to search for
Returns: an :class:`ElementSelector` | [
"Find",
"elements",
"with",
"the",
"given",
"tooltip",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L794-L809 | train |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | press_by_tooltip | def press_by_tooltip(self, tooltip):
"""
Click on a HTML element with a given tooltip.
This is very useful if you're clicking on icon buttons, etc.
"""
for button in find_by_tooltip(world.browser, tooltip):
try:
button.click()
break
except: # pylint:disable=bare-except
pass
else:
raise AssertionError("No button with tooltip '{0}' found"
.format(tooltip)) | python | def press_by_tooltip(self, tooltip):
"""
Click on a HTML element with a given tooltip.
This is very useful if you're clicking on icon buttons, etc.
"""
for button in find_by_tooltip(world.browser, tooltip):
try:
button.click()
break
except: # pylint:disable=bare-except
pass
else:
raise AssertionError("No button with tooltip '{0}' found"
.format(tooltip)) | [
"def",
"press_by_tooltip",
"(",
"self",
",",
"tooltip",
")",
":",
"for",
"button",
"in",
"find_by_tooltip",
"(",
"world",
".",
"browser",
",",
"tooltip",
")",
":",
"try",
":",
"button",
".",
"click",
"(",
")",
"break",
"except",
":",
"# pylint:disable=bare-except",
"pass",
"else",
":",
"raise",
"AssertionError",
"(",
"\"No button with tooltip '{0}' found\"",
".",
"format",
"(",
"tooltip",
")",
")"
] | Click on a HTML element with a given tooltip.
This is very useful if you're clicking on icon buttons, etc. | [
"Click",
"on",
"a",
"HTML",
"element",
"with",
"a",
"given",
"tooltip",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L840-L854 | train |
SHDShim/pytheos | pytheos/scales/objs.py | MGEOS.print_equations | def print_equations(self):
"""
show equations used for the EOS
"""
print("P_static: ", self.eqn_st)
print("P_thermal: ", self.eqn_th)
print("P_anharmonic: ", self.eqn_anh)
print("P_electronic: ", self.eqn_el) | python | def print_equations(self):
"""
show equations used for the EOS
"""
print("P_static: ", self.eqn_st)
print("P_thermal: ", self.eqn_th)
print("P_anharmonic: ", self.eqn_anh)
print("P_electronic: ", self.eqn_el) | [
"def",
"print_equations",
"(",
"self",
")",
":",
"print",
"(",
"\"P_static: \"",
",",
"self",
".",
"eqn_st",
")",
"print",
"(",
"\"P_thermal: \"",
",",
"self",
".",
"eqn_th",
")",
"print",
"(",
"\"P_anharmonic: \"",
",",
"self",
".",
"eqn_anh",
")",
"print",
"(",
"\"P_electronic: \"",
",",
"self",
".",
"eqn_el",
")"
] | show equations used for the EOS | [
"show",
"equations",
"used",
"for",
"the",
"EOS"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L84-L91 | train |
SHDShim/pytheos | pytheos/scales/objs.py | MGEOS._set_params | def _set_params(self, p):
"""
change parameters in OrderedDict to list with or without uncertainties
:param p: parameters in OrderedDict
:return: parameters in list
:note: internal function
"""
if self.force_norm:
params = [value.n for key, value in p.items()]
else:
params = [value for key, value in p.items()]
return params | python | def _set_params(self, p):
"""
change parameters in OrderedDict to list with or without uncertainties
:param p: parameters in OrderedDict
:return: parameters in list
:note: internal function
"""
if self.force_norm:
params = [value.n for key, value in p.items()]
else:
params = [value for key, value in p.items()]
return params | [
"def",
"_set_params",
"(",
"self",
",",
"p",
")",
":",
"if",
"self",
".",
"force_norm",
":",
"params",
"=",
"[",
"value",
".",
"n",
"for",
"key",
",",
"value",
"in",
"p",
".",
"items",
"(",
")",
"]",
"else",
":",
"params",
"=",
"[",
"value",
"for",
"key",
",",
"value",
"in",
"p",
".",
"items",
"(",
")",
"]",
"return",
"params"
] | change parameters in OrderedDict to list with or without uncertainties
:param p: parameters in OrderedDict
:return: parameters in list
:note: internal function | [
"change",
"parameters",
"in",
"OrderedDict",
"to",
"list",
"with",
"or",
"without",
"uncertainties"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L102-L114 | train |
SHDShim/pytheos | pytheos/scales/objs.py | MGEOS.cal_pel | def cal_pel(self, v, temp):
"""
calculate pressure from electronic contributions
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa
"""
if (self.eqn_el is None) or (self.params_el is None):
return np.zeros_like(v)
params = self._set_params(self.params_el)
return func_el[self.eqn_el](v, temp, *params,
self.n, self.z, t_ref=self.t_ref,
three_r=self.three_r) | python | def cal_pel(self, v, temp):
"""
calculate pressure from electronic contributions
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa
"""
if (self.eqn_el is None) or (self.params_el is None):
return np.zeros_like(v)
params = self._set_params(self.params_el)
return func_el[self.eqn_el](v, temp, *params,
self.n, self.z, t_ref=self.t_ref,
three_r=self.three_r) | [
"def",
"cal_pel",
"(",
"self",
",",
"v",
",",
"temp",
")",
":",
"if",
"(",
"self",
".",
"eqn_el",
"is",
"None",
")",
"or",
"(",
"self",
".",
"params_el",
"is",
"None",
")",
":",
"return",
"np",
".",
"zeros_like",
"(",
"v",
")",
"params",
"=",
"self",
".",
"_set_params",
"(",
"self",
".",
"params_el",
")",
"return",
"func_el",
"[",
"self",
".",
"eqn_el",
"]",
"(",
"v",
",",
"temp",
",",
"*",
"params",
",",
"self",
".",
"n",
",",
"self",
".",
"z",
",",
"t_ref",
"=",
"self",
".",
"t_ref",
",",
"three_r",
"=",
"self",
".",
"three_r",
")"
] | calculate pressure from electronic contributions
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa | [
"calculate",
"pressure",
"from",
"electronic",
"contributions"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L141-L154 | train |
SHDShim/pytheos | pytheos/scales/objs.py | MGEOS.cal_panh | def cal_panh(self, v, temp):
"""
calculate pressure from anharmonic contributions
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa
"""
if (self.eqn_anh is None) or (self.params_anh is None):
return np.zeros_like(v)
params = self._set_params(self.params_anh)
return func_anh[self.eqn_anh](v, temp, *params,
self.n, self.z, t_ref=self.t_ref,
three_r=self.three_r) | python | def cal_panh(self, v, temp):
"""
calculate pressure from anharmonic contributions
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa
"""
if (self.eqn_anh is None) or (self.params_anh is None):
return np.zeros_like(v)
params = self._set_params(self.params_anh)
return func_anh[self.eqn_anh](v, temp, *params,
self.n, self.z, t_ref=self.t_ref,
three_r=self.three_r) | [
"def",
"cal_panh",
"(",
"self",
",",
"v",
",",
"temp",
")",
":",
"if",
"(",
"self",
".",
"eqn_anh",
"is",
"None",
")",
"or",
"(",
"self",
".",
"params_anh",
"is",
"None",
")",
":",
"return",
"np",
".",
"zeros_like",
"(",
"v",
")",
"params",
"=",
"self",
".",
"_set_params",
"(",
"self",
".",
"params_anh",
")",
"return",
"func_anh",
"[",
"self",
".",
"eqn_anh",
"]",
"(",
"v",
",",
"temp",
",",
"*",
"params",
",",
"self",
".",
"n",
",",
"self",
".",
"z",
",",
"t_ref",
"=",
"self",
".",
"t_ref",
",",
"three_r",
"=",
"self",
".",
"three_r",
")"
] | calculate pressure from anharmonic contributions
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa | [
"calculate",
"pressure",
"from",
"anharmonic",
"contributions"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L156-L169 | train |
SHDShim/pytheos | pytheos/scales/objs.py | JHEOS._hugoniot_t | def _hugoniot_t(self, v):
"""
calculate Hugoniot temperature
:param v: unit-cell volume in A^3
:return: temperature in K
:note: 2017/05/10, It is intentional that I call hugoniot_t
instead of hugoniot_t_nlin for the nonlinear case.
The reason is the hugoniot_t_nlin (and its equivalent part in mdaap)
has numerical problem. In fact, I found no problem to match the
Jamieson table values with the use of linear thermal part instead of
non-linear version.
"""
rho = self._get_rho(v)
params_h = self._set_params(self.params_hugoniot)
params_t = self._set_params(self.params_therm)
if self.nonlinear:
return hugoniot_t(rho, *params_h[:-1], *params_t[1:],
self.n, self.mass, three_r=self.three_r,
c_v=self.c_v)
else:
return hugoniot_t(rho, *params_h, *params_t[1:],
self.n, self.mass, three_r=self.three_r,
c_v=self.c_v) | python | def _hugoniot_t(self, v):
"""
calculate Hugoniot temperature
:param v: unit-cell volume in A^3
:return: temperature in K
:note: 2017/05/10, It is intentional that I call hugoniot_t
instead of hugoniot_t_nlin for the nonlinear case.
The reason is the hugoniot_t_nlin (and its equivalent part in mdaap)
has numerical problem. In fact, I found no problem to match the
Jamieson table values with the use of linear thermal part instead of
non-linear version.
"""
rho = self._get_rho(v)
params_h = self._set_params(self.params_hugoniot)
params_t = self._set_params(self.params_therm)
if self.nonlinear:
return hugoniot_t(rho, *params_h[:-1], *params_t[1:],
self.n, self.mass, three_r=self.three_r,
c_v=self.c_v)
else:
return hugoniot_t(rho, *params_h, *params_t[1:],
self.n, self.mass, three_r=self.three_r,
c_v=self.c_v) | [
"def",
"_hugoniot_t",
"(",
"self",
",",
"v",
")",
":",
"rho",
"=",
"self",
".",
"_get_rho",
"(",
"v",
")",
"params_h",
"=",
"self",
".",
"_set_params",
"(",
"self",
".",
"params_hugoniot",
")",
"params_t",
"=",
"self",
".",
"_set_params",
"(",
"self",
".",
"params_therm",
")",
"if",
"self",
".",
"nonlinear",
":",
"return",
"hugoniot_t",
"(",
"rho",
",",
"*",
"params_h",
"[",
":",
"-",
"1",
"]",
",",
"*",
"params_t",
"[",
"1",
":",
"]",
",",
"self",
".",
"n",
",",
"self",
".",
"mass",
",",
"three_r",
"=",
"self",
".",
"three_r",
",",
"c_v",
"=",
"self",
".",
"c_v",
")",
"else",
":",
"return",
"hugoniot_t",
"(",
"rho",
",",
"*",
"params_h",
",",
"*",
"params_t",
"[",
"1",
":",
"]",
",",
"self",
".",
"n",
",",
"self",
".",
"mass",
",",
"three_r",
"=",
"self",
".",
"three_r",
",",
"c_v",
"=",
"self",
".",
"c_v",
")"
] | calculate Hugoniot temperature
:param v: unit-cell volume in A^3
:return: temperature in K
:note: 2017/05/10, It is intentional that I call hugoniot_t
instead of hugoniot_t_nlin for the nonlinear case.
The reason is the hugoniot_t_nlin (and its equivalent part in mdaap)
has numerical problem. In fact, I found no problem to match the
Jamieson table values with the use of linear thermal part instead of
non-linear version. | [
"calculate",
"Hugoniot",
"temperature"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L352-L375 | train |
SHDShim/pytheos | pytheos/scales/objs.py | JHEOS._hugoniot_pth | def _hugoniot_pth(self, v):
"""
calculate thermal pressure along hugoniot
:param v: unit-cell volume in A^3
:return: thermal pressure along hugoniot in GPa
"""
temp = self._hugoniot_t(v)
return self.cal_pth(v, temp) | python | def _hugoniot_pth(self, v):
"""
calculate thermal pressure along hugoniot
:param v: unit-cell volume in A^3
:return: thermal pressure along hugoniot in GPa
"""
temp = self._hugoniot_t(v)
return self.cal_pth(v, temp) | [
"def",
"_hugoniot_pth",
"(",
"self",
",",
"v",
")",
":",
"temp",
"=",
"self",
".",
"_hugoniot_t",
"(",
"v",
")",
"return",
"self",
".",
"cal_pth",
"(",
"v",
",",
"temp",
")"
] | calculate thermal pressure along hugoniot
:param v: unit-cell volume in A^3
:return: thermal pressure along hugoniot in GPa | [
"calculate",
"thermal",
"pressure",
"along",
"hugoniot"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L389-L397 | train |
SHDShim/pytheos | pytheos/scales/objs.py | JHEOS.cal_v | def cal_v(self, p, temp, min_strain=0.3, max_strain=1.0):
"""
calculate unit-cell volume at given pressure and temperature
:param p: pressure in GPa
:param temp: temperature in K
:param min_strain: minimum strain searched for volume root
:param max_strain: maximum strain searched for volume root
:return: unit-cell volume in A^3
:note: 2017/05/10 I found wrap function is not compatible with
OrderedDict. So I convert unp array to np array.
"""
v0 = self.params_therm['v0'].nominal_value
self.force_norm = True
pp = unp.nominal_values(p)
ttemp = unp.nominal_values(temp)
def _cal_v_single(pp, ttemp):
if (pp <= 1.e-5) and (ttemp == 300.):
return v0
def f_diff(v, ttemp, pp):
return self.cal_p(v, ttemp) - pp
# print(f_diff(v0 * 0.3, temp, p))
v = brenth(f_diff, v0 * max_strain, v0 * min_strain,
args=(ttemp, pp))
return v
f_vu = np.vectorize(_cal_v_single)
v = f_vu(pp, ttemp)
self.force_norm = False
return v | python | def cal_v(self, p, temp, min_strain=0.3, max_strain=1.0):
"""
calculate unit-cell volume at given pressure and temperature
:param p: pressure in GPa
:param temp: temperature in K
:param min_strain: minimum strain searched for volume root
:param max_strain: maximum strain searched for volume root
:return: unit-cell volume in A^3
:note: 2017/05/10 I found wrap function is not compatible with
OrderedDict. So I convert unp array to np array.
"""
v0 = self.params_therm['v0'].nominal_value
self.force_norm = True
pp = unp.nominal_values(p)
ttemp = unp.nominal_values(temp)
def _cal_v_single(pp, ttemp):
if (pp <= 1.e-5) and (ttemp == 300.):
return v0
def f_diff(v, ttemp, pp):
return self.cal_p(v, ttemp) - pp
# print(f_diff(v0 * 0.3, temp, p))
v = brenth(f_diff, v0 * max_strain, v0 * min_strain,
args=(ttemp, pp))
return v
f_vu = np.vectorize(_cal_v_single)
v = f_vu(pp, ttemp)
self.force_norm = False
return v | [
"def",
"cal_v",
"(",
"self",
",",
"p",
",",
"temp",
",",
"min_strain",
"=",
"0.3",
",",
"max_strain",
"=",
"1.0",
")",
":",
"v0",
"=",
"self",
".",
"params_therm",
"[",
"'v0'",
"]",
".",
"nominal_value",
"self",
".",
"force_norm",
"=",
"True",
"pp",
"=",
"unp",
".",
"nominal_values",
"(",
"p",
")",
"ttemp",
"=",
"unp",
".",
"nominal_values",
"(",
"temp",
")",
"def",
"_cal_v_single",
"(",
"pp",
",",
"ttemp",
")",
":",
"if",
"(",
"pp",
"<=",
"1.e-5",
")",
"and",
"(",
"ttemp",
"==",
"300.",
")",
":",
"return",
"v0",
"def",
"f_diff",
"(",
"v",
",",
"ttemp",
",",
"pp",
")",
":",
"return",
"self",
".",
"cal_p",
"(",
"v",
",",
"ttemp",
")",
"-",
"pp",
"# print(f_diff(v0 * 0.3, temp, p))",
"v",
"=",
"brenth",
"(",
"f_diff",
",",
"v0",
"*",
"max_strain",
",",
"v0",
"*",
"min_strain",
",",
"args",
"=",
"(",
"ttemp",
",",
"pp",
")",
")",
"return",
"v",
"f_vu",
"=",
"np",
".",
"vectorize",
"(",
"_cal_v_single",
")",
"v",
"=",
"f_vu",
"(",
"pp",
",",
"ttemp",
")",
"self",
".",
"force_norm",
"=",
"False",
"return",
"v"
] | calculate unit-cell volume at given pressure and temperature
:param p: pressure in GPa
:param temp: temperature in K
:param min_strain: minimum strain searched for volume root
:param max_strain: maximum strain searched for volume root
:return: unit-cell volume in A^3
:note: 2017/05/10 I found wrap function is not compatible with
OrderedDict. So I convert unp array to np array. | [
"calculate",
"unit",
"-",
"cell",
"volume",
"at",
"given",
"pressure",
"and",
"temperature"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L409-L439 | train |
ChrisBeaumont/smother | smother/interval.py | parse_intervals | def parse_intervals(path, as_context=False):
"""
Parse path strings into a collection of Intervals.
`path` is a string describing a region in a file. It's format is
dotted.module.name:[line | start-stop | context]
`dotted.module.name` is a python module
`line` is a single line number in the module (1-offset)
`start-stop` is a right-open interval of line numbers
`context` is a '.' delimited, nested name of a class or function.
For example FooClass.method_a.inner_method
identifies the innermost function in code like
class FooClass:
def method_a(self):
def inner_method():
pass
Parameters
----------
path : str
Region description (see above)
as_context : bool (optional, default=False)
If `True`, return `ContextInterval`s instead of `LineInterval`s.
If `path` provides a line number or range, the result will include
all contexts that intersect this line range.
Returns
-------
list of `Interval`s
"""
def _regions_from_range():
if as_context:
ctxs = list(set(pf.lines[start - 1: stop - 1]))
return [
ContextInterval(filename, ctx)
for ctx in ctxs
]
else:
return [LineInterval(filename, start, stop)]
if ':' in path:
path, subpath = path.split(':')
else:
subpath = ''
pf = PythonFile.from_modulename(path)
filename = pf.filename
rng = NUMBER_RE.match(subpath)
if rng: # specified a line or line range
start, stop = map(int, rng.groups(0))
stop = stop or start + 1
return _regions_from_range()
elif not subpath: # asked for entire module
if as_context:
return [ContextInterval(filename, pf.prefix)]
start, stop = 1, pf.line_count + 1
return _regions_from_range()
else: # specified a context name
context = pf.prefix + ':' + subpath
if context not in pf.lines:
raise ValueError("%s is not a valid context for %s"
% (context, pf.prefix))
if as_context:
return [ContextInterval(filename, context)]
else:
start, stop = pf.context_range(context)
return [LineInterval(filename, start, stop)] | python | def parse_intervals(path, as_context=False):
"""
Parse path strings into a collection of Intervals.
`path` is a string describing a region in a file. It's format is
dotted.module.name:[line | start-stop | context]
`dotted.module.name` is a python module
`line` is a single line number in the module (1-offset)
`start-stop` is a right-open interval of line numbers
`context` is a '.' delimited, nested name of a class or function.
For example FooClass.method_a.inner_method
identifies the innermost function in code like
class FooClass:
def method_a(self):
def inner_method():
pass
Parameters
----------
path : str
Region description (see above)
as_context : bool (optional, default=False)
If `True`, return `ContextInterval`s instead of `LineInterval`s.
If `path` provides a line number or range, the result will include
all contexts that intersect this line range.
Returns
-------
list of `Interval`s
"""
def _regions_from_range():
if as_context:
ctxs = list(set(pf.lines[start - 1: stop - 1]))
return [
ContextInterval(filename, ctx)
for ctx in ctxs
]
else:
return [LineInterval(filename, start, stop)]
if ':' in path:
path, subpath = path.split(':')
else:
subpath = ''
pf = PythonFile.from_modulename(path)
filename = pf.filename
rng = NUMBER_RE.match(subpath)
if rng: # specified a line or line range
start, stop = map(int, rng.groups(0))
stop = stop or start + 1
return _regions_from_range()
elif not subpath: # asked for entire module
if as_context:
return [ContextInterval(filename, pf.prefix)]
start, stop = 1, pf.line_count + 1
return _regions_from_range()
else: # specified a context name
context = pf.prefix + ':' + subpath
if context not in pf.lines:
raise ValueError("%s is not a valid context for %s"
% (context, pf.prefix))
if as_context:
return [ContextInterval(filename, context)]
else:
start, stop = pf.context_range(context)
return [LineInterval(filename, start, stop)] | [
"def",
"parse_intervals",
"(",
"path",
",",
"as_context",
"=",
"False",
")",
":",
"def",
"_regions_from_range",
"(",
")",
":",
"if",
"as_context",
":",
"ctxs",
"=",
"list",
"(",
"set",
"(",
"pf",
".",
"lines",
"[",
"start",
"-",
"1",
":",
"stop",
"-",
"1",
"]",
")",
")",
"return",
"[",
"ContextInterval",
"(",
"filename",
",",
"ctx",
")",
"for",
"ctx",
"in",
"ctxs",
"]",
"else",
":",
"return",
"[",
"LineInterval",
"(",
"filename",
",",
"start",
",",
"stop",
")",
"]",
"if",
"':'",
"in",
"path",
":",
"path",
",",
"subpath",
"=",
"path",
".",
"split",
"(",
"':'",
")",
"else",
":",
"subpath",
"=",
"''",
"pf",
"=",
"PythonFile",
".",
"from_modulename",
"(",
"path",
")",
"filename",
"=",
"pf",
".",
"filename",
"rng",
"=",
"NUMBER_RE",
".",
"match",
"(",
"subpath",
")",
"if",
"rng",
":",
"# specified a line or line range",
"start",
",",
"stop",
"=",
"map",
"(",
"int",
",",
"rng",
".",
"groups",
"(",
"0",
")",
")",
"stop",
"=",
"stop",
"or",
"start",
"+",
"1",
"return",
"_regions_from_range",
"(",
")",
"elif",
"not",
"subpath",
":",
"# asked for entire module",
"if",
"as_context",
":",
"return",
"[",
"ContextInterval",
"(",
"filename",
",",
"pf",
".",
"prefix",
")",
"]",
"start",
",",
"stop",
"=",
"1",
",",
"pf",
".",
"line_count",
"+",
"1",
"return",
"_regions_from_range",
"(",
")",
"else",
":",
"# specified a context name",
"context",
"=",
"pf",
".",
"prefix",
"+",
"':'",
"+",
"subpath",
"if",
"context",
"not",
"in",
"pf",
".",
"lines",
":",
"raise",
"ValueError",
"(",
"\"%s is not a valid context for %s\"",
"%",
"(",
"context",
",",
"pf",
".",
"prefix",
")",
")",
"if",
"as_context",
":",
"return",
"[",
"ContextInterval",
"(",
"filename",
",",
"context",
")",
"]",
"else",
":",
"start",
",",
"stop",
"=",
"pf",
".",
"context_range",
"(",
"context",
")",
"return",
"[",
"LineInterval",
"(",
"filename",
",",
"start",
",",
"stop",
")",
"]"
] | Parse path strings into a collection of Intervals.
`path` is a string describing a region in a file. It's format is
dotted.module.name:[line | start-stop | context]
`dotted.module.name` is a python module
`line` is a single line number in the module (1-offset)
`start-stop` is a right-open interval of line numbers
`context` is a '.' delimited, nested name of a class or function.
For example FooClass.method_a.inner_method
identifies the innermost function in code like
class FooClass:
def method_a(self):
def inner_method():
pass
Parameters
----------
path : str
Region description (see above)
as_context : bool (optional, default=False)
If `True`, return `ContextInterval`s instead of `LineInterval`s.
If `path` provides a line number or range, the result will include
all contexts that intersect this line range.
Returns
-------
list of `Interval`s | [
"Parse",
"path",
"strings",
"into",
"a",
"collection",
"of",
"Intervals",
"."
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/interval.py#L55-L127 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_suffix | def p_suffix(self, length=None, elipsis=False):
"Return the rest of the input"
if length is not None:
result = self.input[self.pos:self.pos + length]
if elipsis and len(result) == length:
result += "..."
return result
return self.input[self.pos:] | python | def p_suffix(self, length=None, elipsis=False):
"Return the rest of the input"
if length is not None:
result = self.input[self.pos:self.pos + length]
if elipsis and len(result) == length:
result += "..."
return result
return self.input[self.pos:] | [
"def",
"p_suffix",
"(",
"self",
",",
"length",
"=",
"None",
",",
"elipsis",
"=",
"False",
")",
":",
"if",
"length",
"is",
"not",
"None",
":",
"result",
"=",
"self",
".",
"input",
"[",
"self",
".",
"pos",
":",
"self",
".",
"pos",
"+",
"length",
"]",
"if",
"elipsis",
"and",
"len",
"(",
"result",
")",
"==",
"length",
":",
"result",
"+=",
"\"...\"",
"return",
"result",
"return",
"self",
".",
"input",
"[",
"self",
".",
"pos",
":",
"]"
] | Return the rest of the input | [
"Return",
"the",
"rest",
"of",
"the",
"input"
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L65-L72 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_debug | def p_debug(self, message):
"Format and print debug messages"
print("{}{} `{}`".format(self._debug_indent * " ",
message, repr(self.p_suffix(10)))) | python | def p_debug(self, message):
"Format and print debug messages"
print("{}{} `{}`".format(self._debug_indent * " ",
message, repr(self.p_suffix(10)))) | [
"def",
"p_debug",
"(",
"self",
",",
"message",
")",
":",
"print",
"(",
"\"{}{} `{}`\"",
".",
"format",
"(",
"self",
".",
"_debug_indent",
"*",
"\" \"",
",",
"message",
",",
"repr",
"(",
"self",
".",
"p_suffix",
"(",
"10",
")",
")",
")",
")"
] | Format and print debug messages | [
"Format",
"and",
"print",
"debug",
"messages"
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L74-L77 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_next | def p_next(self):
"Consume and return the next char"
try:
self.pos += 1
return self.input[self.pos - 1]
except IndexError:
self.pos -= 1
return None | python | def p_next(self):
"Consume and return the next char"
try:
self.pos += 1
return self.input[self.pos - 1]
except IndexError:
self.pos -= 1
return None | [
"def",
"p_next",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"pos",
"+=",
"1",
"return",
"self",
".",
"input",
"[",
"self",
".",
"pos",
"-",
"1",
"]",
"except",
"IndexError",
":",
"self",
".",
"pos",
"-=",
"1",
"return",
"None"
] | Consume and return the next char | [
"Consume",
"and",
"return",
"the",
"next",
"char"
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L86-L93 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_current_col | def p_current_col(self):
"Return currnet column in line"
prefix = self.input[:self.pos]
nlidx = prefix.rfind('\n')
if nlidx == -1:
return self.pos
return self.pos - nlidx | python | def p_current_col(self):
"Return currnet column in line"
prefix = self.input[:self.pos]
nlidx = prefix.rfind('\n')
if nlidx == -1:
return self.pos
return self.pos - nlidx | [
"def",
"p_current_col",
"(",
"self",
")",
":",
"prefix",
"=",
"self",
".",
"input",
"[",
":",
"self",
".",
"pos",
"]",
"nlidx",
"=",
"prefix",
".",
"rfind",
"(",
"'\\n'",
")",
"if",
"nlidx",
"==",
"-",
"1",
":",
"return",
"self",
".",
"pos",
"return",
"self",
".",
"pos",
"-",
"nlidx"
] | Return currnet column in line | [
"Return",
"currnet",
"column",
"in",
"line"
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L116-L122 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_pretty_pos | def p_pretty_pos(self):
"Print current line and a pretty cursor below. Used in error messages"
col = self.p_current_col
suffix = self.input[self.pos - col:]
end = suffix.find("\n")
if end != -1:
suffix = suffix[:end]
return "%s\n%s" % (suffix, "-" * col + "^") | python | def p_pretty_pos(self):
"Print current line and a pretty cursor below. Used in error messages"
col = self.p_current_col
suffix = self.input[self.pos - col:]
end = suffix.find("\n")
if end != -1:
suffix = suffix[:end]
return "%s\n%s" % (suffix, "-" * col + "^") | [
"def",
"p_pretty_pos",
"(",
"self",
")",
":",
"col",
"=",
"self",
".",
"p_current_col",
"suffix",
"=",
"self",
".",
"input",
"[",
"self",
".",
"pos",
"-",
"col",
":",
"]",
"end",
"=",
"suffix",
".",
"find",
"(",
"\"\\n\"",
")",
"if",
"end",
"!=",
"-",
"1",
":",
"suffix",
"=",
"suffix",
"[",
":",
"end",
"]",
"return",
"\"%s\\n%s\"",
"%",
"(",
"suffix",
",",
"\"-\"",
"*",
"col",
"+",
"\"^\"",
")"
] | Print current line and a pretty cursor below. Used in error messages | [
"Print",
"current",
"line",
"and",
"a",
"pretty",
"cursor",
"below",
".",
"Used",
"in",
"error",
"messages"
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L124-L131 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_startswith | def p_startswith(self, st, ignorecase=False):
"Return True if the input starts with `st` at current position"
length = len(st)
matcher = result = self.input[self.pos:self.pos + length]
if ignorecase:
matcher = result.lower()
st = st.lower()
if matcher == st:
self.pos += length
return result
return False | python | def p_startswith(self, st, ignorecase=False):
"Return True if the input starts with `st` at current position"
length = len(st)
matcher = result = self.input[self.pos:self.pos + length]
if ignorecase:
matcher = result.lower()
st = st.lower()
if matcher == st:
self.pos += length
return result
return False | [
"def",
"p_startswith",
"(",
"self",
",",
"st",
",",
"ignorecase",
"=",
"False",
")",
":",
"length",
"=",
"len",
"(",
"st",
")",
"matcher",
"=",
"result",
"=",
"self",
".",
"input",
"[",
"self",
".",
"pos",
":",
"self",
".",
"pos",
"+",
"length",
"]",
"if",
"ignorecase",
":",
"matcher",
"=",
"result",
".",
"lower",
"(",
")",
"st",
"=",
"st",
".",
"lower",
"(",
")",
"if",
"matcher",
"==",
"st",
":",
"self",
".",
"pos",
"+=",
"length",
"return",
"result",
"return",
"False"
] | Return True if the input starts with `st` at current position | [
"Return",
"True",
"if",
"the",
"input",
"starts",
"with",
"st",
"at",
"current",
"position"
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L163-L173 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_flatten | def p_flatten(self, obj, **kwargs):
""" Flatten a list of lists of lists... of strings into a string
This is usually used as the action for sequence expressions:
.. code-block::
my_rule <- 'a' . 'c' {p_flatten}
With the input "abc" and no action, this rule returns [ 'a', 'b', 'c'].
{ p_flatten } procuces "abc".
>>> parser.p_flatten(['a', ['b', 'c']])
'abc'
"""
if isinstance(obj, six.string_types):
return obj
result = ""
for i in obj:
result += self.p_flatten(i)
return result | python | def p_flatten(self, obj, **kwargs):
""" Flatten a list of lists of lists... of strings into a string
This is usually used as the action for sequence expressions:
.. code-block::
my_rule <- 'a' . 'c' {p_flatten}
With the input "abc" and no action, this rule returns [ 'a', 'b', 'c'].
{ p_flatten } procuces "abc".
>>> parser.p_flatten(['a', ['b', 'c']])
'abc'
"""
if isinstance(obj, six.string_types):
return obj
result = ""
for i in obj:
result += self.p_flatten(i)
return result | [
"def",
"p_flatten",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"obj",
"result",
"=",
"\"\"",
"for",
"i",
"in",
"obj",
":",
"result",
"+=",
"self",
".",
"p_flatten",
"(",
"i",
")",
"return",
"result"
] | Flatten a list of lists of lists... of strings into a string
This is usually used as the action for sequence expressions:
.. code-block::
my_rule <- 'a' . 'c' {p_flatten}
With the input "abc" and no action, this rule returns [ 'a', 'b', 'c'].
{ p_flatten } procuces "abc".
>>> parser.p_flatten(['a', ['b', 'c']])
'abc' | [
"Flatten",
"a",
"list",
"of",
"lists",
"of",
"lists",
"...",
"of",
"strings",
"into",
"a",
"string"
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L175-L196 | train |
lisael/fastidious | fastidious/parser_base.py | ParserMixin.p_parse | def p_parse(cls, input, methodname=None, parse_all=True):
"""
Parse the `input` using `methodname` as entry point.
If `parse_all` is true, the input MUST be fully consumed at the end of
the parsing, otherwise p_parse raises an exception.
"""
if methodname is None:
methodname = cls.__default__
p = cls(input)
result = getattr(p, methodname)()
if result is cls.NoMatch or parse_all and p.p_peek() is not None:
p.p_raise()
return result | python | def p_parse(cls, input, methodname=None, parse_all=True):
"""
Parse the `input` using `methodname` as entry point.
If `parse_all` is true, the input MUST be fully consumed at the end of
the parsing, otherwise p_parse raises an exception.
"""
if methodname is None:
methodname = cls.__default__
p = cls(input)
result = getattr(p, methodname)()
if result is cls.NoMatch or parse_all and p.p_peek() is not None:
p.p_raise()
return result | [
"def",
"p_parse",
"(",
"cls",
",",
"input",
",",
"methodname",
"=",
"None",
",",
"parse_all",
"=",
"True",
")",
":",
"if",
"methodname",
"is",
"None",
":",
"methodname",
"=",
"cls",
".",
"__default__",
"p",
"=",
"cls",
"(",
"input",
")",
"result",
"=",
"getattr",
"(",
"p",
",",
"methodname",
")",
"(",
")",
"if",
"result",
"is",
"cls",
".",
"NoMatch",
"or",
"parse_all",
"and",
"p",
".",
"p_peek",
"(",
")",
"is",
"not",
"None",
":",
"p",
".",
"p_raise",
"(",
")",
"return",
"result"
] | Parse the `input` using `methodname` as entry point.
If `parse_all` is true, the input MUST be fully consumed at the end of
the parsing, otherwise p_parse raises an exception. | [
"Parse",
"the",
"input",
"using",
"methodname",
"as",
"entry",
"point",
"."
] | 2542db9de779ddabc3a64e9eb19a4e2de99741dc | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L199-L212 | train |
klen/muffin-admin | example/admin.py | bulk_delete | def bulk_delete(handler, request):
"""Bulk delete items"""
ids = request.GET.getall('ids')
Message.delete().where(Message.id << ids).execute()
raise muffin.HTTPFound(handler.url) | python | def bulk_delete(handler, request):
"""Bulk delete items"""
ids = request.GET.getall('ids')
Message.delete().where(Message.id << ids).execute()
raise muffin.HTTPFound(handler.url) | [
"def",
"bulk_delete",
"(",
"handler",
",",
"request",
")",
":",
"ids",
"=",
"request",
".",
"GET",
".",
"getall",
"(",
"'ids'",
")",
"Message",
".",
"delete",
"(",
")",
".",
"where",
"(",
"Message",
".",
"id",
"<<",
"ids",
")",
".",
"execute",
"(",
")",
"raise",
"muffin",
".",
"HTTPFound",
"(",
"handler",
".",
"url",
")"
] | Bulk delete items | [
"Bulk",
"delete",
"items"
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/example/admin.py#L47-L51 | train |
jiasir/playback | playback/cli/manila_share.py | make | def make(parser):
"""provison Manila Share with HA"""
s = parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
def install_f(args):
install(args)
install_parser = install_subparser(s)
install_parser.set_defaults(func=install_f) | python | def make(parser):
"""provison Manila Share with HA"""
s = parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
def install_f(args):
install(args)
install_parser = install_subparser(s)
install_parser.set_defaults(func=install_f) | [
"def",
"make",
"(",
"parser",
")",
":",
"s",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
"'commands'",
",",
"metavar",
"=",
"'COMMAND'",
",",
"help",
"=",
"'description'",
",",
")",
"def",
"install_f",
"(",
"args",
")",
":",
"install",
"(",
"args",
")",
"install_parser",
"=",
"install_subparser",
"(",
"s",
")",
"install_parser",
".",
"set_defaults",
"(",
"func",
"=",
"install_f",
")"
] | provison Manila Share with HA | [
"provison",
"Manila",
"Share",
"with",
"HA"
] | 58b2a5d669dcfaa8cad50c544a4b068dcacf9b69 | https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/cli/manila_share.py#L102-L113 | train |
Capitains/MyCapytain | MyCapytain/resources/collections/dts/_resolver.py | HttpResolverDtsCollection._parse_paginated_members | def _parse_paginated_members(self, direction="children"):
""" Launch parsing of children
"""
page = self._last_page_parsed[direction]
if not page:
page = 1
else:
page = int(page)
while page:
if page > 1:
response = self._resolver.endpoint.get_collection(
collection_id=self.id,
page=page,
nav=direction
)
else:
response = self._resolver.endpoint.get_collection(
collection_id=self.id,
nav=direction
)
response.raise_for_status()
data = response.json()
data = expand(data)[0]
if direction == "children":
self.children.update({
o.id: o
for o in type(self).parse_member(
obj=data, collection=self, direction=direction, resolver=self._resolver
)
})
else:
self.parents.update({
o
for o in type(self).parse_member(
obj=data, collection=self, direction=direction, resolver=self._resolver
)
})
self._last_page_parsed[direction] = page
page = None
if "https://www.w3.org/ns/hydra/core#view" in data:
if "https://www.w3.org/ns/hydra/core#next" in data["https://www.w3.org/ns/hydra/core#view"][0]:
page = int(_re_page.findall(
data["https://www.w3.org/ns/hydra/core#view"]
[0]["https://www.w3.org/ns/hydra/core#next"]
[0]["@value"]
)[0])
self._parsed[direction] = True | python | def _parse_paginated_members(self, direction="children"):
""" Launch parsing of children
"""
page = self._last_page_parsed[direction]
if not page:
page = 1
else:
page = int(page)
while page:
if page > 1:
response = self._resolver.endpoint.get_collection(
collection_id=self.id,
page=page,
nav=direction
)
else:
response = self._resolver.endpoint.get_collection(
collection_id=self.id,
nav=direction
)
response.raise_for_status()
data = response.json()
data = expand(data)[0]
if direction == "children":
self.children.update({
o.id: o
for o in type(self).parse_member(
obj=data, collection=self, direction=direction, resolver=self._resolver
)
})
else:
self.parents.update({
o
for o in type(self).parse_member(
obj=data, collection=self, direction=direction, resolver=self._resolver
)
})
self._last_page_parsed[direction] = page
page = None
if "https://www.w3.org/ns/hydra/core#view" in data:
if "https://www.w3.org/ns/hydra/core#next" in data["https://www.w3.org/ns/hydra/core#view"][0]:
page = int(_re_page.findall(
data["https://www.w3.org/ns/hydra/core#view"]
[0]["https://www.w3.org/ns/hydra/core#next"]
[0]["@value"]
)[0])
self._parsed[direction] = True | [
"def",
"_parse_paginated_members",
"(",
"self",
",",
"direction",
"=",
"\"children\"",
")",
":",
"page",
"=",
"self",
".",
"_last_page_parsed",
"[",
"direction",
"]",
"if",
"not",
"page",
":",
"page",
"=",
"1",
"else",
":",
"page",
"=",
"int",
"(",
"page",
")",
"while",
"page",
":",
"if",
"page",
">",
"1",
":",
"response",
"=",
"self",
".",
"_resolver",
".",
"endpoint",
".",
"get_collection",
"(",
"collection_id",
"=",
"self",
".",
"id",
",",
"page",
"=",
"page",
",",
"nav",
"=",
"direction",
")",
"else",
":",
"response",
"=",
"self",
".",
"_resolver",
".",
"endpoint",
".",
"get_collection",
"(",
"collection_id",
"=",
"self",
".",
"id",
",",
"nav",
"=",
"direction",
")",
"response",
".",
"raise_for_status",
"(",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"data",
"=",
"expand",
"(",
"data",
")",
"[",
"0",
"]",
"if",
"direction",
"==",
"\"children\"",
":",
"self",
".",
"children",
".",
"update",
"(",
"{",
"o",
".",
"id",
":",
"o",
"for",
"o",
"in",
"type",
"(",
"self",
")",
".",
"parse_member",
"(",
"obj",
"=",
"data",
",",
"collection",
"=",
"self",
",",
"direction",
"=",
"direction",
",",
"resolver",
"=",
"self",
".",
"_resolver",
")",
"}",
")",
"else",
":",
"self",
".",
"parents",
".",
"update",
"(",
"{",
"o",
"for",
"o",
"in",
"type",
"(",
"self",
")",
".",
"parse_member",
"(",
"obj",
"=",
"data",
",",
"collection",
"=",
"self",
",",
"direction",
"=",
"direction",
",",
"resolver",
"=",
"self",
".",
"_resolver",
")",
"}",
")",
"self",
".",
"_last_page_parsed",
"[",
"direction",
"]",
"=",
"page",
"page",
"=",
"None",
"if",
"\"https://www.w3.org/ns/hydra/core#view\"",
"in",
"data",
":",
"if",
"\"https://www.w3.org/ns/hydra/core#next\"",
"in",
"data",
"[",
"\"https://www.w3.org/ns/hydra/core#view\"",
"]",
"[",
"0",
"]",
":",
"page",
"=",
"int",
"(",
"_re_page",
".",
"findall",
"(",
"data",
"[",
"\"https://www.w3.org/ns/hydra/core#view\"",
"]",
"[",
"0",
"]",
"[",
"\"https://www.w3.org/ns/hydra/core#next\"",
"]",
"[",
"0",
"]",
"[",
"\"@value\"",
"]",
")",
"[",
"0",
"]",
")",
"self",
".",
"_parsed",
"[",
"direction",
"]",
"=",
"True"
] | Launch parsing of children | [
"Launch",
"parsing",
"of",
"children"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/dts/_resolver.py#L103-L154 | train |
erijo/tellive-py | tellive/client.py | LiveClient.request_token | def request_token(self):
""" Returns url, request_token, request_secret"""
logging.debug("Getting request token from %s:%d",
self.server, self.port)
token, secret = self._token("/oauth/requestToken")
return "{}/oauth/authorize?oauth_token={}".format(self.host, token), \
token, secret | python | def request_token(self):
""" Returns url, request_token, request_secret"""
logging.debug("Getting request token from %s:%d",
self.server, self.port)
token, secret = self._token("/oauth/requestToken")
return "{}/oauth/authorize?oauth_token={}".format(self.host, token), \
token, secret | [
"def",
"request_token",
"(",
"self",
")",
":",
"logging",
".",
"debug",
"(",
"\"Getting request token from %s:%d\"",
",",
"self",
".",
"server",
",",
"self",
".",
"port",
")",
"token",
",",
"secret",
"=",
"self",
".",
"_token",
"(",
"\"/oauth/requestToken\"",
")",
"return",
"\"{}/oauth/authorize?oauth_token={}\"",
".",
"format",
"(",
"self",
".",
"host",
",",
"token",
")",
",",
"token",
",",
"secret"
] | Returns url, request_token, request_secret | [
"Returns",
"url",
"request_token",
"request_secret"
] | a84ebb1eb29ee4c69a085e55e523ac5fff0087fc | https://github.com/erijo/tellive-py/blob/a84ebb1eb29ee4c69a085e55e523ac5fff0087fc/tellive/client.py#L65-L71 | train |
erijo/tellive-py | tellive/client.py | LiveClient.access_token | def access_token(self, request_token, request_secret):
"""Returns access_token, access_secret"""
logging.debug("Getting access token from %s:%d",
self.server, self.port)
self.access_token, self.access_secret = \
self._token("/oauth/accessToken", request_token, request_secret)
return self.access_token, self.access_secret | python | def access_token(self, request_token, request_secret):
"""Returns access_token, access_secret"""
logging.debug("Getting access token from %s:%d",
self.server, self.port)
self.access_token, self.access_secret = \
self._token("/oauth/accessToken", request_token, request_secret)
return self.access_token, self.access_secret | [
"def",
"access_token",
"(",
"self",
",",
"request_token",
",",
"request_secret",
")",
":",
"logging",
".",
"debug",
"(",
"\"Getting access token from %s:%d\"",
",",
"self",
".",
"server",
",",
"self",
".",
"port",
")",
"self",
".",
"access_token",
",",
"self",
".",
"access_secret",
"=",
"self",
".",
"_token",
"(",
"\"/oauth/accessToken\"",
",",
"request_token",
",",
"request_secret",
")",
"return",
"self",
".",
"access_token",
",",
"self",
".",
"access_secret"
] | Returns access_token, access_secret | [
"Returns",
"access_token",
"access_secret"
] | a84ebb1eb29ee4c69a085e55e523ac5fff0087fc | https://github.com/erijo/tellive-py/blob/a84ebb1eb29ee4c69a085e55e523ac5fff0087fc/tellive/client.py#L73-L79 | train |
potatolondon/gae-pytz | pytz/gae.py | TimezoneLoader.open_resource | def open_resource(self, name):
"""Opens a resource from the zoneinfo subdir for reading."""
# Import nested here so we can run setup.py without GAE.
from google.appengine.api import memcache
from pytz import OLSON_VERSION
name_parts = name.lstrip('/').split('/')
if os.path.pardir in name_parts:
raise ValueError('Bad path segment: %r' % os.path.pardir)
cache_key = 'pytz.zoneinfo.%s.%s' % (OLSON_VERSION, name)
zonedata = memcache.get(cache_key)
if zonedata is None:
zonedata = get_zoneinfo().read('zoneinfo/' + '/'.join(name_parts))
memcache.add(cache_key, zonedata)
log.info('Added timezone to memcache: %s' % cache_key)
else:
log.info('Loaded timezone from memcache: %s' % cache_key)
return StringIO(zonedata) | python | def open_resource(self, name):
"""Opens a resource from the zoneinfo subdir for reading."""
# Import nested here so we can run setup.py without GAE.
from google.appengine.api import memcache
from pytz import OLSON_VERSION
name_parts = name.lstrip('/').split('/')
if os.path.pardir in name_parts:
raise ValueError('Bad path segment: %r' % os.path.pardir)
cache_key = 'pytz.zoneinfo.%s.%s' % (OLSON_VERSION, name)
zonedata = memcache.get(cache_key)
if zonedata is None:
zonedata = get_zoneinfo().read('zoneinfo/' + '/'.join(name_parts))
memcache.add(cache_key, zonedata)
log.info('Added timezone to memcache: %s' % cache_key)
else:
log.info('Loaded timezone from memcache: %s' % cache_key)
return StringIO(zonedata) | [
"def",
"open_resource",
"(",
"self",
",",
"name",
")",
":",
"# Import nested here so we can run setup.py without GAE.",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"memcache",
"from",
"pytz",
"import",
"OLSON_VERSION",
"name_parts",
"=",
"name",
".",
"lstrip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"os",
".",
"path",
".",
"pardir",
"in",
"name_parts",
":",
"raise",
"ValueError",
"(",
"'Bad path segment: %r'",
"%",
"os",
".",
"path",
".",
"pardir",
")",
"cache_key",
"=",
"'pytz.zoneinfo.%s.%s'",
"%",
"(",
"OLSON_VERSION",
",",
"name",
")",
"zonedata",
"=",
"memcache",
".",
"get",
"(",
"cache_key",
")",
"if",
"zonedata",
"is",
"None",
":",
"zonedata",
"=",
"get_zoneinfo",
"(",
")",
".",
"read",
"(",
"'zoneinfo/'",
"+",
"'/'",
".",
"join",
"(",
"name_parts",
")",
")",
"memcache",
".",
"add",
"(",
"cache_key",
",",
"zonedata",
")",
"log",
".",
"info",
"(",
"'Added timezone to memcache: %s'",
"%",
"cache_key",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Loaded timezone from memcache: %s'",
"%",
"cache_key",
")",
"return",
"StringIO",
"(",
"zonedata",
")"
] | Opens a resource from the zoneinfo subdir for reading. | [
"Opens",
"a",
"resource",
"from",
"the",
"zoneinfo",
"subdir",
"for",
"reading",
"."
] | 24741951a7af3e79cd8727ae3f79265decc93fef | https://github.com/potatolondon/gae-pytz/blob/24741951a7af3e79cd8727ae3f79265decc93fef/pytz/gae.py#L46-L65 | train |
potatolondon/gae-pytz | pytz/gae.py | TimezoneLoader.resource_exists | def resource_exists(self, name):
"""Return true if the given resource exists"""
if name not in self.available:
try:
get_zoneinfo().getinfo('zoneinfo/' + name)
self.available[name] = True
except KeyError:
self.available[name] = False
return self.available[name] | python | def resource_exists(self, name):
"""Return true if the given resource exists"""
if name not in self.available:
try:
get_zoneinfo().getinfo('zoneinfo/' + name)
self.available[name] = True
except KeyError:
self.available[name] = False
return self.available[name] | [
"def",
"resource_exists",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"available",
":",
"try",
":",
"get_zoneinfo",
"(",
")",
".",
"getinfo",
"(",
"'zoneinfo/'",
"+",
"name",
")",
"self",
".",
"available",
"[",
"name",
"]",
"=",
"True",
"except",
"KeyError",
":",
"self",
".",
"available",
"[",
"name",
"]",
"=",
"False",
"return",
"self",
".",
"available",
"[",
"name",
"]"
] | Return true if the given resource exists | [
"Return",
"true",
"if",
"the",
"given",
"resource",
"exists"
] | 24741951a7af3e79cd8727ae3f79265decc93fef | https://github.com/potatolondon/gae-pytz/blob/24741951a7af3e79cd8727ae3f79265decc93fef/pytz/gae.py#L67-L76 | train |
crdoconnor/commandlib | hitch/key.py | bdd | def bdd(*keywords):
"""
Run tests matching keywords.
"""
settings = _personal_settings().data
_storybook().with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play() | python | def bdd(*keywords):
"""
Run tests matching keywords.
"""
settings = _personal_settings().data
_storybook().with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play() | [
"def",
"bdd",
"(",
"*",
"keywords",
")",
":",
"settings",
"=",
"_personal_settings",
"(",
")",
".",
"data",
"_storybook",
"(",
")",
".",
"with_params",
"(",
"*",
"*",
"{",
"\"python version\"",
":",
"settings",
"[",
"\"params\"",
"]",
"[",
"\"python version\"",
"]",
"}",
")",
".",
"only_uninherited",
"(",
")",
".",
"shortcut",
"(",
"*",
"keywords",
")",
".",
"play",
"(",
")"
] | Run tests matching keywords. | [
"Run",
"tests",
"matching",
"keywords",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/hitch/key.py#L212-L219 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihcclient.py | IHCSoapClient.authenticate | def authenticate(self, username: str, password: str) -> bool:
"""Do an Authentricate request and save the cookie returned to be used
on the following requests.
Return True if the request was successfull
"""
self.username = username
self.password = password
auth_payload = """<authenticate1 xmlns=\"utcs\"
xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
<password>{password}</password>
<username>{username}</username>
<application>treeview</application>
</authenticate1>"""
payload = auth_payload.format(password=self.password,
username=self.username)
xdoc = self.connection.soap_action(
'/ws/AuthenticationService', 'authenticate', payload)
if xdoc:
isok = xdoc.find(
'./SOAP-ENV:Body/ns1:authenticate2/ns1:loginWasSuccessful',
IHCSoapClient.ihcns)
return isok.text == 'true'
return False | python | def authenticate(self, username: str, password: str) -> bool:
"""Do an Authentricate request and save the cookie returned to be used
on the following requests.
Return True if the request was successfull
"""
self.username = username
self.password = password
auth_payload = """<authenticate1 xmlns=\"utcs\"
xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
<password>{password}</password>
<username>{username}</username>
<application>treeview</application>
</authenticate1>"""
payload = auth_payload.format(password=self.password,
username=self.username)
xdoc = self.connection.soap_action(
'/ws/AuthenticationService', 'authenticate', payload)
if xdoc:
isok = xdoc.find(
'./SOAP-ENV:Body/ns1:authenticate2/ns1:loginWasSuccessful',
IHCSoapClient.ihcns)
return isok.text == 'true'
return False | [
"def",
"authenticate",
"(",
"self",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"bool",
":",
"self",
".",
"username",
"=",
"username",
"self",
".",
"password",
"=",
"password",
"auth_payload",
"=",
"\"\"\"<authenticate1 xmlns=\\\"utcs\\\"\n xmlns:i=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\n <password>{password}</password>\n <username>{username}</username>\n <application>treeview</application>\n </authenticate1>\"\"\"",
"payload",
"=",
"auth_payload",
".",
"format",
"(",
"password",
"=",
"self",
".",
"password",
",",
"username",
"=",
"self",
".",
"username",
")",
"xdoc",
"=",
"self",
".",
"connection",
".",
"soap_action",
"(",
"'/ws/AuthenticationService'",
",",
"'authenticate'",
",",
"payload",
")",
"if",
"xdoc",
":",
"isok",
"=",
"xdoc",
".",
"find",
"(",
"'./SOAP-ENV:Body/ns1:authenticate2/ns1:loginWasSuccessful'",
",",
"IHCSoapClient",
".",
"ihcns",
")",
"return",
"isok",
".",
"text",
"==",
"'true'",
"return",
"False"
] | Do an Authentricate request and save the cookie returned to be used
on the following requests.
Return True if the request was successfull | [
"Do",
"an",
"Authentricate",
"request",
"and",
"save",
"the",
"cookie",
"returned",
"to",
"be",
"used",
"on",
"the",
"following",
"requests",
".",
"Return",
"True",
"if",
"the",
"request",
"was",
"successfull"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcclient.py#L27-L51 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihcclient.py | IHCSoapClient.get_project | def get_project(self) -> str:
"""Get the ihc project"""
xdoc = self.connection.soap_action('/ws/ControllerService',
'getIHCProject', "")
if xdoc:
base64data = xdoc.find(
'./SOAP-ENV:Body/ns1:getIHCProject1/ns1:data',
IHCSoapClient.ihcns).text
if not base64:
return False
compresseddata = base64.b64decode(base64data)
return zlib.decompress(compresseddata,
16+zlib.MAX_WBITS).decode('ISO-8859-1')
return False | python | def get_project(self) -> str:
"""Get the ihc project"""
xdoc = self.connection.soap_action('/ws/ControllerService',
'getIHCProject', "")
if xdoc:
base64data = xdoc.find(
'./SOAP-ENV:Body/ns1:getIHCProject1/ns1:data',
IHCSoapClient.ihcns).text
if not base64:
return False
compresseddata = base64.b64decode(base64data)
return zlib.decompress(compresseddata,
16+zlib.MAX_WBITS).decode('ISO-8859-1')
return False | [
"def",
"get_project",
"(",
"self",
")",
"->",
"str",
":",
"xdoc",
"=",
"self",
".",
"connection",
".",
"soap_action",
"(",
"'/ws/ControllerService'",
",",
"'getIHCProject'",
",",
"\"\"",
")",
"if",
"xdoc",
":",
"base64data",
"=",
"xdoc",
".",
"find",
"(",
"'./SOAP-ENV:Body/ns1:getIHCProject1/ns1:data'",
",",
"IHCSoapClient",
".",
"ihcns",
")",
".",
"text",
"if",
"not",
"base64",
":",
"return",
"False",
"compresseddata",
"=",
"base64",
".",
"b64decode",
"(",
"base64data",
")",
"return",
"zlib",
".",
"decompress",
"(",
"compresseddata",
",",
"16",
"+",
"zlib",
".",
"MAX_WBITS",
")",
".",
"decode",
"(",
"'ISO-8859-1'",
")",
"return",
"False"
] | Get the ihc project | [
"Get",
"the",
"ihc",
"project"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcclient.py#L81-L94 | train |
persandstrom/python-vasttrafik | vasttrafik/journy_planner.py | _get_node | def _get_node(response, *ancestors):
""" Traverse tree to node """
document = response
for ancestor in ancestors:
if ancestor not in document:
return {}
else:
document = document[ancestor]
return document | python | def _get_node(response, *ancestors):
""" Traverse tree to node """
document = response
for ancestor in ancestors:
if ancestor not in document:
return {}
else:
document = document[ancestor]
return document | [
"def",
"_get_node",
"(",
"response",
",",
"*",
"ancestors",
")",
":",
"document",
"=",
"response",
"for",
"ancestor",
"in",
"ancestors",
":",
"if",
"ancestor",
"not",
"in",
"document",
":",
"return",
"{",
"}",
"else",
":",
"document",
"=",
"document",
"[",
"ancestor",
"]",
"return",
"document"
] | Traverse tree to node | [
"Traverse",
"tree",
"to",
"node"
] | 9c657fde1e91229c5878ea25530260596d296d37 | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L20-L28 | train |
persandstrom/python-vasttrafik | vasttrafik/journy_planner.py | JournyPlanner.update_token | def update_token(self):
""" Get token from key and secret """
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64.b64encode(
(self._key + ':' + self._secret).encode()).decode()
}
data = {'grant_type': 'client_credentials'}
response = requests.post(TOKEN_URL, data=data, headers=headers)
obj = json.loads(response.content.decode('UTF-8'))
self._token = obj['access_token']
self._token_expire_date = (
datetime.now() +
timedelta(minutes=self._expiery)) | python | def update_token(self):
""" Get token from key and secret """
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64.b64encode(
(self._key + ':' + self._secret).encode()).decode()
}
data = {'grant_type': 'client_credentials'}
response = requests.post(TOKEN_URL, data=data, headers=headers)
obj = json.loads(response.content.decode('UTF-8'))
self._token = obj['access_token']
self._token_expire_date = (
datetime.now() +
timedelta(minutes=self._expiery)) | [
"def",
"update_token",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
",",
"'Authorization'",
":",
"'Basic '",
"+",
"base64",
".",
"b64encode",
"(",
"(",
"self",
".",
"_key",
"+",
"':'",
"+",
"self",
".",
"_secret",
")",
".",
"encode",
"(",
")",
")",
".",
"decode",
"(",
")",
"}",
"data",
"=",
"{",
"'grant_type'",
":",
"'client_credentials'",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"TOKEN_URL",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"obj",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"content",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"self",
".",
"_token",
"=",
"obj",
"[",
"'access_token'",
"]",
"self",
".",
"_token_expire_date",
"=",
"(",
"datetime",
".",
"now",
"(",
")",
"+",
"timedelta",
"(",
"minutes",
"=",
"self",
".",
"_expiery",
")",
")"
] | Get token from key and secret | [
"Get",
"token",
"from",
"key",
"and",
"secret"
] | 9c657fde1e91229c5878ea25530260596d296d37 | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L40-L54 | train |
persandstrom/python-vasttrafik | vasttrafik/journy_planner.py | JournyPlanner.location_nearbystops | def location_nearbystops(self, origin_coord_lat, origin_coord_long):
""" location.nearbystops """
response = self._request(
'location.nearbystops',
originCoordLat=origin_coord_lat,
originCoordLong=origin_coord_long)
return _get_node(response, 'LocationList', 'StopLocation') | python | def location_nearbystops(self, origin_coord_lat, origin_coord_long):
""" location.nearbystops """
response = self._request(
'location.nearbystops',
originCoordLat=origin_coord_lat,
originCoordLong=origin_coord_long)
return _get_node(response, 'LocationList', 'StopLocation') | [
"def",
"location_nearbystops",
"(",
"self",
",",
"origin_coord_lat",
",",
"origin_coord_long",
")",
":",
"response",
"=",
"self",
".",
"_request",
"(",
"'location.nearbystops'",
",",
"originCoordLat",
"=",
"origin_coord_lat",
",",
"originCoordLong",
"=",
"origin_coord_long",
")",
"return",
"_get_node",
"(",
"response",
",",
"'LocationList'",
",",
"'StopLocation'",
")"
] | location.nearbystops | [
"location",
".",
"nearbystops"
] | 9c657fde1e91229c5878ea25530260596d296d37 | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L64-L70 | train |
persandstrom/python-vasttrafik | vasttrafik/journy_planner.py | JournyPlanner.location_name | def location_name(self, name):
""" location.name """
response = self._request(
'location.name',
input=name)
return _get_node(response, 'LocationList', 'StopLocation') | python | def location_name(self, name):
""" location.name """
response = self._request(
'location.name',
input=name)
return _get_node(response, 'LocationList', 'StopLocation') | [
"def",
"location_name",
"(",
"self",
",",
"name",
")",
":",
"response",
"=",
"self",
".",
"_request",
"(",
"'location.name'",
",",
"input",
"=",
"name",
")",
"return",
"_get_node",
"(",
"response",
",",
"'LocationList'",
",",
"'StopLocation'",
")"
] | location.name | [
"location",
".",
"name"
] | 9c657fde1e91229c5878ea25530260596d296d37 | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L80-L85 | train |
Capitains/MyCapytain | MyCapytain/common/utils/_graph.py | expand_namespace | def expand_namespace(nsmap, string):
""" If the string starts with a known prefix in nsmap, replace it by full URI
:param nsmap: Dictionary of prefix -> uri of namespace
:param string: String in which to replace the namespace
:return: Expanded string with no namespace
"""
for ns in nsmap:
if isinstance(string, str) and isinstance(ns, str) and string.startswith(ns+":"):
return string.replace(ns+":", nsmap[ns])
return string | python | def expand_namespace(nsmap, string):
""" If the string starts with a known prefix in nsmap, replace it by full URI
:param nsmap: Dictionary of prefix -> uri of namespace
:param string: String in which to replace the namespace
:return: Expanded string with no namespace
"""
for ns in nsmap:
if isinstance(string, str) and isinstance(ns, str) and string.startswith(ns+":"):
return string.replace(ns+":", nsmap[ns])
return string | [
"def",
"expand_namespace",
"(",
"nsmap",
",",
"string",
")",
":",
"for",
"ns",
"in",
"nsmap",
":",
"if",
"isinstance",
"(",
"string",
",",
"str",
")",
"and",
"isinstance",
"(",
"ns",
",",
"str",
")",
"and",
"string",
".",
"startswith",
"(",
"ns",
"+",
"\":\"",
")",
":",
"return",
"string",
".",
"replace",
"(",
"ns",
"+",
"\":\"",
",",
"nsmap",
"[",
"ns",
"]",
")",
"return",
"string"
] | If the string starts with a known prefix in nsmap, replace it by full URI
:param nsmap: Dictionary of prefix -> uri of namespace
:param string: String in which to replace the namespace
:return: Expanded string with no namespace | [
"If",
"the",
"string",
"starts",
"with",
"a",
"known",
"prefix",
"in",
"nsmap",
"replace",
"it",
"by",
"full",
"URI"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_graph.py#L72-L82 | train |
Capitains/MyCapytain | MyCapytain/common/utils/_graph.py | Subgraph.graphiter | def graphiter(self, graph, target, ascendants=0, descendants=1):
""" Iter on a graph to finds object connected
:param graph: Graph to serialize
:type graph: Graph
:param target: Node to iterate over
:type target: Node
:param ascendants: Number of level to iter over upwards (-1 = No Limit)
:param descendants: Number of level to iter over downwards (-1 = No limit)
:return:
"""
asc = 0 + ascendants
if asc != 0:
asc -= 1
desc = 0 + descendants
if desc != 0:
desc -= 1
t = str(target)
if descendants != 0 and self.downwards[t] is True:
self.downwards[t] = False
for pred, obj in graph.predicate_objects(target):
if desc == 0 and isinstance(obj, BNode):
continue
self.add((target, pred, obj))
# Retrieve triples about the object
if desc != 0 and self.downwards[str(obj)] is True:
self.graphiter(graph, target=obj, ascendants=0, descendants=desc)
if ascendants != 0 and self.updwards[t] is True:
self.updwards[t] = False
for s, p in graph.subject_predicates(object=target):
if desc == 0 and isinstance(s, BNode):
continue
self.add((s, p, target))
# Retrieve triples about the parent as object
if asc != 0 and self.updwards[str(s)] is True:
self.graphiter(graph, target=s, ascendants=asc, descendants=0) | python | def graphiter(self, graph, target, ascendants=0, descendants=1):
""" Iter on a graph to finds object connected
:param graph: Graph to serialize
:type graph: Graph
:param target: Node to iterate over
:type target: Node
:param ascendants: Number of level to iter over upwards (-1 = No Limit)
:param descendants: Number of level to iter over downwards (-1 = No limit)
:return:
"""
asc = 0 + ascendants
if asc != 0:
asc -= 1
desc = 0 + descendants
if desc != 0:
desc -= 1
t = str(target)
if descendants != 0 and self.downwards[t] is True:
self.downwards[t] = False
for pred, obj in graph.predicate_objects(target):
if desc == 0 and isinstance(obj, BNode):
continue
self.add((target, pred, obj))
# Retrieve triples about the object
if desc != 0 and self.downwards[str(obj)] is True:
self.graphiter(graph, target=obj, ascendants=0, descendants=desc)
if ascendants != 0 and self.updwards[t] is True:
self.updwards[t] = False
for s, p in graph.subject_predicates(object=target):
if desc == 0 and isinstance(s, BNode):
continue
self.add((s, p, target))
# Retrieve triples about the parent as object
if asc != 0 and self.updwards[str(s)] is True:
self.graphiter(graph, target=s, ascendants=asc, descendants=0) | [
"def",
"graphiter",
"(",
"self",
",",
"graph",
",",
"target",
",",
"ascendants",
"=",
"0",
",",
"descendants",
"=",
"1",
")",
":",
"asc",
"=",
"0",
"+",
"ascendants",
"if",
"asc",
"!=",
"0",
":",
"asc",
"-=",
"1",
"desc",
"=",
"0",
"+",
"descendants",
"if",
"desc",
"!=",
"0",
":",
"desc",
"-=",
"1",
"t",
"=",
"str",
"(",
"target",
")",
"if",
"descendants",
"!=",
"0",
"and",
"self",
".",
"downwards",
"[",
"t",
"]",
"is",
"True",
":",
"self",
".",
"downwards",
"[",
"t",
"]",
"=",
"False",
"for",
"pred",
",",
"obj",
"in",
"graph",
".",
"predicate_objects",
"(",
"target",
")",
":",
"if",
"desc",
"==",
"0",
"and",
"isinstance",
"(",
"obj",
",",
"BNode",
")",
":",
"continue",
"self",
".",
"add",
"(",
"(",
"target",
",",
"pred",
",",
"obj",
")",
")",
"# Retrieve triples about the object",
"if",
"desc",
"!=",
"0",
"and",
"self",
".",
"downwards",
"[",
"str",
"(",
"obj",
")",
"]",
"is",
"True",
":",
"self",
".",
"graphiter",
"(",
"graph",
",",
"target",
"=",
"obj",
",",
"ascendants",
"=",
"0",
",",
"descendants",
"=",
"desc",
")",
"if",
"ascendants",
"!=",
"0",
"and",
"self",
".",
"updwards",
"[",
"t",
"]",
"is",
"True",
":",
"self",
".",
"updwards",
"[",
"t",
"]",
"=",
"False",
"for",
"s",
",",
"p",
"in",
"graph",
".",
"subject_predicates",
"(",
"object",
"=",
"target",
")",
":",
"if",
"desc",
"==",
"0",
"and",
"isinstance",
"(",
"s",
",",
"BNode",
")",
":",
"continue",
"self",
".",
"add",
"(",
"(",
"s",
",",
"p",
",",
"target",
")",
")",
"# Retrieve triples about the parent as object",
"if",
"asc",
"!=",
"0",
"and",
"self",
".",
"updwards",
"[",
"str",
"(",
"s",
")",
"]",
"is",
"True",
":",
"self",
".",
"graphiter",
"(",
"graph",
",",
"target",
"=",
"s",
",",
"ascendants",
"=",
"asc",
",",
"descendants",
"=",
"0",
")"
] | Iter on a graph to finds object connected
:param graph: Graph to serialize
:type graph: Graph
:param target: Node to iterate over
:type target: Node
:param ascendants: Number of level to iter over upwards (-1 = No Limit)
:param descendants: Number of level to iter over downwards (-1 = No limit)
:return: | [
"Iter",
"on",
"a",
"graph",
"to",
"finds",
"object",
"connected"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_graph.py#L21-L63 | train |
xflr6/features | features/tools.py | uniqued | def uniqued(iterable):
"""Return unique list of items preserving order.
>>> uniqued([3, 2, 1, 3, 2, 1, 0])
[3, 2, 1, 0]
"""
seen = set()
add = seen.add
return [i for i in iterable if i not in seen and not add(i)] | python | def uniqued(iterable):
"""Return unique list of items preserving order.
>>> uniqued([3, 2, 1, 3, 2, 1, 0])
[3, 2, 1, 0]
"""
seen = set()
add = seen.add
return [i for i in iterable if i not in seen and not add(i)] | [
"def",
"uniqued",
"(",
"iterable",
")",
":",
"seen",
"=",
"set",
"(",
")",
"add",
"=",
"seen",
".",
"add",
"return",
"[",
"i",
"for",
"i",
"in",
"iterable",
"if",
"i",
"not",
"in",
"seen",
"and",
"not",
"add",
"(",
"i",
")",
"]"
] | Return unique list of items preserving order.
>>> uniqued([3, 2, 1, 3, 2, 1, 0])
[3, 2, 1, 0] | [
"Return",
"unique",
"list",
"of",
"items",
"preserving",
"order",
"."
] | f985304dd642da6ecdc66d85167d00daa4efe5f4 | https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/tools.py#L10-L18 | train |
xflr6/features | features/tools.py | butlast | def butlast(iterable):
"""Yield all items from ``iterable`` except the last one.
>>> list(butlast(['spam', 'eggs', 'ham']))
['spam', 'eggs']
>>> list(butlast(['spam']))
[]
>>> list(butlast([]))
[]
"""
iterable = iter(iterable)
try:
first = next(iterable)
except StopIteration:
return
for second in iterable:
yield first
first = second | python | def butlast(iterable):
"""Yield all items from ``iterable`` except the last one.
>>> list(butlast(['spam', 'eggs', 'ham']))
['spam', 'eggs']
>>> list(butlast(['spam']))
[]
>>> list(butlast([]))
[]
"""
iterable = iter(iterable)
try:
first = next(iterable)
except StopIteration:
return
for second in iterable:
yield first
first = second | [
"def",
"butlast",
"(",
"iterable",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"try",
":",
"first",
"=",
"next",
"(",
"iterable",
")",
"except",
"StopIteration",
":",
"return",
"for",
"second",
"in",
"iterable",
":",
"yield",
"first",
"first",
"=",
"second"
] | Yield all items from ``iterable`` except the last one.
>>> list(butlast(['spam', 'eggs', 'ham']))
['spam', 'eggs']
>>> list(butlast(['spam']))
[]
>>> list(butlast([]))
[] | [
"Yield",
"all",
"items",
"from",
"iterable",
"except",
"the",
"last",
"one",
"."
] | f985304dd642da6ecdc66d85167d00daa4efe5f4 | https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/tools.py#L21-L40 | train |
xflr6/features | features/tools.py | generic_translate | def generic_translate(frm=None, to=None, delete=''):
"""Return a translate function for strings and unicode.
>>> translate = generic_translate('Hoy', 'Bad', 'r')
>>> translate('Holy grail')
'Bald gail'
>>> translate(u'Holy grail') == u'Bald gail'
True
"""
if PY2:
delete_dict = dict.fromkeys(ord(unicode(d)) for d in delete)
if frm is None and to is None:
string_trans = None
unicode_table = delete_dict
else:
string_trans = string.maketrans(frm, to)
unicode_table = dict(((ord(unicode(f)), unicode(t))
for f, t in zip(frm, to)), **delete_dict)
string_args = (string_trans, delete) if delete else (string_trans,)
translate_args = [string_args, (unicode_table,)]
def translate(basestr):
args = translate_args[isinstance(basestr, unicode)]
return basestr.translate(*args)
else:
string_trans = str.maketrans(frm or '', to or '', delete or '')
def translate(basestr):
return basestr.translate(string_trans)
return translate | python | def generic_translate(frm=None, to=None, delete=''):
"""Return a translate function for strings and unicode.
>>> translate = generic_translate('Hoy', 'Bad', 'r')
>>> translate('Holy grail')
'Bald gail'
>>> translate(u'Holy grail') == u'Bald gail'
True
"""
if PY2:
delete_dict = dict.fromkeys(ord(unicode(d)) for d in delete)
if frm is None and to is None:
string_trans = None
unicode_table = delete_dict
else:
string_trans = string.maketrans(frm, to)
unicode_table = dict(((ord(unicode(f)), unicode(t))
for f, t in zip(frm, to)), **delete_dict)
string_args = (string_trans, delete) if delete else (string_trans,)
translate_args = [string_args, (unicode_table,)]
def translate(basestr):
args = translate_args[isinstance(basestr, unicode)]
return basestr.translate(*args)
else:
string_trans = str.maketrans(frm or '', to or '', delete or '')
def translate(basestr):
return basestr.translate(string_trans)
return translate | [
"def",
"generic_translate",
"(",
"frm",
"=",
"None",
",",
"to",
"=",
"None",
",",
"delete",
"=",
"''",
")",
":",
"if",
"PY2",
":",
"delete_dict",
"=",
"dict",
".",
"fromkeys",
"(",
"ord",
"(",
"unicode",
"(",
"d",
")",
")",
"for",
"d",
"in",
"delete",
")",
"if",
"frm",
"is",
"None",
"and",
"to",
"is",
"None",
":",
"string_trans",
"=",
"None",
"unicode_table",
"=",
"delete_dict",
"else",
":",
"string_trans",
"=",
"string",
".",
"maketrans",
"(",
"frm",
",",
"to",
")",
"unicode_table",
"=",
"dict",
"(",
"(",
"(",
"ord",
"(",
"unicode",
"(",
"f",
")",
")",
",",
"unicode",
"(",
"t",
")",
")",
"for",
"f",
",",
"t",
"in",
"zip",
"(",
"frm",
",",
"to",
")",
")",
",",
"*",
"*",
"delete_dict",
")",
"string_args",
"=",
"(",
"string_trans",
",",
"delete",
")",
"if",
"delete",
"else",
"(",
"string_trans",
",",
")",
"translate_args",
"=",
"[",
"string_args",
",",
"(",
"unicode_table",
",",
")",
"]",
"def",
"translate",
"(",
"basestr",
")",
":",
"args",
"=",
"translate_args",
"[",
"isinstance",
"(",
"basestr",
",",
"unicode",
")",
"]",
"return",
"basestr",
".",
"translate",
"(",
"*",
"args",
")",
"else",
":",
"string_trans",
"=",
"str",
".",
"maketrans",
"(",
"frm",
"or",
"''",
",",
"to",
"or",
"''",
",",
"delete",
"or",
"''",
")",
"def",
"translate",
"(",
"basestr",
")",
":",
"return",
"basestr",
".",
"translate",
"(",
"string_trans",
")",
"return",
"translate"
] | Return a translate function for strings and unicode.
>>> translate = generic_translate('Hoy', 'Bad', 'r')
>>> translate('Holy grail')
'Bald gail'
>>> translate(u'Holy grail') == u'Bald gail'
True | [
"Return",
"a",
"translate",
"function",
"for",
"strings",
"and",
"unicode",
"."
] | f985304dd642da6ecdc66d85167d00daa4efe5f4 | https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/tools.py#L43-L79 | train |
etingof/pysnmpcrypto | pysnmpcrypto/des3.py | _cryptography_cipher | def _cryptography_cipher(key, iv):
"""Build a cryptography TripleDES Cipher object.
:param bytes key: Encryption key
:param bytesiv iv: Initialization vector
:returns: TripleDES Cipher instance
:rtype: cryptography.hazmat.primitives.ciphers.Cipher
"""
return Cipher(
algorithm=algorithms.TripleDES(key),
mode=modes.CBC(iv),
backend=default_backend()
) | python | def _cryptography_cipher(key, iv):
"""Build a cryptography TripleDES Cipher object.
:param bytes key: Encryption key
:param bytesiv iv: Initialization vector
:returns: TripleDES Cipher instance
:rtype: cryptography.hazmat.primitives.ciphers.Cipher
"""
return Cipher(
algorithm=algorithms.TripleDES(key),
mode=modes.CBC(iv),
backend=default_backend()
) | [
"def",
"_cryptography_cipher",
"(",
"key",
",",
"iv",
")",
":",
"return",
"Cipher",
"(",
"algorithm",
"=",
"algorithms",
".",
"TripleDES",
"(",
"key",
")",
",",
"mode",
"=",
"modes",
".",
"CBC",
"(",
"iv",
")",
",",
"backend",
"=",
"default_backend",
"(",
")",
")"
] | Build a cryptography TripleDES Cipher object.
:param bytes key: Encryption key
:param bytesiv iv: Initialization vector
:returns: TripleDES Cipher instance
:rtype: cryptography.hazmat.primitives.ciphers.Cipher | [
"Build",
"a",
"cryptography",
"TripleDES",
"Cipher",
"object",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/des3.py#L28-L40 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.