repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
ramses-tech/nefertari
|
nefertari/renderers.py
|
DefaultResponseRendererMixin._get_create_update_kwargs
|
def _get_create_update_kwargs(self, value, common_kw):
""" Get kwargs common to create, update, replace. """
kw = common_kw.copy()
kw['body'] = value
if '_self' in value:
kw['headers'] = [('Location', value['_self'])]
return kw
|
python
|
def _get_create_update_kwargs(self, value, common_kw):
""" Get kwargs common to create, update, replace. """
kw = common_kw.copy()
kw['body'] = value
if '_self' in value:
kw['headers'] = [('Location', value['_self'])]
return kw
|
[
"def",
"_get_create_update_kwargs",
"(",
"self",
",",
"value",
",",
"common_kw",
")",
":",
"kw",
"=",
"common_kw",
".",
"copy",
"(",
")",
"kw",
"[",
"'body'",
"]",
"=",
"value",
"if",
"'_self'",
"in",
"value",
":",
"kw",
"[",
"'headers'",
"]",
"=",
"[",
"(",
"'Location'",
",",
"value",
"[",
"'_self'",
"]",
")",
"]",
"return",
"kw"
] |
Get kwargs common to create, update, replace.
|
[
"Get",
"kwargs",
"common",
"to",
"create",
"update",
"replace",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L96-L102
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
DefaultResponseRendererMixin.render_create
|
def render_create(self, value, system, common_kw):
""" Render response for view `create` method (collection POST) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPCreated(**kw)
|
python
|
def render_create(self, value, system, common_kw):
""" Render response for view `create` method (collection POST) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPCreated(**kw)
|
[
"def",
"render_create",
"(",
"self",
",",
"value",
",",
"system",
",",
"common_kw",
")",
":",
"kw",
"=",
"self",
".",
"_get_create_update_kwargs",
"(",
"value",
",",
"common_kw",
")",
"return",
"JHTTPCreated",
"(",
"*",
"*",
"kw",
")"
] |
Render response for view `create` method (collection POST)
|
[
"Render",
"response",
"for",
"view",
"create",
"method",
"(",
"collection",
"POST",
")"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L104-L107
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
DefaultResponseRendererMixin.render_update
|
def render_update(self, value, system, common_kw):
""" Render response for view `update` method (item PATCH) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPOk('Updated', **kw)
|
python
|
def render_update(self, value, system, common_kw):
""" Render response for view `update` method (item PATCH) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPOk('Updated', **kw)
|
[
"def",
"render_update",
"(",
"self",
",",
"value",
",",
"system",
",",
"common_kw",
")",
":",
"kw",
"=",
"self",
".",
"_get_create_update_kwargs",
"(",
"value",
",",
"common_kw",
")",
"return",
"JHTTPOk",
"(",
"'Updated'",
",",
"*",
"*",
"kw",
")"
] |
Render response for view `update` method (item PATCH)
|
[
"Render",
"response",
"for",
"view",
"update",
"method",
"(",
"item",
"PATCH",
")"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L109-L112
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
DefaultResponseRendererMixin.render_delete_many
|
def render_delete_many(self, value, system, common_kw):
""" Render response for view `delete_many` method (collection DELETE)
"""
if isinstance(value, dict):
return JHTTPOk(extra=value)
msg = 'Deleted {} {}(s) objects'.format(
value, system['view'].Model.__name__)
return JHTTPOk(msg, **common_kw.copy())
|
python
|
def render_delete_many(self, value, system, common_kw):
""" Render response for view `delete_many` method (collection DELETE)
"""
if isinstance(value, dict):
return JHTTPOk(extra=value)
msg = 'Deleted {} {}(s) objects'.format(
value, system['view'].Model.__name__)
return JHTTPOk(msg, **common_kw.copy())
|
[
"def",
"render_delete_many",
"(",
"self",
",",
"value",
",",
"system",
",",
"common_kw",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"JHTTPOk",
"(",
"extra",
"=",
"value",
")",
"msg",
"=",
"'Deleted {} {}(s) objects'",
".",
"format",
"(",
"value",
",",
"system",
"[",
"'view'",
"]",
".",
"Model",
".",
"__name__",
")",
"return",
"JHTTPOk",
"(",
"msg",
",",
"*",
"*",
"common_kw",
".",
"copy",
"(",
")",
")"
] |
Render response for view `delete_many` method (collection DELETE)
|
[
"Render",
"response",
"for",
"view",
"delete_many",
"method",
"(",
"collection",
"DELETE",
")"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L122-L129
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
DefaultResponseRendererMixin.render_update_many
|
def render_update_many(self, value, system, common_kw):
""" Render response for view `update_many` method
(collection PUT/PATCH)
"""
msg = 'Updated {} {}(s) objects'.format(
value, system['view'].Model.__name__)
return JHTTPOk(msg, **common_kw.copy())
|
python
|
def render_update_many(self, value, system, common_kw):
""" Render response for view `update_many` method
(collection PUT/PATCH)
"""
msg = 'Updated {} {}(s) objects'.format(
value, system['view'].Model.__name__)
return JHTTPOk(msg, **common_kw.copy())
|
[
"def",
"render_update_many",
"(",
"self",
",",
"value",
",",
"system",
",",
"common_kw",
")",
":",
"msg",
"=",
"'Updated {} {}(s) objects'",
".",
"format",
"(",
"value",
",",
"system",
"[",
"'view'",
"]",
".",
"Model",
".",
"__name__",
")",
"return",
"JHTTPOk",
"(",
"msg",
",",
"*",
"*",
"common_kw",
".",
"copy",
"(",
")",
")"
] |
Render response for view `update_many` method
(collection PUT/PATCH)
|
[
"Render",
"response",
"for",
"view",
"update_many",
"method",
"(",
"collection",
"PUT",
"/",
"PATCH",
")"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L131-L137
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
DefaultResponseRendererMixin._render_response
|
def _render_response(self, value, system):
""" Handle response rendering.
Calls mixin methods according to request.action value.
"""
super_call = super(DefaultResponseRendererMixin, self)._render_response
try:
method_name = 'render_{}'.format(system['request'].action)
except (KeyError, AttributeError):
return super_call(value, system)
method = getattr(self, method_name, None)
if method is not None:
common_kw = self._get_common_kwargs(system)
response = method(value, system, common_kw)
system['request'].response = response
return
return super_call(value, system)
|
python
|
def _render_response(self, value, system):
""" Handle response rendering.
Calls mixin methods according to request.action value.
"""
super_call = super(DefaultResponseRendererMixin, self)._render_response
try:
method_name = 'render_{}'.format(system['request'].action)
except (KeyError, AttributeError):
return super_call(value, system)
method = getattr(self, method_name, None)
if method is not None:
common_kw = self._get_common_kwargs(system)
response = method(value, system, common_kw)
system['request'].response = response
return
return super_call(value, system)
|
[
"def",
"_render_response",
"(",
"self",
",",
"value",
",",
"system",
")",
":",
"super_call",
"=",
"super",
"(",
"DefaultResponseRendererMixin",
",",
"self",
")",
".",
"_render_response",
"try",
":",
"method_name",
"=",
"'render_{}'",
".",
"format",
"(",
"system",
"[",
"'request'",
"]",
".",
"action",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"return",
"super_call",
"(",
"value",
",",
"system",
")",
"method",
"=",
"getattr",
"(",
"self",
",",
"method_name",
",",
"None",
")",
"if",
"method",
"is",
"not",
"None",
":",
"common_kw",
"=",
"self",
".",
"_get_common_kwargs",
"(",
"system",
")",
"response",
"=",
"method",
"(",
"value",
",",
"system",
",",
"common_kw",
")",
"system",
"[",
"'request'",
"]",
".",
"response",
"=",
"response",
"return",
"return",
"super_call",
"(",
"value",
",",
"system",
")"
] |
Handle response rendering.
Calls mixin methods according to request.action value.
|
[
"Handle",
"response",
"rendering",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L139-L155
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/policies.py
|
ApiKeyAuthenticationPolicy.remember
|
def remember(self, request, username, **kw):
""" Returns 'WWW-Authenticate' header with a value that should be used
in 'Authorization' header.
"""
if self.credentials_callback:
token = self.credentials_callback(username, request)
api_key = 'ApiKey {}:{}'.format(username, token)
return [('WWW-Authenticate', api_key)]
|
python
|
def remember(self, request, username, **kw):
""" Returns 'WWW-Authenticate' header with a value that should be used
in 'Authorization' header.
"""
if self.credentials_callback:
token = self.credentials_callback(username, request)
api_key = 'ApiKey {}:{}'.format(username, token)
return [('WWW-Authenticate', api_key)]
|
[
"def",
"remember",
"(",
"self",
",",
"request",
",",
"username",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"credentials_callback",
":",
"token",
"=",
"self",
".",
"credentials_callback",
"(",
"username",
",",
"request",
")",
"api_key",
"=",
"'ApiKey {}:{}'",
".",
"format",
"(",
"username",
",",
"token",
")",
"return",
"[",
"(",
"'WWW-Authenticate'",
",",
"api_key",
")",
"]"
] |
Returns 'WWW-Authenticate' header with a value that should be used
in 'Authorization' header.
|
[
"Returns",
"WWW",
"-",
"Authenticate",
"header",
"with",
"a",
"value",
"that",
"should",
"be",
"used",
"in",
"Authorization",
"header",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L49-L56
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/policies.py
|
ApiKeyAuthenticationPolicy.callback
|
def callback(self, username, request):
""" Having :username: return user's identifiers or None. """
credentials = self._get_credentials(request)
if credentials:
username, api_key = credentials
if self.check:
return self.check(username, api_key, request)
|
python
|
def callback(self, username, request):
""" Having :username: return user's identifiers or None. """
credentials = self._get_credentials(request)
if credentials:
username, api_key = credentials
if self.check:
return self.check(username, api_key, request)
|
[
"def",
"callback",
"(",
"self",
",",
"username",
",",
"request",
")",
":",
"credentials",
"=",
"self",
".",
"_get_credentials",
"(",
"request",
")",
"if",
"credentials",
":",
"username",
",",
"api_key",
"=",
"credentials",
"if",
"self",
".",
"check",
":",
"return",
"self",
".",
"check",
"(",
"username",
",",
"api_key",
",",
"request",
")"
] |
Having :username: return user's identifiers or None.
|
[
"Having",
":",
"username",
":",
"return",
"user",
"s",
"identifiers",
"or",
"None",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L69-L75
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/policies.py
|
ApiKeyAuthenticationPolicy._get_credentials
|
def _get_credentials(self, request):
""" Extract username and api key token from 'Authorization' header """
authorization = request.headers.get('Authorization')
if not authorization:
return None
try:
authmeth, authbytes = authorization.split(' ', 1)
except ValueError: # not enough values to unpack
return None
if authmeth.lower() != 'apikey':
return None
if six.PY2 or isinstance(authbytes, bytes):
try:
auth = authbytes.decode('utf-8')
except UnicodeDecodeError:
auth = authbytes.decode('latin-1')
else:
auth = authbytes
try:
username, api_key = auth.split(':', 1)
except ValueError: # not enough values to unpack
return None
return username, api_key
|
python
|
def _get_credentials(self, request):
""" Extract username and api key token from 'Authorization' header """
authorization = request.headers.get('Authorization')
if not authorization:
return None
try:
authmeth, authbytes = authorization.split(' ', 1)
except ValueError: # not enough values to unpack
return None
if authmeth.lower() != 'apikey':
return None
if six.PY2 or isinstance(authbytes, bytes):
try:
auth = authbytes.decode('utf-8')
except UnicodeDecodeError:
auth = authbytes.decode('latin-1')
else:
auth = authbytes
try:
username, api_key = auth.split(':', 1)
except ValueError: # not enough values to unpack
return None
return username, api_key
|
[
"def",
"_get_credentials",
"(",
"self",
",",
"request",
")",
":",
"authorization",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Authorization'",
")",
"if",
"not",
"authorization",
":",
"return",
"None",
"try",
":",
"authmeth",
",",
"authbytes",
"=",
"authorization",
".",
"split",
"(",
"' '",
",",
"1",
")",
"except",
"ValueError",
":",
"# not enough values to unpack",
"return",
"None",
"if",
"authmeth",
".",
"lower",
"(",
")",
"!=",
"'apikey'",
":",
"return",
"None",
"if",
"six",
".",
"PY2",
"or",
"isinstance",
"(",
"authbytes",
",",
"bytes",
")",
":",
"try",
":",
"auth",
"=",
"authbytes",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"auth",
"=",
"authbytes",
".",
"decode",
"(",
"'latin-1'",
")",
"else",
":",
"auth",
"=",
"authbytes",
"try",
":",
"username",
",",
"api_key",
"=",
"auth",
".",
"split",
"(",
"':'",
",",
"1",
")",
"except",
"ValueError",
":",
"# not enough values to unpack",
"return",
"None",
"return",
"username",
",",
"api_key"
] |
Extract username and api key token from 'Authorization' header
|
[
"Extract",
"username",
"and",
"api",
"key",
"token",
"from",
"Authorization",
"header"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L77-L101
|
train
|
ramses-tech/nefertari
|
nefertari/events.py
|
_get_event_kwargs
|
def _get_event_kwargs(view_obj):
""" Helper function to get event kwargs.
:param view_obj: Instance of View that processes the request.
:returns dict: Containing event kwargs or None if events shouldn't
be fired.
"""
request = view_obj.request
view_method = getattr(view_obj, request.action)
do_trigger = not (
getattr(view_method, '_silent', False) or
getattr(view_obj, '_silent', False))
if do_trigger:
event_kwargs = {
'view': view_obj,
'model': view_obj.Model,
'fields': FieldData.from_dict(
view_obj._json_params,
view_obj.Model)
}
ctx = view_obj.context
if hasattr(ctx, 'pk_field') or isinstance(ctx, DataProxy):
event_kwargs['instance'] = ctx
return event_kwargs
|
python
|
def _get_event_kwargs(view_obj):
""" Helper function to get event kwargs.
:param view_obj: Instance of View that processes the request.
:returns dict: Containing event kwargs or None if events shouldn't
be fired.
"""
request = view_obj.request
view_method = getattr(view_obj, request.action)
do_trigger = not (
getattr(view_method, '_silent', False) or
getattr(view_obj, '_silent', False))
if do_trigger:
event_kwargs = {
'view': view_obj,
'model': view_obj.Model,
'fields': FieldData.from_dict(
view_obj._json_params,
view_obj.Model)
}
ctx = view_obj.context
if hasattr(ctx, 'pk_field') or isinstance(ctx, DataProxy):
event_kwargs['instance'] = ctx
return event_kwargs
|
[
"def",
"_get_event_kwargs",
"(",
"view_obj",
")",
":",
"request",
"=",
"view_obj",
".",
"request",
"view_method",
"=",
"getattr",
"(",
"view_obj",
",",
"request",
".",
"action",
")",
"do_trigger",
"=",
"not",
"(",
"getattr",
"(",
"view_method",
",",
"'_silent'",
",",
"False",
")",
"or",
"getattr",
"(",
"view_obj",
",",
"'_silent'",
",",
"False",
")",
")",
"if",
"do_trigger",
":",
"event_kwargs",
"=",
"{",
"'view'",
":",
"view_obj",
",",
"'model'",
":",
"view_obj",
".",
"Model",
",",
"'fields'",
":",
"FieldData",
".",
"from_dict",
"(",
"view_obj",
".",
"_json_params",
",",
"view_obj",
".",
"Model",
")",
"}",
"ctx",
"=",
"view_obj",
".",
"context",
"if",
"hasattr",
"(",
"ctx",
",",
"'pk_field'",
")",
"or",
"isinstance",
"(",
"ctx",
",",
"DataProxy",
")",
":",
"event_kwargs",
"[",
"'instance'",
"]",
"=",
"ctx",
"return",
"event_kwargs"
] |
Helper function to get event kwargs.
:param view_obj: Instance of View that processes the request.
:returns dict: Containing event kwargs or None if events shouldn't
be fired.
|
[
"Helper",
"function",
"to",
"get",
"event",
"kwargs",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L305-L330
|
train
|
ramses-tech/nefertari
|
nefertari/events.py
|
_get_event_cls
|
def _get_event_cls(view_obj, events_map):
""" Helper function to get event class.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Found event class.
"""
request = view_obj.request
view_method = getattr(view_obj, request.action)
event_action = (
getattr(view_method, '_event_action', None) or
request.action)
return events_map[event_action]
|
python
|
def _get_event_cls(view_obj, events_map):
""" Helper function to get event class.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Found event class.
"""
request = view_obj.request
view_method = getattr(view_obj, request.action)
event_action = (
getattr(view_method, '_event_action', None) or
request.action)
return events_map[event_action]
|
[
"def",
"_get_event_cls",
"(",
"view_obj",
",",
"events_map",
")",
":",
"request",
"=",
"view_obj",
".",
"request",
"view_method",
"=",
"getattr",
"(",
"view_obj",
",",
"request",
".",
"action",
")",
"event_action",
"=",
"(",
"getattr",
"(",
"view_method",
",",
"'_event_action'",
",",
"None",
")",
"or",
"request",
".",
"action",
")",
"return",
"events_map",
"[",
"event_action",
"]"
] |
Helper function to get event class.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Found event class.
|
[
"Helper",
"function",
"to",
"get",
"event",
"class",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L333-L346
|
train
|
ramses-tech/nefertari
|
nefertari/events.py
|
_trigger_events
|
def _trigger_events(view_obj, events_map, additional_kw=None):
""" Common logic to trigger before/after events.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Instance if triggered event.
"""
if additional_kw is None:
additional_kw = {}
event_kwargs = _get_event_kwargs(view_obj)
if event_kwargs is None:
return
event_kwargs.update(additional_kw)
event_cls = _get_event_cls(view_obj, events_map)
event = event_cls(**event_kwargs)
view_obj.request.registry.notify(event)
return event
|
python
|
def _trigger_events(view_obj, events_map, additional_kw=None):
""" Common logic to trigger before/after events.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Instance if triggered event.
"""
if additional_kw is None:
additional_kw = {}
event_kwargs = _get_event_kwargs(view_obj)
if event_kwargs is None:
return
event_kwargs.update(additional_kw)
event_cls = _get_event_cls(view_obj, events_map)
event = event_cls(**event_kwargs)
view_obj.request.registry.notify(event)
return event
|
[
"def",
"_trigger_events",
"(",
"view_obj",
",",
"events_map",
",",
"additional_kw",
"=",
"None",
")",
":",
"if",
"additional_kw",
"is",
"None",
":",
"additional_kw",
"=",
"{",
"}",
"event_kwargs",
"=",
"_get_event_kwargs",
"(",
"view_obj",
")",
"if",
"event_kwargs",
"is",
"None",
":",
"return",
"event_kwargs",
".",
"update",
"(",
"additional_kw",
")",
"event_cls",
"=",
"_get_event_cls",
"(",
"view_obj",
",",
"events_map",
")",
"event",
"=",
"event_cls",
"(",
"*",
"*",
"event_kwargs",
")",
"view_obj",
".",
"request",
".",
"registry",
".",
"notify",
"(",
"event",
")",
"return",
"event"
] |
Common logic to trigger before/after events.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Instance if triggered event.
|
[
"Common",
"logic",
"to",
"trigger",
"before",
"/",
"after",
"events",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L349-L368
|
train
|
ramses-tech/nefertari
|
nefertari/events.py
|
subscribe_to_events
|
def subscribe_to_events(config, subscriber, events, model=None):
""" Helper function to subscribe to group of events.
:param config: Pyramid contig instance.
:param subscriber: Event subscriber function.
:param events: Sequence of events to subscribe to.
:param model: Model predicate value.
"""
kwargs = {}
if model is not None:
kwargs['model'] = model
for evt in events:
config.add_subscriber(subscriber, evt, **kwargs)
|
python
|
def subscribe_to_events(config, subscriber, events, model=None):
""" Helper function to subscribe to group of events.
:param config: Pyramid contig instance.
:param subscriber: Event subscriber function.
:param events: Sequence of events to subscribe to.
:param model: Model predicate value.
"""
kwargs = {}
if model is not None:
kwargs['model'] = model
for evt in events:
config.add_subscriber(subscriber, evt, **kwargs)
|
[
"def",
"subscribe_to_events",
"(",
"config",
",",
"subscriber",
",",
"events",
",",
"model",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"model",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'model'",
"]",
"=",
"model",
"for",
"evt",
"in",
"events",
":",
"config",
".",
"add_subscriber",
"(",
"subscriber",
",",
"evt",
",",
"*",
"*",
"kwargs",
")"
] |
Helper function to subscribe to group of events.
:param config: Pyramid contig instance.
:param subscriber: Event subscriber function.
:param events: Sequence of events to subscribe to.
:param model: Model predicate value.
|
[
"Helper",
"function",
"to",
"subscribe",
"to",
"group",
"of",
"events",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L393-L406
|
train
|
ramses-tech/nefertari
|
nefertari/events.py
|
add_field_processors
|
def add_field_processors(config, processors, model, field):
""" Add processors for model field.
Under the hood, regular nefertari event subscribed is created which
calls field processors in order passed to this function.
Processors are passed following params:
* **new_value**: New value of of field.
* **instance**: Instance affected by request. Is None when set of
items is updated in bulk and when item is created.
* **field**: Instance of nefertari.utils.data.FieldData instance
containing data of changed field.
* **request**: Current Pyramid Request instance.
* **model**: Model class affected by request.
* **event**: Underlying event object.
Each processor must return processed value which is passed to next
processor.
:param config: Pyramid Congurator instance.
:param processors: Sequence of processor functions.
:param model: Model class for field if which processors are
registered.
:param field: Field name for which processors are registered.
"""
before_change_events = (
BeforeCreate,
BeforeUpdate,
BeforeReplace,
BeforeUpdateMany,
BeforeRegister,
)
def wrapper(event, _processors=processors, _field=field):
proc_kw = {
'new_value': event.field.new_value,
'instance': event.instance,
'field': event.field,
'request': event.view.request,
'model': event.model,
'event': event,
}
for proc_func in _processors:
proc_kw['new_value'] = proc_func(**proc_kw)
event.field.new_value = proc_kw['new_value']
event.set_field_value(_field, proc_kw['new_value'])
for evt in before_change_events:
config.add_subscriber(wrapper, evt, model=model, field=field)
|
python
|
def add_field_processors(config, processors, model, field):
""" Add processors for model field.
Under the hood, regular nefertari event subscribed is created which
calls field processors in order passed to this function.
Processors are passed following params:
* **new_value**: New value of of field.
* **instance**: Instance affected by request. Is None when set of
items is updated in bulk and when item is created.
* **field**: Instance of nefertari.utils.data.FieldData instance
containing data of changed field.
* **request**: Current Pyramid Request instance.
* **model**: Model class affected by request.
* **event**: Underlying event object.
Each processor must return processed value which is passed to next
processor.
:param config: Pyramid Congurator instance.
:param processors: Sequence of processor functions.
:param model: Model class for field if which processors are
registered.
:param field: Field name for which processors are registered.
"""
before_change_events = (
BeforeCreate,
BeforeUpdate,
BeforeReplace,
BeforeUpdateMany,
BeforeRegister,
)
def wrapper(event, _processors=processors, _field=field):
proc_kw = {
'new_value': event.field.new_value,
'instance': event.instance,
'field': event.field,
'request': event.view.request,
'model': event.model,
'event': event,
}
for proc_func in _processors:
proc_kw['new_value'] = proc_func(**proc_kw)
event.field.new_value = proc_kw['new_value']
event.set_field_value(_field, proc_kw['new_value'])
for evt in before_change_events:
config.add_subscriber(wrapper, evt, model=model, field=field)
|
[
"def",
"add_field_processors",
"(",
"config",
",",
"processors",
",",
"model",
",",
"field",
")",
":",
"before_change_events",
"=",
"(",
"BeforeCreate",
",",
"BeforeUpdate",
",",
"BeforeReplace",
",",
"BeforeUpdateMany",
",",
"BeforeRegister",
",",
")",
"def",
"wrapper",
"(",
"event",
",",
"_processors",
"=",
"processors",
",",
"_field",
"=",
"field",
")",
":",
"proc_kw",
"=",
"{",
"'new_value'",
":",
"event",
".",
"field",
".",
"new_value",
",",
"'instance'",
":",
"event",
".",
"instance",
",",
"'field'",
":",
"event",
".",
"field",
",",
"'request'",
":",
"event",
".",
"view",
".",
"request",
",",
"'model'",
":",
"event",
".",
"model",
",",
"'event'",
":",
"event",
",",
"}",
"for",
"proc_func",
"in",
"_processors",
":",
"proc_kw",
"[",
"'new_value'",
"]",
"=",
"proc_func",
"(",
"*",
"*",
"proc_kw",
")",
"event",
".",
"field",
".",
"new_value",
"=",
"proc_kw",
"[",
"'new_value'",
"]",
"event",
".",
"set_field_value",
"(",
"_field",
",",
"proc_kw",
"[",
"'new_value'",
"]",
")",
"for",
"evt",
"in",
"before_change_events",
":",
"config",
".",
"add_subscriber",
"(",
"wrapper",
",",
"evt",
",",
"model",
"=",
"model",
",",
"field",
"=",
"field",
")"
] |
Add processors for model field.
Under the hood, regular nefertari event subscribed is created which
calls field processors in order passed to this function.
Processors are passed following params:
* **new_value**: New value of of field.
* **instance**: Instance affected by request. Is None when set of
items is updated in bulk and when item is created.
* **field**: Instance of nefertari.utils.data.FieldData instance
containing data of changed field.
* **request**: Current Pyramid Request instance.
* **model**: Model class affected by request.
* **event**: Underlying event object.
Each processor must return processed value which is passed to next
processor.
:param config: Pyramid Congurator instance.
:param processors: Sequence of processor functions.
:param model: Model class for field if which processors are
registered.
:param field: Field name for which processors are registered.
|
[
"Add",
"processors",
"for",
"model",
"field",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L409-L459
|
train
|
ramses-tech/nefertari
|
nefertari/events.py
|
BeforeEvent.set_field_value
|
def set_field_value(self, field_name, value):
""" Set value of request field named `field_name`.
Use this method to apply changes to object which is affected
by request. Values are set on `view._json_params` dict.
If `field_name` is not affected by request, it is added to
`self.fields` which makes field processors which are connected
to `field_name` to be triggered, if they are run after this
method call(connected to events after handler that performs
method call).
:param field_name: Name of request field value of which should
be set.
:param value: Value to be set.
"""
self.view._json_params[field_name] = value
if field_name in self.fields:
self.fields[field_name].new_value = value
return
fields = FieldData.from_dict({field_name: value}, self.model)
self.fields.update(fields)
|
python
|
def set_field_value(self, field_name, value):
""" Set value of request field named `field_name`.
Use this method to apply changes to object which is affected
by request. Values are set on `view._json_params` dict.
If `field_name` is not affected by request, it is added to
`self.fields` which makes field processors which are connected
to `field_name` to be triggered, if they are run after this
method call(connected to events after handler that performs
method call).
:param field_name: Name of request field value of which should
be set.
:param value: Value to be set.
"""
self.view._json_params[field_name] = value
if field_name in self.fields:
self.fields[field_name].new_value = value
return
fields = FieldData.from_dict({field_name: value}, self.model)
self.fields.update(fields)
|
[
"def",
"set_field_value",
"(",
"self",
",",
"field_name",
",",
"value",
")",
":",
"self",
".",
"view",
".",
"_json_params",
"[",
"field_name",
"]",
"=",
"value",
"if",
"field_name",
"in",
"self",
".",
"fields",
":",
"self",
".",
"fields",
"[",
"field_name",
"]",
".",
"new_value",
"=",
"value",
"return",
"fields",
"=",
"FieldData",
".",
"from_dict",
"(",
"{",
"field_name",
":",
"value",
"}",
",",
"self",
".",
"model",
")",
"self",
".",
"fields",
".",
"update",
"(",
"fields",
")"
] |
Set value of request field named `field_name`.
Use this method to apply changes to object which is affected
by request. Values are set on `view._json_params` dict.
If `field_name` is not affected by request, it is added to
`self.fields` which makes field processors which are connected
to `field_name` to be triggered, if they are run after this
method call(connected to events after handler that performs
method call).
:param field_name: Name of request field value of which should
be set.
:param value: Value to be set.
|
[
"Set",
"value",
"of",
"request",
"field",
"named",
"field_name",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L46-L68
|
train
|
ramses-tech/nefertari
|
nefertari/events.py
|
AfterEvent.set_field_value
|
def set_field_value(self, field_name, value):
""" Set value of response field named `field_name`.
If response contains single item, its field is set.
If response contains multiple items, all the items in response
are edited.
To edit response meta(e.g. 'count') edit response directly at
`event.response`.
:param field_name: Name of response field value of which should
be set.
:param value: Value to be set.
"""
if self.response is None:
return
if 'data' in self.response:
items = self.response['data']
else:
items = [self.response]
for item in items:
item[field_name] = value
|
python
|
def set_field_value(self, field_name, value):
""" Set value of response field named `field_name`.
If response contains single item, its field is set.
If response contains multiple items, all the items in response
are edited.
To edit response meta(e.g. 'count') edit response directly at
`event.response`.
:param field_name: Name of response field value of which should
be set.
:param value: Value to be set.
"""
if self.response is None:
return
if 'data' in self.response:
items = self.response['data']
else:
items = [self.response]
for item in items:
item[field_name] = value
|
[
"def",
"set_field_value",
"(",
"self",
",",
"field_name",
",",
"value",
")",
":",
"if",
"self",
".",
"response",
"is",
"None",
":",
"return",
"if",
"'data'",
"in",
"self",
".",
"response",
":",
"items",
"=",
"self",
".",
"response",
"[",
"'data'",
"]",
"else",
":",
"items",
"=",
"[",
"self",
".",
"response",
"]",
"for",
"item",
"in",
"items",
":",
"item",
"[",
"field_name",
"]",
"=",
"value"
] |
Set value of response field named `field_name`.
If response contains single item, its field is set.
If response contains multiple items, all the items in response
are edited.
To edit response meta(e.g. 'count') edit response directly at
`event.response`.
:param field_name: Name of response field value of which should
be set.
:param value: Value to be set.
|
[
"Set",
"value",
"of",
"response",
"field",
"named",
"field_name",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L76-L98
|
train
|
ramses-tech/nefertari
|
nefertari/elasticsearch.py
|
process_fields_param
|
def process_fields_param(fields):
""" Process 'fields' ES param.
* Fields list is split if needed
* '_type' field is added, if not present, so the actual value is
displayed instead of 'None'
"""
if not fields:
return fields
if isinstance(fields, six.string_types):
fields = split_strip(fields)
if '_type' not in fields:
fields.append('_type')
return {
'_source_include': fields,
'_source': True,
}
|
python
|
def process_fields_param(fields):
""" Process 'fields' ES param.
* Fields list is split if needed
* '_type' field is added, if not present, so the actual value is
displayed instead of 'None'
"""
if not fields:
return fields
if isinstance(fields, six.string_types):
fields = split_strip(fields)
if '_type' not in fields:
fields.append('_type')
return {
'_source_include': fields,
'_source': True,
}
|
[
"def",
"process_fields_param",
"(",
"fields",
")",
":",
"if",
"not",
"fields",
":",
"return",
"fields",
"if",
"isinstance",
"(",
"fields",
",",
"six",
".",
"string_types",
")",
":",
"fields",
"=",
"split_strip",
"(",
"fields",
")",
"if",
"'_type'",
"not",
"in",
"fields",
":",
"fields",
".",
"append",
"(",
"'_type'",
")",
"return",
"{",
"'_source_include'",
":",
"fields",
",",
"'_source'",
":",
"True",
",",
"}"
] |
Process 'fields' ES param.
* Fields list is split if needed
* '_type' field is added, if not present, so the actual value is
displayed instead of 'None'
|
[
"Process",
"fields",
"ES",
"param",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L98-L114
|
train
|
ramses-tech/nefertari
|
nefertari/elasticsearch.py
|
ESHttpConnection._catch_index_error
|
def _catch_index_error(self, response):
""" Catch and raise index errors which are not critical and thus
not raised by elasticsearch-py.
"""
code, headers, raw_data = response
if not raw_data:
return
data = json.loads(raw_data)
if not data or not data.get('errors'):
return
try:
error_dict = data['items'][0]['index']
message = error_dict['error']
except (KeyError, IndexError):
return
raise exception_response(400, detail=message)
|
python
|
def _catch_index_error(self, response):
""" Catch and raise index errors which are not critical and thus
not raised by elasticsearch-py.
"""
code, headers, raw_data = response
if not raw_data:
return
data = json.loads(raw_data)
if not data or not data.get('errors'):
return
try:
error_dict = data['items'][0]['index']
message = error_dict['error']
except (KeyError, IndexError):
return
raise exception_response(400, detail=message)
|
[
"def",
"_catch_index_error",
"(",
"self",
",",
"response",
")",
":",
"code",
",",
"headers",
",",
"raw_data",
"=",
"response",
"if",
"not",
"raw_data",
":",
"return",
"data",
"=",
"json",
".",
"loads",
"(",
"raw_data",
")",
"if",
"not",
"data",
"or",
"not",
"data",
".",
"get",
"(",
"'errors'",
")",
":",
"return",
"try",
":",
"error_dict",
"=",
"data",
"[",
"'items'",
"]",
"[",
"0",
"]",
"[",
"'index'",
"]",
"message",
"=",
"error_dict",
"[",
"'error'",
"]",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"return",
"raise",
"exception_response",
"(",
"400",
",",
"detail",
"=",
"message",
")"
] |
Catch and raise index errors which are not critical and thus
not raised by elasticsearch-py.
|
[
"Catch",
"and",
"raise",
"index",
"errors",
"which",
"are",
"not",
"critical",
"and",
"thus",
"not",
"raised",
"by",
"elasticsearch",
"-",
"py",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L25-L40
|
train
|
ramses-tech/nefertari
|
nefertari/elasticsearch.py
|
ES.setup_mappings
|
def setup_mappings(cls, force=False):
""" Setup ES mappings for all existing models.
This method is meant to be run once at application lauch.
ES._mappings_setup flag is set to not run make mapping creation
calls on subsequent runs.
Use `force=True` to make subsequent calls perform mapping
creation calls to ES.
"""
if getattr(cls, '_mappings_setup', False) and not force:
log.debug('ES mappings have been already set up for currently '
'running application. Call `setup_mappings` with '
'`force=True` to perform mappings set up again.')
return
log.info('Setting up ES mappings for all existing models')
models = engine.get_document_classes()
try:
for model_name, model_cls in models.items():
if getattr(model_cls, '_index_enabled', False):
es = cls(model_cls.__name__)
es.put_mapping(body=model_cls.get_es_mapping())
except JHTTPBadRequest as ex:
raise Exception(ex.json['extra']['data'])
cls._mappings_setup = True
|
python
|
def setup_mappings(cls, force=False):
""" Setup ES mappings for all existing models.
This method is meant to be run once at application lauch.
ES._mappings_setup flag is set to not run make mapping creation
calls on subsequent runs.
Use `force=True` to make subsequent calls perform mapping
creation calls to ES.
"""
if getattr(cls, '_mappings_setup', False) and not force:
log.debug('ES mappings have been already set up for currently '
'running application. Call `setup_mappings` with '
'`force=True` to perform mappings set up again.')
return
log.info('Setting up ES mappings for all existing models')
models = engine.get_document_classes()
try:
for model_name, model_cls in models.items():
if getattr(model_cls, '_index_enabled', False):
es = cls(model_cls.__name__)
es.put_mapping(body=model_cls.get_es_mapping())
except JHTTPBadRequest as ex:
raise Exception(ex.json['extra']['data'])
cls._mappings_setup = True
|
[
"def",
"setup_mappings",
"(",
"cls",
",",
"force",
"=",
"False",
")",
":",
"if",
"getattr",
"(",
"cls",
",",
"'_mappings_setup'",
",",
"False",
")",
"and",
"not",
"force",
":",
"log",
".",
"debug",
"(",
"'ES mappings have been already set up for currently '",
"'running application. Call `setup_mappings` with '",
"'`force=True` to perform mappings set up again.'",
")",
"return",
"log",
".",
"info",
"(",
"'Setting up ES mappings for all existing models'",
")",
"models",
"=",
"engine",
".",
"get_document_classes",
"(",
")",
"try",
":",
"for",
"model_name",
",",
"model_cls",
"in",
"models",
".",
"items",
"(",
")",
":",
"if",
"getattr",
"(",
"model_cls",
",",
"'_index_enabled'",
",",
"False",
")",
":",
"es",
"=",
"cls",
"(",
"model_cls",
".",
"__name__",
")",
"es",
".",
"put_mapping",
"(",
"body",
"=",
"model_cls",
".",
"get_es_mapping",
"(",
")",
")",
"except",
"JHTTPBadRequest",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"ex",
".",
"json",
"[",
"'extra'",
"]",
"[",
"'data'",
"]",
")",
"cls",
".",
"_mappings_setup",
"=",
"True"
] |
Setup ES mappings for all existing models.
This method is meant to be run once at application lauch.
ES._mappings_setup flag is set to not run make mapping creation
calls on subsequent runs.
Use `force=True` to make subsequent calls perform mapping
creation calls to ES.
|
[
"Setup",
"ES",
"mappings",
"for",
"all",
"existing",
"models",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L226-L250
|
train
|
ramses-tech/nefertari
|
nefertari/elasticsearch.py
|
ES.process_chunks
|
def process_chunks(self, documents, operation):
""" Apply `operation` to chunks of `documents` of size
`self.chunk_size`.
"""
chunk_size = self.chunk_size
start = end = 0
count = len(documents)
while count:
if count < chunk_size:
chunk_size = count
end += chunk_size
bulk = documents[start:end]
operation(documents_actions=bulk)
start += chunk_size
count -= chunk_size
|
python
|
def process_chunks(self, documents, operation):
""" Apply `operation` to chunks of `documents` of size
`self.chunk_size`.
"""
chunk_size = self.chunk_size
start = end = 0
count = len(documents)
while count:
if count < chunk_size:
chunk_size = count
end += chunk_size
bulk = documents[start:end]
operation(documents_actions=bulk)
start += chunk_size
count -= chunk_size
|
[
"def",
"process_chunks",
"(",
"self",
",",
"documents",
",",
"operation",
")",
":",
"chunk_size",
"=",
"self",
".",
"chunk_size",
"start",
"=",
"end",
"=",
"0",
"count",
"=",
"len",
"(",
"documents",
")",
"while",
"count",
":",
"if",
"count",
"<",
"chunk_size",
":",
"chunk_size",
"=",
"count",
"end",
"+=",
"chunk_size",
"bulk",
"=",
"documents",
"[",
"start",
":",
"end",
"]",
"operation",
"(",
"documents_actions",
"=",
"bulk",
")",
"start",
"+=",
"chunk_size",
"count",
"-=",
"chunk_size"
] |
Apply `operation` to chunks of `documents` of size
`self.chunk_size`.
|
[
"Apply",
"operation",
"to",
"chunks",
"of",
"documents",
"of",
"size",
"self",
".",
"chunk_size",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L259-L277
|
train
|
ramses-tech/nefertari
|
nefertari/elasticsearch.py
|
ES.index_missing_documents
|
def index_missing_documents(self, documents, request=None):
""" Index documents that are missing from ES index.
Determines which documents are missing using ES `mget` call which
returns a list of document IDs as `documents`. Then missing
`documents` from that list are indexed.
"""
log.info('Trying to index documents of type `{}` missing from '
'`{}` index'.format(self.doc_type, self.index_name))
if not documents:
log.info('No documents to index')
return
query_kwargs = dict(
index=self.index_name,
doc_type=self.doc_type,
fields=['_id'],
body={'ids': [d['_pk'] for d in documents]},
)
try:
response = self.api.mget(**query_kwargs)
except IndexNotFoundException:
indexed_ids = set()
else:
indexed_ids = set(
d['_id'] for d in response['docs'] if d.get('found'))
documents = [d for d in documents if str(d['_pk']) not in indexed_ids]
if not documents:
log.info('No documents of type `{}` are missing from '
'index `{}`'.format(self.doc_type, self.index_name))
return
self._bulk('index', documents, request)
|
python
|
def index_missing_documents(self, documents, request=None):
""" Index documents that are missing from ES index.
Determines which documents are missing using ES `mget` call which
returns a list of document IDs as `documents`. Then missing
`documents` from that list are indexed.
"""
log.info('Trying to index documents of type `{}` missing from '
'`{}` index'.format(self.doc_type, self.index_name))
if not documents:
log.info('No documents to index')
return
query_kwargs = dict(
index=self.index_name,
doc_type=self.doc_type,
fields=['_id'],
body={'ids': [d['_pk'] for d in documents]},
)
try:
response = self.api.mget(**query_kwargs)
except IndexNotFoundException:
indexed_ids = set()
else:
indexed_ids = set(
d['_id'] for d in response['docs'] if d.get('found'))
documents = [d for d in documents if str(d['_pk']) not in indexed_ids]
if not documents:
log.info('No documents of type `{}` are missing from '
'index `{}`'.format(self.doc_type, self.index_name))
return
self._bulk('index', documents, request)
|
[
"def",
"index_missing_documents",
"(",
"self",
",",
"documents",
",",
"request",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Trying to index documents of type `{}` missing from '",
"'`{}` index'",
".",
"format",
"(",
"self",
".",
"doc_type",
",",
"self",
".",
"index_name",
")",
")",
"if",
"not",
"documents",
":",
"log",
".",
"info",
"(",
"'No documents to index'",
")",
"return",
"query_kwargs",
"=",
"dict",
"(",
"index",
"=",
"self",
".",
"index_name",
",",
"doc_type",
"=",
"self",
".",
"doc_type",
",",
"fields",
"=",
"[",
"'_id'",
"]",
",",
"body",
"=",
"{",
"'ids'",
":",
"[",
"d",
"[",
"'_pk'",
"]",
"for",
"d",
"in",
"documents",
"]",
"}",
",",
")",
"try",
":",
"response",
"=",
"self",
".",
"api",
".",
"mget",
"(",
"*",
"*",
"query_kwargs",
")",
"except",
"IndexNotFoundException",
":",
"indexed_ids",
"=",
"set",
"(",
")",
"else",
":",
"indexed_ids",
"=",
"set",
"(",
"d",
"[",
"'_id'",
"]",
"for",
"d",
"in",
"response",
"[",
"'docs'",
"]",
"if",
"d",
".",
"get",
"(",
"'found'",
")",
")",
"documents",
"=",
"[",
"d",
"for",
"d",
"in",
"documents",
"if",
"str",
"(",
"d",
"[",
"'_pk'",
"]",
")",
"not",
"in",
"indexed_ids",
"]",
"if",
"not",
"documents",
":",
"log",
".",
"info",
"(",
"'No documents of type `{}` are missing from '",
"'index `{}`'",
".",
"format",
"(",
"self",
".",
"doc_type",
",",
"self",
".",
"index_name",
")",
")",
"return",
"self",
".",
"_bulk",
"(",
"'index'",
",",
"documents",
",",
"request",
")"
] |
Index documents that are missing from ES index.
Determines which documents are missing using ES `mget` call which
returns a list of document IDs as `documents`. Then missing
`documents` from that list are indexed.
|
[
"Index",
"documents",
"that",
"are",
"missing",
"from",
"ES",
"index",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L326-L358
|
train
|
ramses-tech/nefertari
|
nefertari/elasticsearch.py
|
ES.aggregate
|
def aggregate(self, **params):
""" Perform aggreration
Arguments:
:_aggregations_params: Dict of aggregation params. Root key is an
aggregation name. Required.
:_raise_on_empty: Boolean indicating whether to raise exception
when IndexNotFoundException exception happens. Optional,
defaults to False.
"""
_aggregations_params = params.pop('_aggregations_params', None)
_raise_on_empty = params.pop('_raise_on_empty', False)
if not _aggregations_params:
raise Exception('Missing _aggregations_params')
# Set limit so ES won't complain. It is ignored in the end
params['_limit'] = 0
search_params = self.build_search_params(params)
search_params.pop('size', None)
search_params.pop('from_', None)
search_params.pop('sort', None)
search_params['body']['aggregations'] = _aggregations_params
log.debug('Performing aggregation: {}'.format(_aggregations_params))
try:
response = self.api.search(**search_params)
except IndexNotFoundException:
if _raise_on_empty:
raise JHTTPNotFound(
'Aggregation failed: Index does not exist')
return {}
try:
return response['aggregations']
except KeyError:
raise JHTTPNotFound('No aggregations returned from ES')
|
python
|
def aggregate(self, **params):
""" Perform aggreration
Arguments:
:_aggregations_params: Dict of aggregation params. Root key is an
aggregation name. Required.
:_raise_on_empty: Boolean indicating whether to raise exception
when IndexNotFoundException exception happens. Optional,
defaults to False.
"""
_aggregations_params = params.pop('_aggregations_params', None)
_raise_on_empty = params.pop('_raise_on_empty', False)
if not _aggregations_params:
raise Exception('Missing _aggregations_params')
# Set limit so ES won't complain. It is ignored in the end
params['_limit'] = 0
search_params = self.build_search_params(params)
search_params.pop('size', None)
search_params.pop('from_', None)
search_params.pop('sort', None)
search_params['body']['aggregations'] = _aggregations_params
log.debug('Performing aggregation: {}'.format(_aggregations_params))
try:
response = self.api.search(**search_params)
except IndexNotFoundException:
if _raise_on_empty:
raise JHTTPNotFound(
'Aggregation failed: Index does not exist')
return {}
try:
return response['aggregations']
except KeyError:
raise JHTTPNotFound('No aggregations returned from ES')
|
[
"def",
"aggregate",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_aggregations_params",
"=",
"params",
".",
"pop",
"(",
"'_aggregations_params'",
",",
"None",
")",
"_raise_on_empty",
"=",
"params",
".",
"pop",
"(",
"'_raise_on_empty'",
",",
"False",
")",
"if",
"not",
"_aggregations_params",
":",
"raise",
"Exception",
"(",
"'Missing _aggregations_params'",
")",
"# Set limit so ES won't complain. It is ignored in the end",
"params",
"[",
"'_limit'",
"]",
"=",
"0",
"search_params",
"=",
"self",
".",
"build_search_params",
"(",
"params",
")",
"search_params",
".",
"pop",
"(",
"'size'",
",",
"None",
")",
"search_params",
".",
"pop",
"(",
"'from_'",
",",
"None",
")",
"search_params",
".",
"pop",
"(",
"'sort'",
",",
"None",
")",
"search_params",
"[",
"'body'",
"]",
"[",
"'aggregations'",
"]",
"=",
"_aggregations_params",
"log",
".",
"debug",
"(",
"'Performing aggregation: {}'",
".",
"format",
"(",
"_aggregations_params",
")",
")",
"try",
":",
"response",
"=",
"self",
".",
"api",
".",
"search",
"(",
"*",
"*",
"search_params",
")",
"except",
"IndexNotFoundException",
":",
"if",
"_raise_on_empty",
":",
"raise",
"JHTTPNotFound",
"(",
"'Aggregation failed: Index does not exist'",
")",
"return",
"{",
"}",
"try",
":",
"return",
"response",
"[",
"'aggregations'",
"]",
"except",
"KeyError",
":",
"raise",
"JHTTPNotFound",
"(",
"'No aggregations returned from ES'",
")"
] |
Perform aggreration
Arguments:
:_aggregations_params: Dict of aggregation params. Root key is an
aggregation name. Required.
:_raise_on_empty: Boolean indicating whether to raise exception
when IndexNotFoundException exception happens. Optional,
defaults to False.
|
[
"Perform",
"aggreration"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L493-L530
|
train
|
ramses-tech/nefertari
|
nefertari/elasticsearch.py
|
ES.bulk_index_relations
|
def bulk_index_relations(cls, items, request=None, **kwargs):
""" Index objects related to :items: in bulk.
Related items are first grouped in map
{model_name: {item1, item2, ...}} and then indexed.
:param items: Sequence of DB objects related objects if which
should be indexed.
:param request: Pyramid Request instance.
"""
index_map = defaultdict(set)
for item in items:
relations = item.get_related_documents(**kwargs)
for model_cls, related_items in relations:
indexable = getattr(model_cls, '_index_enabled', False)
if indexable and related_items:
index_map[model_cls.__name__].update(related_items)
for model_name, instances in index_map.items():
cls(model_name).index(to_dicts(instances), request=request)
|
python
|
def bulk_index_relations(cls, items, request=None, **kwargs):
""" Index objects related to :items: in bulk.
Related items are first grouped in map
{model_name: {item1, item2, ...}} and then indexed.
:param items: Sequence of DB objects related objects if which
should be indexed.
:param request: Pyramid Request instance.
"""
index_map = defaultdict(set)
for item in items:
relations = item.get_related_documents(**kwargs)
for model_cls, related_items in relations:
indexable = getattr(model_cls, '_index_enabled', False)
if indexable and related_items:
index_map[model_cls.__name__].update(related_items)
for model_name, instances in index_map.items():
cls(model_name).index(to_dicts(instances), request=request)
|
[
"def",
"bulk_index_relations",
"(",
"cls",
",",
"items",
",",
"request",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"index_map",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"item",
"in",
"items",
":",
"relations",
"=",
"item",
".",
"get_related_documents",
"(",
"*",
"*",
"kwargs",
")",
"for",
"model_cls",
",",
"related_items",
"in",
"relations",
":",
"indexable",
"=",
"getattr",
"(",
"model_cls",
",",
"'_index_enabled'",
",",
"False",
")",
"if",
"indexable",
"and",
"related_items",
":",
"index_map",
"[",
"model_cls",
".",
"__name__",
"]",
".",
"update",
"(",
"related_items",
")",
"for",
"model_name",
",",
"instances",
"in",
"index_map",
".",
"items",
"(",
")",
":",
"cls",
"(",
"model_name",
")",
".",
"index",
"(",
"to_dicts",
"(",
"instances",
")",
",",
"request",
"=",
"request",
")"
] |
Index objects related to :items: in bulk.
Related items are first grouped in map
{model_name: {item1, item2, ...}} and then indexed.
:param items: Sequence of DB objects related objects if which
should be indexed.
:param request: Pyramid Request instance.
|
[
"Index",
"objects",
"related",
"to",
":",
"items",
":",
"in",
"bulk",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L620-L639
|
train
|
sametmax/devpy
|
setup.py
|
get_version
|
def get_version(path="src/devpy/__init__.py"):
""" Return the version of by with regex intead of importing it"""
init_content = open(path, "rt").read()
pattern = r"^__version__ = ['\"]([^'\"]*)['\"]"
return re.search(pattern, init_content, re.M).group(1)
|
python
|
def get_version(path="src/devpy/__init__.py"):
""" Return the version of by with regex intead of importing it"""
init_content = open(path, "rt").read()
pattern = r"^__version__ = ['\"]([^'\"]*)['\"]"
return re.search(pattern, init_content, re.M).group(1)
|
[
"def",
"get_version",
"(",
"path",
"=",
"\"src/devpy/__init__.py\"",
")",
":",
"init_content",
"=",
"open",
"(",
"path",
",",
"\"rt\"",
")",
".",
"read",
"(",
")",
"pattern",
"=",
"r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"",
"return",
"re",
".",
"search",
"(",
"pattern",
",",
"init_content",
",",
"re",
".",
"M",
")",
".",
"group",
"(",
"1",
")"
] |
Return the version of by with regex intead of importing it
|
[
"Return",
"the",
"version",
"of",
"by",
"with",
"regex",
"intead",
"of",
"importing",
"it"
] |
66a150817644edf825d19b80f644e7d05b2a3e86
|
https://github.com/sametmax/devpy/blob/66a150817644edf825d19b80f644e7d05b2a3e86/setup.py#L7-L11
|
train
|
scalative/haas
|
haas/plugin_manager.py
|
PluginManager.add_plugin_arguments
|
def add_plugin_arguments(self, parser):
"""Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
"""
for manager in self.hook_managers.values():
if len(list(manager)) == 0:
continue
manager.map(self._add_hook_extension_arguments, parser)
for namespace, manager in self.driver_managers.items():
choices = list(sorted(manager.names()))
if len(choices) == 0:
continue
option, dest = self._namespace_to_option(namespace)
parser.add_argument(
option, help=self._help[namespace], dest=dest,
choices=choices, default='default')
option_prefix = '{0}-'.format(option)
dest_prefix = '{0}_'.format(dest)
manager.map(self._add_driver_extension_arguments,
parser, option_prefix, dest_prefix)
|
python
|
def add_plugin_arguments(self, parser):
"""Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
"""
for manager in self.hook_managers.values():
if len(list(manager)) == 0:
continue
manager.map(self._add_hook_extension_arguments, parser)
for namespace, manager in self.driver_managers.items():
choices = list(sorted(manager.names()))
if len(choices) == 0:
continue
option, dest = self._namespace_to_option(namespace)
parser.add_argument(
option, help=self._help[namespace], dest=dest,
choices=choices, default='default')
option_prefix = '{0}-'.format(option)
dest_prefix = '{0}_'.format(dest)
manager.map(self._add_driver_extension_arguments,
parser, option_prefix, dest_prefix)
|
[
"def",
"add_plugin_arguments",
"(",
"self",
",",
"parser",
")",
":",
"for",
"manager",
"in",
"self",
".",
"hook_managers",
".",
"values",
"(",
")",
":",
"if",
"len",
"(",
"list",
"(",
"manager",
")",
")",
"==",
"0",
":",
"continue",
"manager",
".",
"map",
"(",
"self",
".",
"_add_hook_extension_arguments",
",",
"parser",
")",
"for",
"namespace",
",",
"manager",
"in",
"self",
".",
"driver_managers",
".",
"items",
"(",
")",
":",
"choices",
"=",
"list",
"(",
"sorted",
"(",
"manager",
".",
"names",
"(",
")",
")",
")",
"if",
"len",
"(",
"choices",
")",
"==",
"0",
":",
"continue",
"option",
",",
"dest",
"=",
"self",
".",
"_namespace_to_option",
"(",
"namespace",
")",
"parser",
".",
"add_argument",
"(",
"option",
",",
"help",
"=",
"self",
".",
"_help",
"[",
"namespace",
"]",
",",
"dest",
"=",
"dest",
",",
"choices",
"=",
"choices",
",",
"default",
"=",
"'default'",
")",
"option_prefix",
"=",
"'{0}-'",
".",
"format",
"(",
"option",
")",
"dest_prefix",
"=",
"'{0}_'",
".",
"format",
"(",
"dest",
")",
"manager",
".",
"map",
"(",
"self",
".",
"_add_driver_extension_arguments",
",",
"parser",
",",
"option_prefix",
",",
"dest_prefix",
")"
] |
Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
|
[
"Add",
"plugin",
"arguments",
"to",
"argument",
"parser",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L105-L129
|
train
|
scalative/haas
|
haas/plugin_manager.py
|
PluginManager.get_enabled_hook_plugins
|
def get_enabled_hook_plugins(self, hook, args, **kwargs):
"""Get enabled plugins for specified hook name.
"""
manager = self.hook_managers[hook]
if len(list(manager)) == 0:
return []
return [
plugin for plugin in manager.map(
self._create_hook_plugin, args, **kwargs)
if plugin is not None
]
|
python
|
def get_enabled_hook_plugins(self, hook, args, **kwargs):
"""Get enabled plugins for specified hook name.
"""
manager = self.hook_managers[hook]
if len(list(manager)) == 0:
return []
return [
plugin for plugin in manager.map(
self._create_hook_plugin, args, **kwargs)
if plugin is not None
]
|
[
"def",
"get_enabled_hook_plugins",
"(",
"self",
",",
"hook",
",",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"manager",
"=",
"self",
".",
"hook_managers",
"[",
"hook",
"]",
"if",
"len",
"(",
"list",
"(",
"manager",
")",
")",
"==",
"0",
":",
"return",
"[",
"]",
"return",
"[",
"plugin",
"for",
"plugin",
"in",
"manager",
".",
"map",
"(",
"self",
".",
"_create_hook_plugin",
",",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"plugin",
"is",
"not",
"None",
"]"
] |
Get enabled plugins for specified hook name.
|
[
"Get",
"enabled",
"plugins",
"for",
"specified",
"hook",
"name",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L131-L142
|
train
|
scalative/haas
|
haas/plugin_manager.py
|
PluginManager.get_driver
|
def get_driver(self, namespace, parsed_args, **kwargs):
"""Get mutually-exlusive plugin for plugin namespace.
"""
option, dest = self._namespace_to_option(namespace)
dest_prefix = '{0}_'.format(dest)
driver_name = getattr(parsed_args, dest, 'default')
driver_extension = self.driver_managers[namespace][driver_name]
return driver_extension.plugin.from_args(
parsed_args, dest_prefix, **kwargs)
|
python
|
def get_driver(self, namespace, parsed_args, **kwargs):
"""Get mutually-exlusive plugin for plugin namespace.
"""
option, dest = self._namespace_to_option(namespace)
dest_prefix = '{0}_'.format(dest)
driver_name = getattr(parsed_args, dest, 'default')
driver_extension = self.driver_managers[namespace][driver_name]
return driver_extension.plugin.from_args(
parsed_args, dest_prefix, **kwargs)
|
[
"def",
"get_driver",
"(",
"self",
",",
"namespace",
",",
"parsed_args",
",",
"*",
"*",
"kwargs",
")",
":",
"option",
",",
"dest",
"=",
"self",
".",
"_namespace_to_option",
"(",
"namespace",
")",
"dest_prefix",
"=",
"'{0}_'",
".",
"format",
"(",
"dest",
")",
"driver_name",
"=",
"getattr",
"(",
"parsed_args",
",",
"dest",
",",
"'default'",
")",
"driver_extension",
"=",
"self",
".",
"driver_managers",
"[",
"namespace",
"]",
"[",
"driver_name",
"]",
"return",
"driver_extension",
".",
"plugin",
".",
"from_args",
"(",
"parsed_args",
",",
"dest_prefix",
",",
"*",
"*",
"kwargs",
")"
] |
Get mutually-exlusive plugin for plugin namespace.
|
[
"Get",
"mutually",
"-",
"exlusive",
"plugin",
"for",
"plugin",
"namespace",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L144-L153
|
train
|
timgabets/bpc8583
|
bpc8583/transaction.py
|
Transaction.get_description
|
def get_description(self):
"""
Get transaction description (for logging purposes)
"""
if self.card:
card_description = self.card.get_description()
else:
card_description = 'Cardless'
if card_description:
card_description += ' | '
return card_description + self.description if self.description else card_description + self.type + ' ' + str(self.IsoMessage.FieldData(11))
|
python
|
def get_description(self):
"""
Get transaction description (for logging purposes)
"""
if self.card:
card_description = self.card.get_description()
else:
card_description = 'Cardless'
if card_description:
card_description += ' | '
return card_description + self.description if self.description else card_description + self.type + ' ' + str(self.IsoMessage.FieldData(11))
|
[
"def",
"get_description",
"(",
"self",
")",
":",
"if",
"self",
".",
"card",
":",
"card_description",
"=",
"self",
".",
"card",
".",
"get_description",
"(",
")",
"else",
":",
"card_description",
"=",
"'Cardless'",
"if",
"card_description",
":",
"card_description",
"+=",
"' | '",
"return",
"card_description",
"+",
"self",
".",
"description",
"if",
"self",
".",
"description",
"else",
"card_description",
"+",
"self",
".",
"type",
"+",
"' '",
"+",
"str",
"(",
"self",
".",
"IsoMessage",
".",
"FieldData",
"(",
"11",
")",
")"
] |
Get transaction description (for logging purposes)
|
[
"Get",
"transaction",
"description",
"(",
"for",
"logging",
"purposes",
")"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L196-L208
|
train
|
timgabets/bpc8583
|
bpc8583/transaction.py
|
Transaction.set_amount
|
def set_amount(self, amount):
"""
Set transaction amount
"""
if amount:
try:
self.IsoMessage.FieldData(4, int(amount))
except ValueError:
self.IsoMessage.FieldData(4, 0)
self.rebuild()
|
python
|
def set_amount(self, amount):
"""
Set transaction amount
"""
if amount:
try:
self.IsoMessage.FieldData(4, int(amount))
except ValueError:
self.IsoMessage.FieldData(4, 0)
self.rebuild()
|
[
"def",
"set_amount",
"(",
"self",
",",
"amount",
")",
":",
"if",
"amount",
":",
"try",
":",
"self",
".",
"IsoMessage",
".",
"FieldData",
"(",
"4",
",",
"int",
"(",
"amount",
")",
")",
"except",
"ValueError",
":",
"self",
".",
"IsoMessage",
".",
"FieldData",
"(",
"4",
",",
"0",
")",
"self",
".",
"rebuild",
"(",
")"
] |
Set transaction amount
|
[
"Set",
"transaction",
"amount"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L244-L253
|
train
|
timgabets/bpc8583
|
bpc8583/transaction.py
|
Transaction.set_expected_action
|
def set_expected_action(self, expected_response_action):
"""
Expected outcome of the transaction ('APPROVED' or 'DECLINED')
"""
if expected_response_action.upper() not in ['APPROVED', 'APPROVE', 'DECLINED', 'DECLINE']:
return False
self.expected_response_action = expected_response_action.upper()
return True
|
python
|
def set_expected_action(self, expected_response_action):
"""
Expected outcome of the transaction ('APPROVED' or 'DECLINED')
"""
if expected_response_action.upper() not in ['APPROVED', 'APPROVE', 'DECLINED', 'DECLINE']:
return False
self.expected_response_action = expected_response_action.upper()
return True
|
[
"def",
"set_expected_action",
"(",
"self",
",",
"expected_response_action",
")",
":",
"if",
"expected_response_action",
".",
"upper",
"(",
")",
"not",
"in",
"[",
"'APPROVED'",
",",
"'APPROVE'",
",",
"'DECLINED'",
",",
"'DECLINE'",
"]",
":",
"return",
"False",
"self",
".",
"expected_response_action",
"=",
"expected_response_action",
".",
"upper",
"(",
")",
"return",
"True"
] |
Expected outcome of the transaction ('APPROVED' or 'DECLINED')
|
[
"Expected",
"outcome",
"of",
"the",
"transaction",
"(",
"APPROVED",
"or",
"DECLINED",
")"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L263-L271
|
train
|
timgabets/bpc8583
|
bpc8583/transaction.py
|
Transaction.build_emv_data
|
def build_emv_data(self):
"""
TODO:
95 TVR
82 app_int_prof
"""
emv_data = ''
emv_data += self.TLV.build({'82': self._get_app_interchange_profile()})
emv_data += self.TLV.build({'9A': get_date()})
emv_data += self.TLV.build({'95': self.term.get_tvr()})
emv_data += self.TLV.build({'9F10': self.card.get_iss_application_data()})
emv_data += self.TLV.build({'9F26': self.card.get_application_cryptogram()})
emv_data += self.TLV.build({'9F36': self.card.get_transaction_counter()})
emv_data += self.TLV.build({'9F37': self.term.get_unpredno()})
emv_data += self.TLV.build({'9F1A': self.term.get_country_code()})
return emv_data
|
python
|
def build_emv_data(self):
"""
TODO:
95 TVR
82 app_int_prof
"""
emv_data = ''
emv_data += self.TLV.build({'82': self._get_app_interchange_profile()})
emv_data += self.TLV.build({'9A': get_date()})
emv_data += self.TLV.build({'95': self.term.get_tvr()})
emv_data += self.TLV.build({'9F10': self.card.get_iss_application_data()})
emv_data += self.TLV.build({'9F26': self.card.get_application_cryptogram()})
emv_data += self.TLV.build({'9F36': self.card.get_transaction_counter()})
emv_data += self.TLV.build({'9F37': self.term.get_unpredno()})
emv_data += self.TLV.build({'9F1A': self.term.get_country_code()})
return emv_data
|
[
"def",
"build_emv_data",
"(",
"self",
")",
":",
"emv_data",
"=",
"''",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'82'",
":",
"self",
".",
"_get_app_interchange_profile",
"(",
")",
"}",
")",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'9A'",
":",
"get_date",
"(",
")",
"}",
")",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'95'",
":",
"self",
".",
"term",
".",
"get_tvr",
"(",
")",
"}",
")",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'9F10'",
":",
"self",
".",
"card",
".",
"get_iss_application_data",
"(",
")",
"}",
")",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'9F26'",
":",
"self",
".",
"card",
".",
"get_application_cryptogram",
"(",
")",
"}",
")",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'9F36'",
":",
"self",
".",
"card",
".",
"get_transaction_counter",
"(",
")",
"}",
")",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'9F37'",
":",
"self",
".",
"term",
".",
"get_unpredno",
"(",
")",
"}",
")",
"emv_data",
"+=",
"self",
".",
"TLV",
".",
"build",
"(",
"{",
"'9F1A'",
":",
"self",
".",
"term",
".",
"get_country_code",
"(",
")",
"}",
")",
"return",
"emv_data"
] |
TODO:
95 TVR
82 app_int_prof
|
[
"TODO",
":",
"95",
"TVR",
"82",
"app_int_prof"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L302-L317
|
train
|
timgabets/bpc8583
|
bpc8583/transaction.py
|
Transaction.set_currency
|
def set_currency(self, currency_id):
"""
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
"""
try:
self.currency = currency_codes[currency_id]
self.IsoMessage.FieldData(49, self.currency)
self.rebuild()
except KeyError:
self.currency = None
|
python
|
def set_currency(self, currency_id):
"""
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
"""
try:
self.currency = currency_codes[currency_id]
self.IsoMessage.FieldData(49, self.currency)
self.rebuild()
except KeyError:
self.currency = None
|
[
"def",
"set_currency",
"(",
"self",
",",
"currency_id",
")",
":",
"try",
":",
"self",
".",
"currency",
"=",
"currency_codes",
"[",
"currency_id",
"]",
"self",
".",
"IsoMessage",
".",
"FieldData",
"(",
"49",
",",
"self",
".",
"currency",
")",
"self",
".",
"rebuild",
"(",
")",
"except",
"KeyError",
":",
"self",
".",
"currency",
"=",
"None"
] |
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
|
[
"Set",
"transaction",
"currency",
"code",
"from",
"given",
"currency",
"id",
"e",
".",
"g",
".",
"set",
"840",
"from",
"USD"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L337-L346
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/blocks.py
|
BlockCounts.finalize
|
def finalize(self):
"""Output the aggregate block count results."""
for name, count in sorted(self.blocks.items(), key=lambda x: x[1]):
print('{:3} {}'.format(count, name))
print('{:3} total'.format(sum(self.blocks.values())))
|
python
|
def finalize(self):
"""Output the aggregate block count results."""
for name, count in sorted(self.blocks.items(), key=lambda x: x[1]):
print('{:3} {}'.format(count, name))
print('{:3} total'.format(sum(self.blocks.values())))
|
[
"def",
"finalize",
"(",
"self",
")",
":",
"for",
"name",
",",
"count",
"in",
"sorted",
"(",
"self",
".",
"blocks",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
":",
"print",
"(",
"'{:3} {}'",
".",
"format",
"(",
"count",
",",
"name",
")",
")",
"print",
"(",
"'{:3} total'",
".",
"format",
"(",
"sum",
"(",
"self",
".",
"blocks",
".",
"values",
"(",
")",
")",
")",
")"
] |
Output the aggregate block count results.
|
[
"Output",
"the",
"aggregate",
"block",
"count",
"results",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L17-L21
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/blocks.py
|
BlockCounts.analyze
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the BlockCounts plugin."""
file_blocks = Counter()
for script in self.iter_scripts(scratch):
for name, _, _ in self.iter_blocks(script.blocks):
file_blocks[name] += 1
self.blocks.update(file_blocks) # Update the overall count
return {'types': file_blocks}
|
python
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the BlockCounts plugin."""
file_blocks = Counter()
for script in self.iter_scripts(scratch):
for name, _, _ in self.iter_blocks(script.blocks):
file_blocks[name] += 1
self.blocks.update(file_blocks) # Update the overall count
return {'types': file_blocks}
|
[
"def",
"analyze",
"(",
"self",
",",
"scratch",
",",
"*",
"*",
"kwargs",
")",
":",
"file_blocks",
"=",
"Counter",
"(",
")",
"for",
"script",
"in",
"self",
".",
"iter_scripts",
"(",
"scratch",
")",
":",
"for",
"name",
",",
"_",
",",
"_",
"in",
"self",
".",
"iter_blocks",
"(",
"script",
".",
"blocks",
")",
":",
"file_blocks",
"[",
"name",
"]",
"+=",
"1",
"self",
".",
"blocks",
".",
"update",
"(",
"file_blocks",
")",
"# Update the overall count",
"return",
"{",
"'types'",
":",
"file_blocks",
"}"
] |
Run and return the results from the BlockCounts plugin.
|
[
"Run",
"and",
"return",
"the",
"results",
"from",
"the",
"BlockCounts",
"plugin",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L23-L30
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/blocks.py
|
DeadCode.analyze
|
def analyze(self, scratch, **kwargs):
"""Run and return the results form the DeadCode plugin.
The variable_event indicates that the Scratch file contains at least
one instance of a broadcast event based on a variable. When
variable_event is True, dead code scripts reported by this plugin that
begin with a "when I receive" block may not actually indicate dead
code.
"""
self.total_instances += 1
sprites = {}
for sprite, script in self.iter_sprite_scripts(scratch):
if not script.reachable:
sprites.setdefault(sprite, []).append(script)
if sprites:
self.dead_code_instances += 1
import pprint
pprint.pprint(sprites)
variable_event = any(True in self.get_broadcast_events(x) for x in
self.iter_scripts(scratch))
return {'dead_code': {'sprites': sprites,
'variable_event': variable_event}}
|
python
|
def analyze(self, scratch, **kwargs):
"""Run and return the results form the DeadCode plugin.
The variable_event indicates that the Scratch file contains at least
one instance of a broadcast event based on a variable. When
variable_event is True, dead code scripts reported by this plugin that
begin with a "when I receive" block may not actually indicate dead
code.
"""
self.total_instances += 1
sprites = {}
for sprite, script in self.iter_sprite_scripts(scratch):
if not script.reachable:
sprites.setdefault(sprite, []).append(script)
if sprites:
self.dead_code_instances += 1
import pprint
pprint.pprint(sprites)
variable_event = any(True in self.get_broadcast_events(x) for x in
self.iter_scripts(scratch))
return {'dead_code': {'sprites': sprites,
'variable_event': variable_event}}
|
[
"def",
"analyze",
"(",
"self",
",",
"scratch",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"total_instances",
"+=",
"1",
"sprites",
"=",
"{",
"}",
"for",
"sprite",
",",
"script",
"in",
"self",
".",
"iter_sprite_scripts",
"(",
"scratch",
")",
":",
"if",
"not",
"script",
".",
"reachable",
":",
"sprites",
".",
"setdefault",
"(",
"sprite",
",",
"[",
"]",
")",
".",
"append",
"(",
"script",
")",
"if",
"sprites",
":",
"self",
".",
"dead_code_instances",
"+=",
"1",
"import",
"pprint",
"pprint",
".",
"pprint",
"(",
"sprites",
")",
"variable_event",
"=",
"any",
"(",
"True",
"in",
"self",
".",
"get_broadcast_events",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"iter_scripts",
"(",
"scratch",
")",
")",
"return",
"{",
"'dead_code'",
":",
"{",
"'sprites'",
":",
"sprites",
",",
"'variable_event'",
":",
"variable_event",
"}",
"}"
] |
Run and return the results form the DeadCode plugin.
The variable_event indicates that the Scratch file contains at least
one instance of a broadcast event based on a variable. When
variable_event is True, dead code scripts reported by this plugin that
begin with a "when I receive" block may not actually indicate dead
code.
|
[
"Run",
"and",
"return",
"the",
"results",
"form",
"the",
"DeadCode",
"plugin",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L43-L65
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/blocks.py
|
DeadCode.finalize
|
def finalize(self):
"""Output the number of instances that contained dead code."""
if self.total_instances > 1:
print('{} of {} instances contained dead code.'
.format(self.dead_code_instances, self.total_instances))
|
python
|
def finalize(self):
"""Output the number of instances that contained dead code."""
if self.total_instances > 1:
print('{} of {} instances contained dead code.'
.format(self.dead_code_instances, self.total_instances))
|
[
"def",
"finalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"total_instances",
">",
"1",
":",
"print",
"(",
"'{} of {} instances contained dead code.'",
".",
"format",
"(",
"self",
".",
"dead_code_instances",
",",
"self",
".",
"total_instances",
")",
")"
] |
Output the number of instances that contained dead code.
|
[
"Output",
"the",
"number",
"of",
"instances",
"that",
"contained",
"dead",
"code",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L67-L71
|
train
|
timgabets/bpc8583
|
examples/isoClient.py
|
show_help
|
def show_help(name):
"""
Show help and basic usage
"""
print('Usage: python3 {} [OPTIONS]... '.format(name))
print('ISO8583 message client')
print(' -v, --verbose\t\tRun transactions verbosely')
print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default')
print(' -s, --server=[IP]\t\tIP of the ISO host to connect to, 127.0.0.1 by default')
print(' -t, --terminal=[ID]\t\tTerminal ID (used in DE 41 ISO field, 10001337 by default)')
print(' -m, --merchant=[ID]\t\tMerchant ID (used in DE 42 ISO field, 999999999999001 by default)')
print(' -k, --terminal-key=[KEY]\t\tTerminal key (\'DEADBEEF DEADBEEF DEADBEEF DEADBEEF\' by default)')
print(' -K, --master-key=[KEY]\t\Master key (\'ABABABAB CDCDCDCD EFEFEFEF AEAEAEAE\' by default)')
print(' -f, --file=[file.xml]\t\tUse transaction data from the given XML-file')
|
python
|
def show_help(name):
"""
Show help and basic usage
"""
print('Usage: python3 {} [OPTIONS]... '.format(name))
print('ISO8583 message client')
print(' -v, --verbose\t\tRun transactions verbosely')
print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default')
print(' -s, --server=[IP]\t\tIP of the ISO host to connect to, 127.0.0.1 by default')
print(' -t, --terminal=[ID]\t\tTerminal ID (used in DE 41 ISO field, 10001337 by default)')
print(' -m, --merchant=[ID]\t\tMerchant ID (used in DE 42 ISO field, 999999999999001 by default)')
print(' -k, --terminal-key=[KEY]\t\tTerminal key (\'DEADBEEF DEADBEEF DEADBEEF DEADBEEF\' by default)')
print(' -K, --master-key=[KEY]\t\Master key (\'ABABABAB CDCDCDCD EFEFEFEF AEAEAEAE\' by default)')
print(' -f, --file=[file.xml]\t\tUse transaction data from the given XML-file')
|
[
"def",
"show_help",
"(",
"name",
")",
":",
"print",
"(",
"'Usage: python3 {} [OPTIONS]... '",
".",
"format",
"(",
"name",
")",
")",
"print",
"(",
"'ISO8583 message client'",
")",
"print",
"(",
"' -v, --verbose\\t\\tRun transactions verbosely'",
")",
"print",
"(",
"' -p, --port=[PORT]\\t\\tTCP port to connect to, 1337 by default'",
")",
"print",
"(",
"' -s, --server=[IP]\\t\\tIP of the ISO host to connect to, 127.0.0.1 by default'",
")",
"print",
"(",
"' -t, --terminal=[ID]\\t\\tTerminal ID (used in DE 41 ISO field, 10001337 by default)'",
")",
"print",
"(",
"' -m, --merchant=[ID]\\t\\tMerchant ID (used in DE 42 ISO field, 999999999999001 by default)'",
")",
"print",
"(",
"' -k, --terminal-key=[KEY]\\t\\tTerminal key (\\'DEADBEEF DEADBEEF DEADBEEF DEADBEEF\\' by default)'",
")",
"print",
"(",
"' -K, --master-key=[KEY]\\t\\Master key (\\'ABABABAB CDCDCDCD EFEFEFEF AEAEAEAE\\' by default)'",
")",
"print",
"(",
"' -f, --file=[file.xml]\\t\\tUse transaction data from the given XML-file'",
")"
] |
Show help and basic usage
|
[
"Show",
"help",
"and",
"basic",
"usage"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/examples/isoClient.py#L301-L314
|
train
|
timgabets/bpc8583
|
examples/isoClient.py
|
isoClient._run_interactive
|
def _run_interactive(self):
"""
Run transactions interactively (by asking user which transaction to run)
"""
self.term.connect()
self._show_available_transactions()
while True:
trxn_type = self._user_input('\nEnter transaction to send: ')
trxn = ''
data = ''
if trxn_type == 'e':
trxn = Transaction('echo', self.card, self.term)
trxn.trace()
elif trxn_type == 'b':
trxn = Transaction('balance', self.card, self.term)
trxn.set_PIN(self._user_input('Enter PIN: '))
trxn.trace()
elif trxn_type == 'p':
default_amount = 20000
amount = self._user_input('Enter transaction amount ({} by default): '.format(default_amount))
if not amount:
amount = default_amount
trxn = Transaction('purchase', self.card, self.term)
trxn.set_PIN(self._user_input('Enter PIN: '))
trxn.set_amount(amount)
trxn.trace()
elif trxn_type == 'q':
break
else:
print('Unknown transaction. Available transactions are:')
self._show_available_transactions()
continue
self.term.send(trxn.get_data(), show_trace=verbosity)
data = self.term.recv(show_trace=verbosity)
IsoMessage = ISO8583(data[2:], IsoSpec1987BPC())
IsoMessage.Print()
self.term.close()
|
python
|
def _run_interactive(self):
"""
Run transactions interactively (by asking user which transaction to run)
"""
self.term.connect()
self._show_available_transactions()
while True:
trxn_type = self._user_input('\nEnter transaction to send: ')
trxn = ''
data = ''
if trxn_type == 'e':
trxn = Transaction('echo', self.card, self.term)
trxn.trace()
elif trxn_type == 'b':
trxn = Transaction('balance', self.card, self.term)
trxn.set_PIN(self._user_input('Enter PIN: '))
trxn.trace()
elif trxn_type == 'p':
default_amount = 20000
amount = self._user_input('Enter transaction amount ({} by default): '.format(default_amount))
if not amount:
amount = default_amount
trxn = Transaction('purchase', self.card, self.term)
trxn.set_PIN(self._user_input('Enter PIN: '))
trxn.set_amount(amount)
trxn.trace()
elif trxn_type == 'q':
break
else:
print('Unknown transaction. Available transactions are:')
self._show_available_transactions()
continue
self.term.send(trxn.get_data(), show_trace=verbosity)
data = self.term.recv(show_trace=verbosity)
IsoMessage = ISO8583(data[2:], IsoSpec1987BPC())
IsoMessage.Print()
self.term.close()
|
[
"def",
"_run_interactive",
"(",
"self",
")",
":",
"self",
".",
"term",
".",
"connect",
"(",
")",
"self",
".",
"_show_available_transactions",
"(",
")",
"while",
"True",
":",
"trxn_type",
"=",
"self",
".",
"_user_input",
"(",
"'\\nEnter transaction to send: '",
")",
"trxn",
"=",
"''",
"data",
"=",
"''",
"if",
"trxn_type",
"==",
"'e'",
":",
"trxn",
"=",
"Transaction",
"(",
"'echo'",
",",
"self",
".",
"card",
",",
"self",
".",
"term",
")",
"trxn",
".",
"trace",
"(",
")",
"elif",
"trxn_type",
"==",
"'b'",
":",
"trxn",
"=",
"Transaction",
"(",
"'balance'",
",",
"self",
".",
"card",
",",
"self",
".",
"term",
")",
"trxn",
".",
"set_PIN",
"(",
"self",
".",
"_user_input",
"(",
"'Enter PIN: '",
")",
")",
"trxn",
".",
"trace",
"(",
")",
"elif",
"trxn_type",
"==",
"'p'",
":",
"default_amount",
"=",
"20000",
"amount",
"=",
"self",
".",
"_user_input",
"(",
"'Enter transaction amount ({} by default): '",
".",
"format",
"(",
"default_amount",
")",
")",
"if",
"not",
"amount",
":",
"amount",
"=",
"default_amount",
"trxn",
"=",
"Transaction",
"(",
"'purchase'",
",",
"self",
".",
"card",
",",
"self",
".",
"term",
")",
"trxn",
".",
"set_PIN",
"(",
"self",
".",
"_user_input",
"(",
"'Enter PIN: '",
")",
")",
"trxn",
".",
"set_amount",
"(",
"amount",
")",
"trxn",
".",
"trace",
"(",
")",
"elif",
"trxn_type",
"==",
"'q'",
":",
"break",
"else",
":",
"print",
"(",
"'Unknown transaction. Available transactions are:'",
")",
"self",
".",
"_show_available_transactions",
"(",
")",
"continue",
"self",
".",
"term",
".",
"send",
"(",
"trxn",
".",
"get_data",
"(",
")",
",",
"show_trace",
"=",
"verbosity",
")",
"data",
"=",
"self",
".",
"term",
".",
"recv",
"(",
"show_trace",
"=",
"verbosity",
")",
"IsoMessage",
"=",
"ISO8583",
"(",
"data",
"[",
"2",
":",
"]",
",",
"IsoSpec1987BPC",
"(",
")",
")",
"IsoMessage",
".",
"Print",
"(",
")",
"self",
".",
"term",
".",
"close",
"(",
")"
] |
Run transactions interactively (by asking user which transaction to run)
|
[
"Run",
"transactions",
"interactively",
"(",
"by",
"asking",
"user",
"which",
"transaction",
"to",
"run",
")"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/examples/isoClient.py#L92-L138
|
train
|
scalative/haas
|
haas/plugins/discoverer.py
|
find_top_level_directory
|
def find_top_level_directory(start_directory):
"""Finds the top-level directory of a project given a start directory
inside the project.
Parameters
----------
start_directory : str
The directory in which test discovery will start.
"""
top_level = start_directory
while os.path.isfile(os.path.join(top_level, '__init__.py')):
top_level = os.path.dirname(top_level)
if top_level == os.path.dirname(top_level):
raise ValueError("Can't find top level directory")
return os.path.abspath(top_level)
|
python
|
def find_top_level_directory(start_directory):
"""Finds the top-level directory of a project given a start directory
inside the project.
Parameters
----------
start_directory : str
The directory in which test discovery will start.
"""
top_level = start_directory
while os.path.isfile(os.path.join(top_level, '__init__.py')):
top_level = os.path.dirname(top_level)
if top_level == os.path.dirname(top_level):
raise ValueError("Can't find top level directory")
return os.path.abspath(top_level)
|
[
"def",
"find_top_level_directory",
"(",
"start_directory",
")",
":",
"top_level",
"=",
"start_directory",
"while",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top_level",
",",
"'__init__.py'",
")",
")",
":",
"top_level",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"top_level",
")",
"if",
"top_level",
"==",
"os",
".",
"path",
".",
"dirname",
"(",
"top_level",
")",
":",
"raise",
"ValueError",
"(",
"\"Can't find top level directory\"",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"top_level",
")"
] |
Finds the top-level directory of a project given a start directory
inside the project.
Parameters
----------
start_directory : str
The directory in which test discovery will start.
|
[
"Finds",
"the",
"top",
"-",
"level",
"directory",
"of",
"a",
"project",
"given",
"a",
"start",
"directory",
"inside",
"the",
"project",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L92-L107
|
train
|
scalative/haas
|
haas/plugins/discoverer.py
|
Discoverer.discover
|
def discover(self, start, top_level_directory=None, pattern='test*.py'):
"""Do test case discovery.
This is the top-level entry-point for test discovery.
If the ``start`` argument is a drectory, then ``haas`` will
discover all tests in the package contained in that directory.
If the ``start`` argument is not a directory, it is assumed to
be a package or module name and tests in the package or module
are loaded.
FIXME: This needs a better description.
Parameters
----------
start : str
The directory, package, module, class or test to load.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
"""
logger.debug('Starting test discovery')
if os.path.isdir(start):
start_directory = start
return self.discover_by_directory(
start_directory, top_level_directory=top_level_directory,
pattern=pattern)
elif os.path.isfile(start):
start_filepath = start
return self.discover_by_file(
start_filepath, top_level_directory=top_level_directory)
else:
package_or_module = start
return self.discover_by_module(
package_or_module, top_level_directory=top_level_directory,
pattern=pattern)
|
python
|
def discover(self, start, top_level_directory=None, pattern='test*.py'):
"""Do test case discovery.
This is the top-level entry-point for test discovery.
If the ``start`` argument is a drectory, then ``haas`` will
discover all tests in the package contained in that directory.
If the ``start`` argument is not a directory, it is assumed to
be a package or module name and tests in the package or module
are loaded.
FIXME: This needs a better description.
Parameters
----------
start : str
The directory, package, module, class or test to load.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
"""
logger.debug('Starting test discovery')
if os.path.isdir(start):
start_directory = start
return self.discover_by_directory(
start_directory, top_level_directory=top_level_directory,
pattern=pattern)
elif os.path.isfile(start):
start_filepath = start
return self.discover_by_file(
start_filepath, top_level_directory=top_level_directory)
else:
package_or_module = start
return self.discover_by_module(
package_or_module, top_level_directory=top_level_directory,
pattern=pattern)
|
[
"def",
"discover",
"(",
"self",
",",
"start",
",",
"top_level_directory",
"=",
"None",
",",
"pattern",
"=",
"'test*.py'",
")",
":",
"logger",
".",
"debug",
"(",
"'Starting test discovery'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"start",
")",
":",
"start_directory",
"=",
"start",
"return",
"self",
".",
"discover_by_directory",
"(",
"start_directory",
",",
"top_level_directory",
"=",
"top_level_directory",
",",
"pattern",
"=",
"pattern",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"start",
")",
":",
"start_filepath",
"=",
"start",
"return",
"self",
".",
"discover_by_file",
"(",
"start_filepath",
",",
"top_level_directory",
"=",
"top_level_directory",
")",
"else",
":",
"package_or_module",
"=",
"start",
"return",
"self",
".",
"discover_by_module",
"(",
"package_or_module",
",",
"top_level_directory",
"=",
"top_level_directory",
",",
"pattern",
"=",
"pattern",
")"
] |
Do test case discovery.
This is the top-level entry-point for test discovery.
If the ``start`` argument is a drectory, then ``haas`` will
discover all tests in the package contained in that directory.
If the ``start`` argument is not a directory, it is assumed to
be a package or module name and tests in the package or module
are loaded.
FIXME: This needs a better description.
Parameters
----------
start : str
The directory, package, module, class or test to load.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
|
[
"Do",
"test",
"case",
"discovery",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L178-L219
|
train
|
scalative/haas
|
haas/plugins/discoverer.py
|
Discoverer.discover_by_module
|
def discover_by_module(self, module_name, top_level_directory=None,
pattern='test*.py'):
"""Find all tests in a package or module, or load a single test case if
a class or test inside a module was specified.
Parameters
----------
module_name : str
The dotted package name, module name or TestCase class and
test method.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
"""
# If the top level directory is given, the module may only be
# importable with that in the path.
if top_level_directory is not None and \
top_level_directory not in sys.path:
sys.path.insert(0, top_level_directory)
logger.debug('Discovering tests by module: module_name=%r, '
'top_level_directory=%r, pattern=%r', module_name,
top_level_directory, pattern)
try:
module, case_attributes = find_module_by_name(module_name)
except ImportError:
return self.discover_filtered_tests(
module_name, top_level_directory=top_level_directory,
pattern=pattern)
dirname, basename = os.path.split(module.__file__)
basename = os.path.splitext(basename)[0]
if len(case_attributes) == 0 and basename == '__init__':
# Discover in a package
return self.discover_by_directory(
dirname, top_level_directory, pattern=pattern)
elif len(case_attributes) == 0:
# Discover all in a module
return self._loader.load_module(module)
return self.discover_single_case(module, case_attributes)
|
python
|
def discover_by_module(self, module_name, top_level_directory=None,
pattern='test*.py'):
"""Find all tests in a package or module, or load a single test case if
a class or test inside a module was specified.
Parameters
----------
module_name : str
The dotted package name, module name or TestCase class and
test method.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
"""
# If the top level directory is given, the module may only be
# importable with that in the path.
if top_level_directory is not None and \
top_level_directory not in sys.path:
sys.path.insert(0, top_level_directory)
logger.debug('Discovering tests by module: module_name=%r, '
'top_level_directory=%r, pattern=%r', module_name,
top_level_directory, pattern)
try:
module, case_attributes = find_module_by_name(module_name)
except ImportError:
return self.discover_filtered_tests(
module_name, top_level_directory=top_level_directory,
pattern=pattern)
dirname, basename = os.path.split(module.__file__)
basename = os.path.splitext(basename)[0]
if len(case_attributes) == 0 and basename == '__init__':
# Discover in a package
return self.discover_by_directory(
dirname, top_level_directory, pattern=pattern)
elif len(case_attributes) == 0:
# Discover all in a module
return self._loader.load_module(module)
return self.discover_single_case(module, case_attributes)
|
[
"def",
"discover_by_module",
"(",
"self",
",",
"module_name",
",",
"top_level_directory",
"=",
"None",
",",
"pattern",
"=",
"'test*.py'",
")",
":",
"# If the top level directory is given, the module may only be",
"# importable with that in the path.",
"if",
"top_level_directory",
"is",
"not",
"None",
"and",
"top_level_directory",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"top_level_directory",
")",
"logger",
".",
"debug",
"(",
"'Discovering tests by module: module_name=%r, '",
"'top_level_directory=%r, pattern=%r'",
",",
"module_name",
",",
"top_level_directory",
",",
"pattern",
")",
"try",
":",
"module",
",",
"case_attributes",
"=",
"find_module_by_name",
"(",
"module_name",
")",
"except",
"ImportError",
":",
"return",
"self",
".",
"discover_filtered_tests",
"(",
"module_name",
",",
"top_level_directory",
"=",
"top_level_directory",
",",
"pattern",
"=",
"pattern",
")",
"dirname",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"module",
".",
"__file__",
")",
"basename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"case_attributes",
")",
"==",
"0",
"and",
"basename",
"==",
"'__init__'",
":",
"# Discover in a package",
"return",
"self",
".",
"discover_by_directory",
"(",
"dirname",
",",
"top_level_directory",
",",
"pattern",
"=",
"pattern",
")",
"elif",
"len",
"(",
"case_attributes",
")",
"==",
"0",
":",
"# Discover all in a module",
"return",
"self",
".",
"_loader",
".",
"load_module",
"(",
"module",
")",
"return",
"self",
".",
"discover_single_case",
"(",
"module",
",",
"case_attributes",
")"
] |
Find all tests in a package or module, or load a single test case if
a class or test inside a module was specified.
Parameters
----------
module_name : str
The dotted package name, module name or TestCase class and
test method.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
|
[
"Find",
"all",
"tests",
"in",
"a",
"package",
"or",
"module",
"or",
"load",
"a",
"single",
"test",
"case",
"if",
"a",
"class",
"or",
"test",
"inside",
"a",
"module",
"was",
"specified",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L221-L266
|
train
|
scalative/haas
|
haas/plugins/discoverer.py
|
Discoverer.discover_single_case
|
def discover_single_case(self, module, case_attributes):
"""Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
A list (length 1 or 2) of str. The first component must be
the name of a TestCase subclass. The second component must
be the name of a method in the TestCase.
"""
# Find single case
case = module
loader = self._loader
for index, component in enumerate(case_attributes):
case = getattr(case, component, None)
if case is None:
return loader.create_suite()
elif loader.is_test_case(case):
rest = case_attributes[index + 1:]
if len(rest) > 1:
raise ValueError('Too many components in module path')
elif len(rest) == 1:
return loader.create_suite(
[loader.load_test(case, *rest)])
return loader.load_case(case)
# No cases matched, return empty suite
return loader.create_suite()
|
python
|
def discover_single_case(self, module, case_attributes):
"""Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
A list (length 1 or 2) of str. The first component must be
the name of a TestCase subclass. The second component must
be the name of a method in the TestCase.
"""
# Find single case
case = module
loader = self._loader
for index, component in enumerate(case_attributes):
case = getattr(case, component, None)
if case is None:
return loader.create_suite()
elif loader.is_test_case(case):
rest = case_attributes[index + 1:]
if len(rest) > 1:
raise ValueError('Too many components in module path')
elif len(rest) == 1:
return loader.create_suite(
[loader.load_test(case, *rest)])
return loader.load_case(case)
# No cases matched, return empty suite
return loader.create_suite()
|
[
"def",
"discover_single_case",
"(",
"self",
",",
"module",
",",
"case_attributes",
")",
":",
"# Find single case",
"case",
"=",
"module",
"loader",
"=",
"self",
".",
"_loader",
"for",
"index",
",",
"component",
"in",
"enumerate",
"(",
"case_attributes",
")",
":",
"case",
"=",
"getattr",
"(",
"case",
",",
"component",
",",
"None",
")",
"if",
"case",
"is",
"None",
":",
"return",
"loader",
".",
"create_suite",
"(",
")",
"elif",
"loader",
".",
"is_test_case",
"(",
"case",
")",
":",
"rest",
"=",
"case_attributes",
"[",
"index",
"+",
"1",
":",
"]",
"if",
"len",
"(",
"rest",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Too many components in module path'",
")",
"elif",
"len",
"(",
"rest",
")",
"==",
"1",
":",
"return",
"loader",
".",
"create_suite",
"(",
"[",
"loader",
".",
"load_test",
"(",
"case",
",",
"*",
"rest",
")",
"]",
")",
"return",
"loader",
".",
"load_case",
"(",
"case",
")",
"# No cases matched, return empty suite",
"return",
"loader",
".",
"create_suite",
"(",
")"
] |
Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
A list (length 1 or 2) of str. The first component must be
the name of a TestCase subclass. The second component must
be the name of a method in the TestCase.
|
[
"Find",
"and",
"load",
"a",
"single",
"TestCase",
"or",
"TestCase",
"method",
"from",
"a",
"module",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L268-L299
|
train
|
scalative/haas
|
haas/plugins/discoverer.py
|
Discoverer.discover_by_directory
|
def discover_by_directory(self, start_directory, top_level_directory=None,
pattern='test*.py'):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
"""
start_directory = os.path.abspath(start_directory)
if top_level_directory is None:
top_level_directory = find_top_level_directory(
start_directory)
logger.debug('Discovering tests in directory: start_directory=%r, '
'top_level_directory=%r, pattern=%r', start_directory,
top_level_directory, pattern)
assert_start_importable(top_level_directory, start_directory)
if top_level_directory not in sys.path:
sys.path.insert(0, top_level_directory)
tests = self._discover_tests(
start_directory, top_level_directory, pattern)
return self._loader.create_suite(list(tests))
|
python
|
def discover_by_directory(self, start_directory, top_level_directory=None,
pattern='test*.py'):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
"""
start_directory = os.path.abspath(start_directory)
if top_level_directory is None:
top_level_directory = find_top_level_directory(
start_directory)
logger.debug('Discovering tests in directory: start_directory=%r, '
'top_level_directory=%r, pattern=%r', start_directory,
top_level_directory, pattern)
assert_start_importable(top_level_directory, start_directory)
if top_level_directory not in sys.path:
sys.path.insert(0, top_level_directory)
tests = self._discover_tests(
start_directory, top_level_directory, pattern)
return self._loader.create_suite(list(tests))
|
[
"def",
"discover_by_directory",
"(",
"self",
",",
"start_directory",
",",
"top_level_directory",
"=",
"None",
",",
"pattern",
"=",
"'test*.py'",
")",
":",
"start_directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"start_directory",
")",
"if",
"top_level_directory",
"is",
"None",
":",
"top_level_directory",
"=",
"find_top_level_directory",
"(",
"start_directory",
")",
"logger",
".",
"debug",
"(",
"'Discovering tests in directory: start_directory=%r, '",
"'top_level_directory=%r, pattern=%r'",
",",
"start_directory",
",",
"top_level_directory",
",",
"pattern",
")",
"assert_start_importable",
"(",
"top_level_directory",
",",
"start_directory",
")",
"if",
"top_level_directory",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"top_level_directory",
")",
"tests",
"=",
"self",
".",
"_discover_tests",
"(",
"start_directory",
",",
"top_level_directory",
",",
"pattern",
")",
"return",
"self",
".",
"_loader",
".",
"create_suite",
"(",
"list",
"(",
"tests",
")",
")"
] |
Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
pattern : str
The glob pattern to match the filenames of modules to search
for tests.
|
[
"Run",
"test",
"discovery",
"in",
"a",
"directory",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L301-L332
|
train
|
scalative/haas
|
haas/plugins/discoverer.py
|
Discoverer.discover_by_file
|
def discover_by_file(self, start_filepath, top_level_directory=None):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
"""
start_filepath = os.path.abspath(start_filepath)
start_directory = os.path.dirname(start_filepath)
if top_level_directory is None:
top_level_directory = find_top_level_directory(
start_directory)
logger.debug('Discovering tests in file: start_filepath=%r, '
'top_level_directory=', start_filepath,
top_level_directory)
assert_start_importable(top_level_directory, start_directory)
if top_level_directory not in sys.path:
sys.path.insert(0, top_level_directory)
tests = self._load_from_file(
start_filepath, top_level_directory)
return self._loader.create_suite(list(tests))
|
python
|
def discover_by_file(self, start_filepath, top_level_directory=None):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
"""
start_filepath = os.path.abspath(start_filepath)
start_directory = os.path.dirname(start_filepath)
if top_level_directory is None:
top_level_directory = find_top_level_directory(
start_directory)
logger.debug('Discovering tests in file: start_filepath=%r, '
'top_level_directory=', start_filepath,
top_level_directory)
assert_start_importable(top_level_directory, start_directory)
if top_level_directory not in sys.path:
sys.path.insert(0, top_level_directory)
tests = self._load_from_file(
start_filepath, top_level_directory)
return self._loader.create_suite(list(tests))
|
[
"def",
"discover_by_file",
"(",
"self",
",",
"start_filepath",
",",
"top_level_directory",
"=",
"None",
")",
":",
"start_filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"start_filepath",
")",
"start_directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"start_filepath",
")",
"if",
"top_level_directory",
"is",
"None",
":",
"top_level_directory",
"=",
"find_top_level_directory",
"(",
"start_directory",
")",
"logger",
".",
"debug",
"(",
"'Discovering tests in file: start_filepath=%r, '",
"'top_level_directory='",
",",
"start_filepath",
",",
"top_level_directory",
")",
"assert_start_importable",
"(",
"top_level_directory",
",",
"start_directory",
")",
"if",
"top_level_directory",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"top_level_directory",
")",
"tests",
"=",
"self",
".",
"_load_from_file",
"(",
"start_filepath",
",",
"top_level_directory",
")",
"return",
"self",
".",
"_loader",
".",
"create_suite",
"(",
"list",
"(",
"tests",
")",
")"
] |
Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
top_level_directory : str
The path to the top-level directoy of the project. This is
the parent directory of the project'stop-level Python
package.
|
[
"Run",
"test",
"discovery",
"on",
"a",
"single",
"file",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L334-L362
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
OptionsViewMixin._set_options_headers
|
def _set_options_headers(self, methods):
""" Set proper headers.
Sets following headers:
Allow
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Arguments:
:methods: Sequence of HTTP method names that are value for
requested URI
"""
request = self.request
response = request.response
response.headers['Allow'] = ', '.join(sorted(methods))
if 'Access-Control-Request-Method' in request.headers:
response.headers['Access-Control-Allow-Methods'] = \
', '.join(sorted(methods))
if 'Access-Control-Request-Headers' in request.headers:
response.headers['Access-Control-Allow-Headers'] = \
'origin, x-requested-with, content-type'
return response
|
python
|
def _set_options_headers(self, methods):
""" Set proper headers.
Sets following headers:
Allow
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Arguments:
:methods: Sequence of HTTP method names that are value for
requested URI
"""
request = self.request
response = request.response
response.headers['Allow'] = ', '.join(sorted(methods))
if 'Access-Control-Request-Method' in request.headers:
response.headers['Access-Control-Allow-Methods'] = \
', '.join(sorted(methods))
if 'Access-Control-Request-Headers' in request.headers:
response.headers['Access-Control-Allow-Headers'] = \
'origin, x-requested-with, content-type'
return response
|
[
"def",
"_set_options_headers",
"(",
"self",
",",
"methods",
")",
":",
"request",
"=",
"self",
".",
"request",
"response",
"=",
"request",
".",
"response",
"response",
".",
"headers",
"[",
"'Allow'",
"]",
"=",
"', '",
".",
"join",
"(",
"sorted",
"(",
"methods",
")",
")",
"if",
"'Access-Control-Request-Method'",
"in",
"request",
".",
"headers",
":",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Methods'",
"]",
"=",
"', '",
".",
"join",
"(",
"sorted",
"(",
"methods",
")",
")",
"if",
"'Access-Control-Request-Headers'",
"in",
"request",
".",
"headers",
":",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Headers'",
"]",
"=",
"'origin, x-requested-with, content-type'",
"return",
"response"
] |
Set proper headers.
Sets following headers:
Allow
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Arguments:
:methods: Sequence of HTTP method names that are value for
requested URI
|
[
"Set",
"proper",
"headers",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L33-L58
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
OptionsViewMixin._get_handled_methods
|
def _get_handled_methods(self, actions_map):
""" Get names of HTTP methods that can be used at requested URI.
Arguments:
:actions_map: Map of actions. Must have the same structure as
self._item_actions and self._collection_actions
"""
methods = ('OPTIONS',)
defined_actions = []
for action_name in actions_map.keys():
view_method = getattr(self, action_name, None)
method_exists = view_method is not None
method_defined = view_method != self.not_allowed_action
if method_exists and method_defined:
defined_actions.append(action_name)
for action in defined_actions:
methods += actions_map[action]
return methods
|
python
|
def _get_handled_methods(self, actions_map):
""" Get names of HTTP methods that can be used at requested URI.
Arguments:
:actions_map: Map of actions. Must have the same structure as
self._item_actions and self._collection_actions
"""
methods = ('OPTIONS',)
defined_actions = []
for action_name in actions_map.keys():
view_method = getattr(self, action_name, None)
method_exists = view_method is not None
method_defined = view_method != self.not_allowed_action
if method_exists and method_defined:
defined_actions.append(action_name)
for action in defined_actions:
methods += actions_map[action]
return methods
|
[
"def",
"_get_handled_methods",
"(",
"self",
",",
"actions_map",
")",
":",
"methods",
"=",
"(",
"'OPTIONS'",
",",
")",
"defined_actions",
"=",
"[",
"]",
"for",
"action_name",
"in",
"actions_map",
".",
"keys",
"(",
")",
":",
"view_method",
"=",
"getattr",
"(",
"self",
",",
"action_name",
",",
"None",
")",
"method_exists",
"=",
"view_method",
"is",
"not",
"None",
"method_defined",
"=",
"view_method",
"!=",
"self",
".",
"not_allowed_action",
"if",
"method_exists",
"and",
"method_defined",
":",
"defined_actions",
".",
"append",
"(",
"action_name",
")",
"for",
"action",
"in",
"defined_actions",
":",
"methods",
"+=",
"actions_map",
"[",
"action",
"]",
"return",
"methods"
] |
Get names of HTTP methods that can be used at requested URI.
Arguments:
:actions_map: Map of actions. Must have the same structure as
self._item_actions and self._collection_actions
|
[
"Get",
"names",
"of",
"HTTP",
"methods",
"that",
"can",
"be",
"used",
"at",
"requested",
"URI",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L60-L80
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
OptionsViewMixin.item_options
|
def item_options(self, **kwargs):
""" Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
"""
actions = self._item_actions.copy()
if self._resource.is_singular:
actions['create'] = ('POST',)
methods = self._get_handled_methods(actions)
return self._set_options_headers(methods)
|
python
|
def item_options(self, **kwargs):
""" Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
"""
actions = self._item_actions.copy()
if self._resource.is_singular:
actions['create'] = ('POST',)
methods = self._get_handled_methods(actions)
return self._set_options_headers(methods)
|
[
"def",
"item_options",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"actions",
"=",
"self",
".",
"_item_actions",
".",
"copy",
"(",
")",
"if",
"self",
".",
"_resource",
".",
"is_singular",
":",
"actions",
"[",
"'create'",
"]",
"=",
"(",
"'POST'",
",",
")",
"methods",
"=",
"self",
".",
"_get_handled_methods",
"(",
"actions",
")",
"return",
"self",
".",
"_set_options_headers",
"(",
"methods",
")"
] |
Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
|
[
"Handle",
"collection",
"OPTIONS",
"request",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L82-L93
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
OptionsViewMixin.collection_options
|
def collection_options(self, **kwargs):
""" Handle collection item OPTIONS request. """
methods = self._get_handled_methods(self._collection_actions)
return self._set_options_headers(methods)
|
python
|
def collection_options(self, **kwargs):
""" Handle collection item OPTIONS request. """
methods = self._get_handled_methods(self._collection_actions)
return self._set_options_headers(methods)
|
[
"def",
"collection_options",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"methods",
"=",
"self",
".",
"_get_handled_methods",
"(",
"self",
".",
"_collection_actions",
")",
"return",
"self",
".",
"_set_options_headers",
"(",
"methods",
")"
] |
Handle collection item OPTIONS request.
|
[
"Handle",
"collection",
"item",
"OPTIONS",
"request",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L95-L98
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
ESAggregator.wrap
|
def wrap(self, func):
""" Wrap :func: to perform aggregation on :func: call.
Should be called with view instance methods.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return self.aggregate()
except KeyError:
return func(*args, **kwargs)
return wrapper
|
python
|
def wrap(self, func):
""" Wrap :func: to perform aggregation on :func: call.
Should be called with view instance methods.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return self.aggregate()
except KeyError:
return func(*args, **kwargs)
return wrapper
|
[
"def",
"wrap",
"(",
"self",
",",
"func",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"aggregate",
"(",
")",
"except",
"KeyError",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
Wrap :func: to perform aggregation on :func: call.
Should be called with view instance methods.
|
[
"Wrap",
":",
"func",
":",
"to",
"perform",
"aggregation",
"on",
":",
"func",
":",
"call",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L129-L140
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
ESAggregator.pop_aggregations_params
|
def pop_aggregations_params(self):
""" Pop and return aggregation params from query string params.
Aggregation params are expected to be prefixed(nested under) by
any of `self._aggregations_keys`.
"""
from nefertari.view import BaseView
self._query_params = BaseView.convert_dotted(self.view._query_params)
for key in self._aggregations_keys:
if key in self._query_params:
return self._query_params.pop(key)
else:
raise KeyError('Missing aggregation params')
|
python
|
def pop_aggregations_params(self):
""" Pop and return aggregation params from query string params.
Aggregation params are expected to be prefixed(nested under) by
any of `self._aggregations_keys`.
"""
from nefertari.view import BaseView
self._query_params = BaseView.convert_dotted(self.view._query_params)
for key in self._aggregations_keys:
if key in self._query_params:
return self._query_params.pop(key)
else:
raise KeyError('Missing aggregation params')
|
[
"def",
"pop_aggregations_params",
"(",
"self",
")",
":",
"from",
"nefertari",
".",
"view",
"import",
"BaseView",
"self",
".",
"_query_params",
"=",
"BaseView",
".",
"convert_dotted",
"(",
"self",
".",
"view",
".",
"_query_params",
")",
"for",
"key",
"in",
"self",
".",
"_aggregations_keys",
":",
"if",
"key",
"in",
"self",
".",
"_query_params",
":",
"return",
"self",
".",
"_query_params",
".",
"pop",
"(",
"key",
")",
"else",
":",
"raise",
"KeyError",
"(",
"'Missing aggregation params'",
")"
] |
Pop and return aggregation params from query string params.
Aggregation params are expected to be prefixed(nested under) by
any of `self._aggregations_keys`.
|
[
"Pop",
"and",
"return",
"aggregation",
"params",
"from",
"query",
"string",
"params",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L142-L155
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
ESAggregator.get_aggregations_fields
|
def get_aggregations_fields(cls, params):
""" Recursively get values under the 'field' key.
Is used to get names of fields on which aggregations should be
performed.
"""
fields = []
for key, val in params.items():
if isinstance(val, dict):
fields += cls.get_aggregations_fields(val)
if key == 'field':
fields.append(val)
return fields
|
python
|
def get_aggregations_fields(cls, params):
""" Recursively get values under the 'field' key.
Is used to get names of fields on which aggregations should be
performed.
"""
fields = []
for key, val in params.items():
if isinstance(val, dict):
fields += cls.get_aggregations_fields(val)
if key == 'field':
fields.append(val)
return fields
|
[
"def",
"get_aggregations_fields",
"(",
"cls",
",",
"params",
")",
":",
"fields",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"fields",
"+=",
"cls",
".",
"get_aggregations_fields",
"(",
"val",
")",
"if",
"key",
"==",
"'field'",
":",
"fields",
".",
"append",
"(",
"val",
")",
"return",
"fields"
] |
Recursively get values under the 'field' key.
Is used to get names of fields on which aggregations should be
performed.
|
[
"Recursively",
"get",
"values",
"under",
"the",
"field",
"key",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L164-L176
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
ESAggregator.check_aggregations_privacy
|
def check_aggregations_privacy(self, aggregations_params):
""" Check per-field privacy rules in aggregations.
Privacy is checked by making sure user has access to the fields
used in aggregations.
"""
fields = self.get_aggregations_fields(aggregations_params)
fields_dict = dictset.fromkeys(fields)
fields_dict['_type'] = self.view.Model.__name__
try:
validate_data_privacy(self.view.request, fields_dict)
except wrappers.ValidationError as ex:
raise JHTTPForbidden(
'Not enough permissions to aggregate on '
'fields: {}'.format(ex))
|
python
|
def check_aggregations_privacy(self, aggregations_params):
""" Check per-field privacy rules in aggregations.
Privacy is checked by making sure user has access to the fields
used in aggregations.
"""
fields = self.get_aggregations_fields(aggregations_params)
fields_dict = dictset.fromkeys(fields)
fields_dict['_type'] = self.view.Model.__name__
try:
validate_data_privacy(self.view.request, fields_dict)
except wrappers.ValidationError as ex:
raise JHTTPForbidden(
'Not enough permissions to aggregate on '
'fields: {}'.format(ex))
|
[
"def",
"check_aggregations_privacy",
"(",
"self",
",",
"aggregations_params",
")",
":",
"fields",
"=",
"self",
".",
"get_aggregations_fields",
"(",
"aggregations_params",
")",
"fields_dict",
"=",
"dictset",
".",
"fromkeys",
"(",
"fields",
")",
"fields_dict",
"[",
"'_type'",
"]",
"=",
"self",
".",
"view",
".",
"Model",
".",
"__name__",
"try",
":",
"validate_data_privacy",
"(",
"self",
".",
"view",
".",
"request",
",",
"fields_dict",
")",
"except",
"wrappers",
".",
"ValidationError",
"as",
"ex",
":",
"raise",
"JHTTPForbidden",
"(",
"'Not enough permissions to aggregate on '",
"'fields: {}'",
".",
"format",
"(",
"ex",
")",
")"
] |
Check per-field privacy rules in aggregations.
Privacy is checked by making sure user has access to the fields
used in aggregations.
|
[
"Check",
"per",
"-",
"field",
"privacy",
"rules",
"in",
"aggregations",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L178-L193
|
train
|
ramses-tech/nefertari
|
nefertari/view_helpers.py
|
ESAggregator.aggregate
|
def aggregate(self):
""" Perform aggregation and return response. """
from nefertari.elasticsearch import ES
aggregations_params = self.pop_aggregations_params()
if self.view._auth_enabled:
self.check_aggregations_privacy(aggregations_params)
self.stub_wrappers()
return ES(self.view.Model.__name__).aggregate(
_aggregations_params=aggregations_params,
**self._query_params)
|
python
|
def aggregate(self):
""" Perform aggregation and return response. """
from nefertari.elasticsearch import ES
aggregations_params = self.pop_aggregations_params()
if self.view._auth_enabled:
self.check_aggregations_privacy(aggregations_params)
self.stub_wrappers()
return ES(self.view.Model.__name__).aggregate(
_aggregations_params=aggregations_params,
**self._query_params)
|
[
"def",
"aggregate",
"(",
"self",
")",
":",
"from",
"nefertari",
".",
"elasticsearch",
"import",
"ES",
"aggregations_params",
"=",
"self",
".",
"pop_aggregations_params",
"(",
")",
"if",
"self",
".",
"view",
".",
"_auth_enabled",
":",
"self",
".",
"check_aggregations_privacy",
"(",
"aggregations_params",
")",
"self",
".",
"stub_wrappers",
"(",
")",
"return",
"ES",
"(",
"self",
".",
"view",
".",
"Model",
".",
"__name__",
")",
".",
"aggregate",
"(",
"_aggregations_params",
"=",
"aggregations_params",
",",
"*",
"*",
"self",
".",
"_query_params",
")"
] |
Perform aggregation and return response.
|
[
"Perform",
"aggregation",
"and",
"return",
"response",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L195-L205
|
train
|
ramses-tech/nefertari
|
nefertari/utils/dictset.py
|
dictset.asdict
|
def asdict(self, name, _type=None, _set=False):
"""
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
"""
if _type is None:
_type = lambda t: t
dict_str = self.pop(name, None)
if not dict_str:
return {}
_dict = {}
for item in split_strip(dict_str):
key, _, val = item.partition(':')
val = _type(val)
if key in _dict:
if isinstance(_dict[key], list):
_dict[key].append(val)
else:
_dict[key] = [_dict[key], val]
else:
_dict[key] = val
if _set:
self[name] = _dict
return _dict
|
python
|
def asdict(self, name, _type=None, _set=False):
"""
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
"""
if _type is None:
_type = lambda t: t
dict_str = self.pop(name, None)
if not dict_str:
return {}
_dict = {}
for item in split_strip(dict_str):
key, _, val = item.partition(':')
val = _type(val)
if key in _dict:
if isinstance(_dict[key], list):
_dict[key].append(val)
else:
_dict[key] = [_dict[key], val]
else:
_dict[key] = val
if _set:
self[name] = _dict
return _dict
|
[
"def",
"asdict",
"(",
"self",
",",
"name",
",",
"_type",
"=",
"None",
",",
"_set",
"=",
"False",
")",
":",
"if",
"_type",
"is",
"None",
":",
"_type",
"=",
"lambda",
"t",
":",
"t",
"dict_str",
"=",
"self",
".",
"pop",
"(",
"name",
",",
"None",
")",
"if",
"not",
"dict_str",
":",
"return",
"{",
"}",
"_dict",
"=",
"{",
"}",
"for",
"item",
"in",
"split_strip",
"(",
"dict_str",
")",
":",
"key",
",",
"_",
",",
"val",
"=",
"item",
".",
"partition",
"(",
"':'",
")",
"val",
"=",
"_type",
"(",
"val",
")",
"if",
"key",
"in",
"_dict",
":",
"if",
"isinstance",
"(",
"_dict",
"[",
"key",
"]",
",",
"list",
")",
":",
"_dict",
"[",
"key",
"]",
".",
"append",
"(",
"val",
")",
"else",
":",
"_dict",
"[",
"key",
"]",
"=",
"[",
"_dict",
"[",
"key",
"]",
",",
"val",
"]",
"else",
":",
"_dict",
"[",
"key",
"]",
"=",
"val",
"if",
"_set",
":",
"self",
"[",
"name",
"]",
"=",
"_dict",
"return",
"_dict"
] |
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
|
[
"Turn",
"this",
"a",
":",
"2",
"b",
":",
"blabla",
"c",
":",
"True",
"a",
":",
"d",
"to",
"{",
"a",
":",
"[",
"2",
"d",
"]",
"b",
":",
"blabla",
"c",
":",
"True",
"}"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/dictset.py#L66-L95
|
train
|
timgabets/bpc8583
|
bpc8583/tools.py
|
get_random_hex
|
def get_random_hex(length):
"""
Return random hex string of a given length
"""
if length <= 0:
return ''
return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
|
python
|
def get_random_hex(length):
"""
Return random hex string of a given length
"""
if length <= 0:
return ''
return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
|
[
"def",
"get_random_hex",
"(",
"length",
")",
":",
"if",
"length",
"<=",
"0",
":",
"return",
"''",
"return",
"hexify",
"(",
"random",
".",
"randint",
"(",
"pow",
"(",
"2",
",",
"length",
"*",
"2",
")",
",",
"pow",
"(",
"2",
",",
"length",
"*",
"4",
")",
")",
")",
"[",
"0",
":",
"length",
"]"
] |
Return random hex string of a given length
|
[
"Return",
"random",
"hex",
"string",
"of",
"a",
"given",
"length"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/tools.py#L59-L65
|
train
|
timgabets/bpc8583
|
bpc8583/tools.py
|
get_response
|
def get_response(_code):
"""
Return xx1x response for xx0x codes (e.g. 0810 for 0800)
"""
if _code:
code = str(_code)
return code[:-2] + str(int(code[-2:-1]) + 1) + code[-1]
else:
return None
|
python
|
def get_response(_code):
"""
Return xx1x response for xx0x codes (e.g. 0810 for 0800)
"""
if _code:
code = str(_code)
return code[:-2] + str(int(code[-2:-1]) + 1) + code[-1]
else:
return None
|
[
"def",
"get_response",
"(",
"_code",
")",
":",
"if",
"_code",
":",
"code",
"=",
"str",
"(",
"_code",
")",
"return",
"code",
"[",
":",
"-",
"2",
"]",
"+",
"str",
"(",
"int",
"(",
"code",
"[",
"-",
"2",
":",
"-",
"1",
"]",
")",
"+",
"1",
")",
"+",
"code",
"[",
"-",
"1",
"]",
"else",
":",
"return",
"None"
] |
Return xx1x response for xx0x codes (e.g. 0810 for 0800)
|
[
"Return",
"xx1x",
"response",
"for",
"xx0x",
"codes",
"(",
"e",
".",
"g",
".",
"0810",
"for",
"0800",
")"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/tools.py#L68-L76
|
train
|
scalative/haas
|
haas/loader.py
|
Loader.load_case
|
def load_case(self, testcase):
"""Load a TestSuite containing all TestCase instances for all tests in
a TestCase subclass.
Parameters
----------
testcase : type
A subclass of :class:`unittest.TestCase`
"""
tests = [self.load_test(testcase, name)
for name in self.find_test_method_names(testcase)]
return self.create_suite(tests)
|
python
|
def load_case(self, testcase):
"""Load a TestSuite containing all TestCase instances for all tests in
a TestCase subclass.
Parameters
----------
testcase : type
A subclass of :class:`unittest.TestCase`
"""
tests = [self.load_test(testcase, name)
for name in self.find_test_method_names(testcase)]
return self.create_suite(tests)
|
[
"def",
"load_case",
"(",
"self",
",",
"testcase",
")",
":",
"tests",
"=",
"[",
"self",
".",
"load_test",
"(",
"testcase",
",",
"name",
")",
"for",
"name",
"in",
"self",
".",
"find_test_method_names",
"(",
"testcase",
")",
"]",
"return",
"self",
".",
"create_suite",
"(",
"tests",
")"
] |
Load a TestSuite containing all TestCase instances for all tests in
a TestCase subclass.
Parameters
----------
testcase : type
A subclass of :class:`unittest.TestCase`
|
[
"Load",
"a",
"TestSuite",
"containing",
"all",
"TestCase",
"instances",
"for",
"all",
"tests",
"in",
"a",
"TestCase",
"subclass",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/loader.py#L83-L95
|
train
|
scalative/haas
|
haas/loader.py
|
Loader.load_module
|
def load_module(self, module):
"""Create and return a test suite containing all cases loaded from the
provided module.
Parameters
----------
module : module
A module object containing ``TestCases``
"""
cases = self.get_test_cases_from_module(module)
suites = [self.load_case(case) for case in cases]
return self.create_suite(suites)
|
python
|
def load_module(self, module):
"""Create and return a test suite containing all cases loaded from the
provided module.
Parameters
----------
module : module
A module object containing ``TestCases``
"""
cases = self.get_test_cases_from_module(module)
suites = [self.load_case(case) for case in cases]
return self.create_suite(suites)
|
[
"def",
"load_module",
"(",
"self",
",",
"module",
")",
":",
"cases",
"=",
"self",
".",
"get_test_cases_from_module",
"(",
"module",
")",
"suites",
"=",
"[",
"self",
".",
"load_case",
"(",
"case",
")",
"for",
"case",
"in",
"cases",
"]",
"return",
"self",
".",
"create_suite",
"(",
"suites",
")"
] |
Create and return a test suite containing all cases loaded from the
provided module.
Parameters
----------
module : module
A module object containing ``TestCases``
|
[
"Create",
"and",
"return",
"a",
"test",
"suite",
"containing",
"all",
"cases",
"loaded",
"from",
"the",
"provided",
"module",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/loader.py#L112-L124
|
train
|
timgabets/bpc8583
|
bpc8583/ISO8583.py
|
ISO8583.Field
|
def Field(self, field, Value = None):
'''
Add field to bitmap
'''
if Value == None:
try:
return self.__Bitmap[field]
except KeyError:
return None
elif Value == 1 or Value == 0:
self.__Bitmap[field] = Value
else:
raise ValueError
|
python
|
def Field(self, field, Value = None):
'''
Add field to bitmap
'''
if Value == None:
try:
return self.__Bitmap[field]
except KeyError:
return None
elif Value == 1 or Value == 0:
self.__Bitmap[field] = Value
else:
raise ValueError
|
[
"def",
"Field",
"(",
"self",
",",
"field",
",",
"Value",
"=",
"None",
")",
":",
"if",
"Value",
"==",
"None",
":",
"try",
":",
"return",
"self",
".",
"__Bitmap",
"[",
"field",
"]",
"except",
"KeyError",
":",
"return",
"None",
"elif",
"Value",
"==",
"1",
"or",
"Value",
"==",
"0",
":",
"self",
".",
"__Bitmap",
"[",
"field",
"]",
"=",
"Value",
"else",
":",
"raise",
"ValueError"
] |
Add field to bitmap
|
[
"Add",
"field",
"to",
"bitmap"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/ISO8583.py#L396-L408
|
train
|
timgabets/bpc8583
|
bpc8583/ISO8583.py
|
ISO8583.FieldData
|
def FieldData(self, field, Value = None):
'''
Add field data
'''
if Value == None:
try:
return self.__FieldData[field]
except KeyError:
return None
else:
if len(str(Value)) > self.__IsoSpec.MaxLength(field):
raise ValueError('Value length larger than field maximum ({0})'.format(self.__IsoSpec.MaxLength(field)))
self.Field(field, Value=1)
self.__FieldData[field] = Value
|
python
|
def FieldData(self, field, Value = None):
'''
Add field data
'''
if Value == None:
try:
return self.__FieldData[field]
except KeyError:
return None
else:
if len(str(Value)) > self.__IsoSpec.MaxLength(field):
raise ValueError('Value length larger than field maximum ({0})'.format(self.__IsoSpec.MaxLength(field)))
self.Field(field, Value=1)
self.__FieldData[field] = Value
|
[
"def",
"FieldData",
"(",
"self",
",",
"field",
",",
"Value",
"=",
"None",
")",
":",
"if",
"Value",
"==",
"None",
":",
"try",
":",
"return",
"self",
".",
"__FieldData",
"[",
"field",
"]",
"except",
"KeyError",
":",
"return",
"None",
"else",
":",
"if",
"len",
"(",
"str",
"(",
"Value",
")",
")",
">",
"self",
".",
"__IsoSpec",
".",
"MaxLength",
"(",
"field",
")",
":",
"raise",
"ValueError",
"(",
"'Value length larger than field maximum ({0})'",
".",
"format",
"(",
"self",
".",
"__IsoSpec",
".",
"MaxLength",
"(",
"field",
")",
")",
")",
"self",
".",
"Field",
"(",
"field",
",",
"Value",
"=",
"1",
")",
"self",
".",
"__FieldData",
"[",
"field",
"]",
"=",
"Value"
] |
Add field data
|
[
"Add",
"field",
"data"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/ISO8583.py#L419-L433
|
train
|
ramses-tech/nefertari
|
nefertari/acl.py
|
authenticated_userid
|
def authenticated_userid(request):
"""Helper function that can be used in ``db_key`` to support `self`
as a collection key.
"""
user = getattr(request, 'user', None)
key = user.pk_field()
return getattr(user, key)
|
python
|
def authenticated_userid(request):
"""Helper function that can be used in ``db_key`` to support `self`
as a collection key.
"""
user = getattr(request, 'user', None)
key = user.pk_field()
return getattr(user, key)
|
[
"def",
"authenticated_userid",
"(",
"request",
")",
":",
"user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"key",
"=",
"user",
".",
"pk_field",
"(",
")",
"return",
"getattr",
"(",
"user",
",",
"key",
")"
] |
Helper function that can be used in ``db_key`` to support `self`
as a collection key.
|
[
"Helper",
"function",
"that",
"can",
"be",
"used",
"in",
"db_key",
"to",
"support",
"self",
"as",
"a",
"collection",
"key",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/acl.py#L68-L74
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin.iter_blocks
|
def iter_blocks(block_list):
"""A generator for blocks contained in a block list.
Yields tuples containing the block name, the depth that the block was
found at, and finally a handle to the block itself.
"""
# queue the block and the depth of the block
queue = [(block, 0) for block in block_list
if isinstance(block, kurt.Block)]
while queue:
block, depth = queue.pop(0)
assert block.type.text
yield block.type.text, depth, block
for arg in block.args:
if hasattr(arg, '__iter__'):
queue[0:0] = [(x, depth + 1) for x in arg
if isinstance(x, kurt.Block)]
elif isinstance(arg, kurt.Block):
queue.append((arg, depth))
|
python
|
def iter_blocks(block_list):
"""A generator for blocks contained in a block list.
Yields tuples containing the block name, the depth that the block was
found at, and finally a handle to the block itself.
"""
# queue the block and the depth of the block
queue = [(block, 0) for block in block_list
if isinstance(block, kurt.Block)]
while queue:
block, depth = queue.pop(0)
assert block.type.text
yield block.type.text, depth, block
for arg in block.args:
if hasattr(arg, '__iter__'):
queue[0:0] = [(x, depth + 1) for x in arg
if isinstance(x, kurt.Block)]
elif isinstance(arg, kurt.Block):
queue.append((arg, depth))
|
[
"def",
"iter_blocks",
"(",
"block_list",
")",
":",
"# queue the block and the depth of the block",
"queue",
"=",
"[",
"(",
"block",
",",
"0",
")",
"for",
"block",
"in",
"block_list",
"if",
"isinstance",
"(",
"block",
",",
"kurt",
".",
"Block",
")",
"]",
"while",
"queue",
":",
"block",
",",
"depth",
"=",
"queue",
".",
"pop",
"(",
"0",
")",
"assert",
"block",
".",
"type",
".",
"text",
"yield",
"block",
".",
"type",
".",
"text",
",",
"depth",
",",
"block",
"for",
"arg",
"in",
"block",
".",
"args",
":",
"if",
"hasattr",
"(",
"arg",
",",
"'__iter__'",
")",
":",
"queue",
"[",
"0",
":",
"0",
"]",
"=",
"[",
"(",
"x",
",",
"depth",
"+",
"1",
")",
"for",
"x",
"in",
"arg",
"if",
"isinstance",
"(",
"x",
",",
"kurt",
".",
"Block",
")",
"]",
"elif",
"isinstance",
"(",
"arg",
",",
"kurt",
".",
"Block",
")",
":",
"queue",
".",
"append",
"(",
"(",
"arg",
",",
"depth",
")",
")"
] |
A generator for blocks contained in a block list.
Yields tuples containing the block name, the depth that the block was
found at, and finally a handle to the block itself.
|
[
"A",
"generator",
"for",
"blocks",
"contained",
"in",
"a",
"block",
"list",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L48-L67
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin.iter_scripts
|
def iter_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield script
for sprite in scratch.sprites:
for script in sprite.scripts:
if not isinstance(script, kurt.Comment):
yield script
|
python
|
def iter_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield script
for sprite in scratch.sprites:
for script in sprite.scripts:
if not isinstance(script, kurt.Comment):
yield script
|
[
"def",
"iter_scripts",
"(",
"scratch",
")",
":",
"for",
"script",
"in",
"scratch",
".",
"stage",
".",
"scripts",
":",
"if",
"not",
"isinstance",
"(",
"script",
",",
"kurt",
".",
"Comment",
")",
":",
"yield",
"script",
"for",
"sprite",
"in",
"scratch",
".",
"sprites",
":",
"for",
"script",
"in",
"sprite",
".",
"scripts",
":",
"if",
"not",
"isinstance",
"(",
"script",
",",
"kurt",
".",
"Comment",
")",
":",
"yield",
"script"
] |
A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
|
[
"A",
"generator",
"for",
"all",
"scripts",
"contained",
"in",
"a",
"scratch",
"file",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L70-L82
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin.iter_sprite_scripts
|
def iter_sprite_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield ('Stage', script)
for sprite in scratch.sprites:
for script in sprite.scripts:
if not isinstance(script, kurt.Comment):
yield (sprite.name, script)
|
python
|
def iter_sprite_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield ('Stage', script)
for sprite in scratch.sprites:
for script in sprite.scripts:
if not isinstance(script, kurt.Comment):
yield (sprite.name, script)
|
[
"def",
"iter_sprite_scripts",
"(",
"scratch",
")",
":",
"for",
"script",
"in",
"scratch",
".",
"stage",
".",
"scripts",
":",
"if",
"not",
"isinstance",
"(",
"script",
",",
"kurt",
".",
"Comment",
")",
":",
"yield",
"(",
"'Stage'",
",",
"script",
")",
"for",
"sprite",
"in",
"scratch",
".",
"sprites",
":",
"for",
"script",
"in",
"sprite",
".",
"scripts",
":",
"if",
"not",
"isinstance",
"(",
"script",
",",
"kurt",
".",
"Comment",
")",
":",
"yield",
"(",
"sprite",
".",
"name",
",",
"script",
")"
] |
A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
|
[
"A",
"generator",
"for",
"all",
"scripts",
"contained",
"in",
"a",
"scratch",
"file",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L91-L103
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin.script_start_type
|
def script_start_type(script):
"""Return the type of block the script begins with."""
if script[0].type.text == 'when @greenFlag clicked':
return HairballPlugin.HAT_GREEN_FLAG
elif script[0].type.text == 'when I receive %s':
return HairballPlugin.HAT_WHEN_I_RECEIVE
elif script[0].type.text == 'when this sprite clicked':
return HairballPlugin.HAT_MOUSE
elif script[0].type.text == 'when %s key pressed':
return HairballPlugin.HAT_KEY
else:
return HairballPlugin.NO_HAT
|
python
|
def script_start_type(script):
"""Return the type of block the script begins with."""
if script[0].type.text == 'when @greenFlag clicked':
return HairballPlugin.HAT_GREEN_FLAG
elif script[0].type.text == 'when I receive %s':
return HairballPlugin.HAT_WHEN_I_RECEIVE
elif script[0].type.text == 'when this sprite clicked':
return HairballPlugin.HAT_MOUSE
elif script[0].type.text == 'when %s key pressed':
return HairballPlugin.HAT_KEY
else:
return HairballPlugin.NO_HAT
|
[
"def",
"script_start_type",
"(",
"script",
")",
":",
"if",
"script",
"[",
"0",
"]",
".",
"type",
".",
"text",
"==",
"'when @greenFlag clicked'",
":",
"return",
"HairballPlugin",
".",
"HAT_GREEN_FLAG",
"elif",
"script",
"[",
"0",
"]",
".",
"type",
".",
"text",
"==",
"'when I receive %s'",
":",
"return",
"HairballPlugin",
".",
"HAT_WHEN_I_RECEIVE",
"elif",
"script",
"[",
"0",
"]",
".",
"type",
".",
"text",
"==",
"'when this sprite clicked'",
":",
"return",
"HairballPlugin",
".",
"HAT_MOUSE",
"elif",
"script",
"[",
"0",
"]",
".",
"type",
".",
"text",
"==",
"'when %s key pressed'",
":",
"return",
"HairballPlugin",
".",
"HAT_KEY",
"else",
":",
"return",
"HairballPlugin",
".",
"NO_HAT"
] |
Return the type of block the script begins with.
|
[
"Return",
"the",
"type",
"of",
"block",
"the",
"script",
"begins",
"with",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L106-L117
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin.get_broadcast_events
|
def get_broadcast_events(cls, script):
"""Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable.
"""
events = Counter()
for name, _, block in cls.iter_blocks(script):
if 'broadcast %s' in name:
if isinstance(block.args[0], kurt.Block):
events[True] += 1
else:
events[block.args[0].lower()] += 1
return events
|
python
|
def get_broadcast_events(cls, script):
"""Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable.
"""
events = Counter()
for name, _, block in cls.iter_blocks(script):
if 'broadcast %s' in name:
if isinstance(block.args[0], kurt.Block):
events[True] += 1
else:
events[block.args[0].lower()] += 1
return events
|
[
"def",
"get_broadcast_events",
"(",
"cls",
",",
"script",
")",
":",
"events",
"=",
"Counter",
"(",
")",
"for",
"name",
",",
"_",
",",
"block",
"in",
"cls",
".",
"iter_blocks",
"(",
"script",
")",
":",
"if",
"'broadcast %s'",
"in",
"name",
":",
"if",
"isinstance",
"(",
"block",
".",
"args",
"[",
"0",
"]",
",",
"kurt",
".",
"Block",
")",
":",
"events",
"[",
"True",
"]",
"+=",
"1",
"else",
":",
"events",
"[",
"block",
".",
"args",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"]",
"+=",
"1",
"return",
"events"
] |
Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable.
|
[
"Return",
"a",
"Counter",
"of",
"event",
"-",
"names",
"that",
"were",
"broadcast",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L120-L134
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin.tag_reachable_scripts
|
def tag_reachable_scripts(cls, scratch):
"""Tag each script with attribute reachable.
The reachable attribute will be set false for any script that does not
begin with a hat block. Additionally, any script that begins with a
'when I receive' block whose event-name doesn't appear in a
corresponding broadcast block is marked as unreachable.
"""
if getattr(scratch, 'hairball_prepared', False): # Only process once
return
reachable = set()
untriggered_events = {}
# Initial pass to find reachable and potentially reachable scripts
for script in cls.iter_scripts(scratch):
if not isinstance(script, kurt.Comment):
starting_type = cls.script_start_type(script)
if starting_type == cls.NO_HAT:
script.reachable = False
elif starting_type == cls.HAT_WHEN_I_RECEIVE:
# Value will be updated if reachable
script.reachable = False
message = script[0].args[0].lower()
untriggered_events.setdefault(message, set()).add(script)
else:
script.reachable = True
reachable.add(script)
# Expand reachable states based on broadcast events
while reachable:
for event in cls.get_broadcast_events(reachable.pop()):
if event in untriggered_events:
for script in untriggered_events.pop(event):
script.reachable = True
reachable.add(script)
scratch.hairball_prepared = True
|
python
|
def tag_reachable_scripts(cls, scratch):
"""Tag each script with attribute reachable.
The reachable attribute will be set false for any script that does not
begin with a hat block. Additionally, any script that begins with a
'when I receive' block whose event-name doesn't appear in a
corresponding broadcast block is marked as unreachable.
"""
if getattr(scratch, 'hairball_prepared', False): # Only process once
return
reachable = set()
untriggered_events = {}
# Initial pass to find reachable and potentially reachable scripts
for script in cls.iter_scripts(scratch):
if not isinstance(script, kurt.Comment):
starting_type = cls.script_start_type(script)
if starting_type == cls.NO_HAT:
script.reachable = False
elif starting_type == cls.HAT_WHEN_I_RECEIVE:
# Value will be updated if reachable
script.reachable = False
message = script[0].args[0].lower()
untriggered_events.setdefault(message, set()).add(script)
else:
script.reachable = True
reachable.add(script)
# Expand reachable states based on broadcast events
while reachable:
for event in cls.get_broadcast_events(reachable.pop()):
if event in untriggered_events:
for script in untriggered_events.pop(event):
script.reachable = True
reachable.add(script)
scratch.hairball_prepared = True
|
[
"def",
"tag_reachable_scripts",
"(",
"cls",
",",
"scratch",
")",
":",
"if",
"getattr",
"(",
"scratch",
",",
"'hairball_prepared'",
",",
"False",
")",
":",
"# Only process once",
"return",
"reachable",
"=",
"set",
"(",
")",
"untriggered_events",
"=",
"{",
"}",
"# Initial pass to find reachable and potentially reachable scripts",
"for",
"script",
"in",
"cls",
".",
"iter_scripts",
"(",
"scratch",
")",
":",
"if",
"not",
"isinstance",
"(",
"script",
",",
"kurt",
".",
"Comment",
")",
":",
"starting_type",
"=",
"cls",
".",
"script_start_type",
"(",
"script",
")",
"if",
"starting_type",
"==",
"cls",
".",
"NO_HAT",
":",
"script",
".",
"reachable",
"=",
"False",
"elif",
"starting_type",
"==",
"cls",
".",
"HAT_WHEN_I_RECEIVE",
":",
"# Value will be updated if reachable",
"script",
".",
"reachable",
"=",
"False",
"message",
"=",
"script",
"[",
"0",
"]",
".",
"args",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"untriggered_events",
".",
"setdefault",
"(",
"message",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"script",
")",
"else",
":",
"script",
".",
"reachable",
"=",
"True",
"reachable",
".",
"add",
"(",
"script",
")",
"# Expand reachable states based on broadcast events",
"while",
"reachable",
":",
"for",
"event",
"in",
"cls",
".",
"get_broadcast_events",
"(",
"reachable",
".",
"pop",
"(",
")",
")",
":",
"if",
"event",
"in",
"untriggered_events",
":",
"for",
"script",
"in",
"untriggered_events",
".",
"pop",
"(",
"event",
")",
":",
"script",
".",
"reachable",
"=",
"True",
"reachable",
".",
"add",
"(",
"script",
")",
"scratch",
".",
"hairball_prepared",
"=",
"True"
] |
Tag each script with attribute reachable.
The reachable attribute will be set false for any script that does not
begin with a hat block. Additionally, any script that begins with a
'when I receive' block whose event-name doesn't appear in a
corresponding broadcast block is marked as unreachable.
|
[
"Tag",
"each",
"script",
"with",
"attribute",
"reachable",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L137-L172
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin.description
|
def description(self):
"""Attribute that returns the plugin description from its docstring."""
lines = []
for line in self.__doc__.split('\n')[2:]:
line = line.strip()
if line:
lines.append(line)
return ' '.join(lines)
|
python
|
def description(self):
"""Attribute that returns the plugin description from its docstring."""
lines = []
for line in self.__doc__.split('\n')[2:]:
line = line.strip()
if line:
lines.append(line)
return ' '.join(lines)
|
[
"def",
"description",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"__doc__",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
":",
"]",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"lines",
".",
"append",
"(",
"line",
")",
"return",
"' '",
".",
"join",
"(",
"lines",
")"
] |
Attribute that returns the plugin description from its docstring.
|
[
"Attribute",
"that",
"returns",
"the",
"plugin",
"description",
"from",
"its",
"docstring",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L175-L182
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/__init__.py
|
HairballPlugin._process
|
def _process(self, scratch, filename, **kwargs):
"""Internal hook that marks reachable scripts before calling analyze.
Returns data exactly as returned by the analyze method.
"""
self.tag_reachable_scripts(scratch)
return self.analyze(scratch, filename=filename, **kwargs)
|
python
|
def _process(self, scratch, filename, **kwargs):
"""Internal hook that marks reachable scripts before calling analyze.
Returns data exactly as returned by the analyze method.
"""
self.tag_reachable_scripts(scratch)
return self.analyze(scratch, filename=filename, **kwargs)
|
[
"def",
"_process",
"(",
"self",
",",
"scratch",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"tag_reachable_scripts",
"(",
"scratch",
")",
"return",
"self",
".",
"analyze",
"(",
"scratch",
",",
"filename",
"=",
"filename",
",",
"*",
"*",
"kwargs",
")"
] |
Internal hook that marks reachable scripts before calling analyze.
Returns data exactly as returned by the analyze method.
|
[
"Internal",
"hook",
"that",
"marks",
"reachable",
"scripts",
"before",
"calling",
"analyze",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L189-L196
|
train
|
mmulqueen/odswriter
|
odswriter/__init__.py
|
ODSWriter.close
|
def close(self):
"""
Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement,
you must call this manually, it is not triggered automatically like on a file object.
:return: Nothing.
"""
self.zipf.writestr("content.xml", self.dom.toxml().encode("utf-8"))
self.zipf.close()
|
python
|
def close(self):
"""
Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement,
you must call this manually, it is not triggered automatically like on a file object.
:return: Nothing.
"""
self.zipf.writestr("content.xml", self.dom.toxml().encode("utf-8"))
self.zipf.close()
|
[
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"zipf",
".",
"writestr",
"(",
"\"content.xml\"",
",",
"self",
".",
"dom",
".",
"toxml",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"self",
".",
"zipf",
".",
"close",
"(",
")"
] |
Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement,
you must call this manually, it is not triggered automatically like on a file object.
:return: Nothing.
|
[
"Finalises",
"the",
"compressed",
"version",
"of",
"the",
"spreadsheet",
".",
"If",
"you",
"aren",
"t",
"using",
"the",
"context",
"manager",
"(",
"with",
"statement",
"you",
"must",
"call",
"this",
"manually",
"it",
"is",
"not",
"triggered",
"automatically",
"like",
"on",
"a",
"file",
"object",
".",
":",
"return",
":",
"Nothing",
"."
] |
0bb038a60dd27bacd76d6b1ff3a200e2a7729651
|
https://github.com/mmulqueen/odswriter/blob/0bb038a60dd27bacd76d6b1ff3a200e2a7729651/odswriter/__init__.py#L49-L56
|
train
|
mmulqueen/odswriter
|
odswriter/__init__.py
|
ODSWriter.writerow
|
def writerow(self, cells):
"""
Write a row of cells into the default sheet of the spreadsheet.
:param cells: A list of cells (most basic Python types supported).
:return: Nothing.
"""
if self.default_sheet is None:
self.default_sheet = self.new_sheet()
self.default_sheet.writerow(cells)
|
python
|
def writerow(self, cells):
"""
Write a row of cells into the default sheet of the spreadsheet.
:param cells: A list of cells (most basic Python types supported).
:return: Nothing.
"""
if self.default_sheet is None:
self.default_sheet = self.new_sheet()
self.default_sheet.writerow(cells)
|
[
"def",
"writerow",
"(",
"self",
",",
"cells",
")",
":",
"if",
"self",
".",
"default_sheet",
"is",
"None",
":",
"self",
".",
"default_sheet",
"=",
"self",
".",
"new_sheet",
"(",
")",
"self",
".",
"default_sheet",
".",
"writerow",
"(",
"cells",
")"
] |
Write a row of cells into the default sheet of the spreadsheet.
:param cells: A list of cells (most basic Python types supported).
:return: Nothing.
|
[
"Write",
"a",
"row",
"of",
"cells",
"into",
"the",
"default",
"sheet",
"of",
"the",
"spreadsheet",
".",
":",
"param",
"cells",
":",
"A",
"list",
"of",
"cells",
"(",
"most",
"basic",
"Python",
"types",
"supported",
")",
".",
":",
"return",
":",
"Nothing",
"."
] |
0bb038a60dd27bacd76d6b1ff3a200e2a7729651
|
https://github.com/mmulqueen/odswriter/blob/0bb038a60dd27bacd76d6b1ff3a200e2a7729651/odswriter/__init__.py#L58-L66
|
train
|
mmulqueen/odswriter
|
odswriter/__init__.py
|
ODSWriter.new_sheet
|
def new_sheet(self, name=None, cols=None):
"""
Create a new sheet in the spreadsheet and return it so content can be added.
:param name: Optional name for the sheet.
:param cols: Specify the number of columns, needed for compatibility in some cases
:return: Sheet object
"""
sheet = Sheet(self.dom, name, cols)
self.sheets.append(sheet)
return sheet
|
python
|
def new_sheet(self, name=None, cols=None):
"""
Create a new sheet in the spreadsheet and return it so content can be added.
:param name: Optional name for the sheet.
:param cols: Specify the number of columns, needed for compatibility in some cases
:return: Sheet object
"""
sheet = Sheet(self.dom, name, cols)
self.sheets.append(sheet)
return sheet
|
[
"def",
"new_sheet",
"(",
"self",
",",
"name",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"sheet",
"=",
"Sheet",
"(",
"self",
".",
"dom",
",",
"name",
",",
"cols",
")",
"self",
".",
"sheets",
".",
"append",
"(",
"sheet",
")",
"return",
"sheet"
] |
Create a new sheet in the spreadsheet and return it so content can be added.
:param name: Optional name for the sheet.
:param cols: Specify the number of columns, needed for compatibility in some cases
:return: Sheet object
|
[
"Create",
"a",
"new",
"sheet",
"in",
"the",
"spreadsheet",
"and",
"return",
"it",
"so",
"content",
"can",
"be",
"added",
".",
":",
"param",
"name",
":",
"Optional",
"name",
"for",
"the",
"sheet",
".",
":",
"param",
"cols",
":",
"Specify",
"the",
"number",
"of",
"columns",
"needed",
"for",
"compatibility",
"in",
"some",
"cases",
":",
"return",
":",
"Sheet",
"object"
] |
0bb038a60dd27bacd76d6b1ff3a200e2a7729651
|
https://github.com/mmulqueen/odswriter/blob/0bb038a60dd27bacd76d6b1ff3a200e2a7729651/odswriter/__init__.py#L77-L86
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
_format_kwargs
|
def _format_kwargs(func):
"""Decorator to handle formatting kwargs to the proper names expected by
the associated function. The formats dictionary string keys will be used as
expected function kwargs and the value list of strings will be renamed to
the associated key string."""
formats = {}
formats['blk'] = ["blank"]
formats['dft'] = ["default"]
formats['hdr'] = ["header"]
formats['hlp'] = ["help"]
formats['msg'] = ["message"]
formats['shw'] = ["show"]
formats['vld'] = ["valid"]
@wraps(func)
def inner(*args, **kwargs):
for k in formats.keys():
for v in formats[k]:
if v in kwargs:
kwargs[k] = kwargs[v]
kwargs.pop(v)
return func(*args, **kwargs)
return inner
|
python
|
def _format_kwargs(func):
"""Decorator to handle formatting kwargs to the proper names expected by
the associated function. The formats dictionary string keys will be used as
expected function kwargs and the value list of strings will be renamed to
the associated key string."""
formats = {}
formats['blk'] = ["blank"]
formats['dft'] = ["default"]
formats['hdr'] = ["header"]
formats['hlp'] = ["help"]
formats['msg'] = ["message"]
formats['shw'] = ["show"]
formats['vld'] = ["valid"]
@wraps(func)
def inner(*args, **kwargs):
for k in formats.keys():
for v in formats[k]:
if v in kwargs:
kwargs[k] = kwargs[v]
kwargs.pop(v)
return func(*args, **kwargs)
return inner
|
[
"def",
"_format_kwargs",
"(",
"func",
")",
":",
"formats",
"=",
"{",
"}",
"formats",
"[",
"'blk'",
"]",
"=",
"[",
"\"blank\"",
"]",
"formats",
"[",
"'dft'",
"]",
"=",
"[",
"\"default\"",
"]",
"formats",
"[",
"'hdr'",
"]",
"=",
"[",
"\"header\"",
"]",
"formats",
"[",
"'hlp'",
"]",
"=",
"[",
"\"help\"",
"]",
"formats",
"[",
"'msg'",
"]",
"=",
"[",
"\"message\"",
"]",
"formats",
"[",
"'shw'",
"]",
"=",
"[",
"\"show\"",
"]",
"formats",
"[",
"'vld'",
"]",
"=",
"[",
"\"valid\"",
"]",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
"in",
"formats",
".",
"keys",
"(",
")",
":",
"for",
"v",
"in",
"formats",
"[",
"k",
"]",
":",
"if",
"v",
"in",
"kwargs",
":",
"kwargs",
"[",
"k",
"]",
"=",
"kwargs",
"[",
"v",
"]",
"kwargs",
".",
"pop",
"(",
"v",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner"
] |
Decorator to handle formatting kwargs to the proper names expected by
the associated function. The formats dictionary string keys will be used as
expected function kwargs and the value list of strings will be renamed to
the associated key string.
|
[
"Decorator",
"to",
"handle",
"formatting",
"kwargs",
"to",
"the",
"proper",
"names",
"expected",
"by",
"the",
"associated",
"function",
".",
"The",
"formats",
"dictionary",
"string",
"keys",
"will",
"be",
"used",
"as",
"expected",
"function",
"kwargs",
"and",
"the",
"value",
"list",
"of",
"strings",
"will",
"be",
"renamed",
"to",
"the",
"associated",
"key",
"string",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L34-L55
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
show_limit
|
def show_limit(entries, **kwargs):
"""Shows a menu but limits the number of entries shown at a time.
Functionally equivalent to `show_menu()` with the `limit` parameter set."""
limit = kwargs.pop('limit', 5)
if limit <= 0:
return show_menu(entries, **kwargs)
istart = 0 # Index of group start.
iend = limit # Index of group end.
dft = kwargs.pop('dft', None)
if type(dft) == int:
dft = str(dft)
while True:
if iend > len(entries):
iend = len(entries)
istart = iend - limit
if istart < 0:
istart = 0
iend = limit
unext = len(entries) - iend # Number of next entries.
uprev = istart # Number of previous entries.
nnext = "" # Name of 'next' menu entry.
nprev = "" # Name of 'prev' menu entry.
dnext = "" # Description of 'next' menu entry.
dprev = "" # Description of 'prev' menu entry.
group = copy.deepcopy(entries[istart:iend])
names = [i.name for i in group]
if unext > 0:
for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]:
if i not in names:
nnext = i
dnext = "Next %u of %u entries" % (unext, len(entries))
group.append(MenuEntry(nnext, dnext, None, None, None))
names.append("n")
break
if uprev > 0:
for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]:
if i not in names:
nprev = i
dprev = "Previous %u of %u entries" % (uprev, len(entries))
group.append(MenuEntry(nprev, dprev, None, None, None))
names.append("p")
break
tmpdft = None
if dft != None:
if dft not in names:
if "n" in names:
tmpdft = "n"
else:
tmpdft = dft
result = show_menu(group, dft=tmpdft, **kwargs)
if result == nnext or result == dnext:
istart += limit
iend += limit
elif result == nprev or result == dprev:
istart -= limit
iend -= limit
else:
return result
|
python
|
def show_limit(entries, **kwargs):
"""Shows a menu but limits the number of entries shown at a time.
Functionally equivalent to `show_menu()` with the `limit` parameter set."""
limit = kwargs.pop('limit', 5)
if limit <= 0:
return show_menu(entries, **kwargs)
istart = 0 # Index of group start.
iend = limit # Index of group end.
dft = kwargs.pop('dft', None)
if type(dft) == int:
dft = str(dft)
while True:
if iend > len(entries):
iend = len(entries)
istart = iend - limit
if istart < 0:
istart = 0
iend = limit
unext = len(entries) - iend # Number of next entries.
uprev = istart # Number of previous entries.
nnext = "" # Name of 'next' menu entry.
nprev = "" # Name of 'prev' menu entry.
dnext = "" # Description of 'next' menu entry.
dprev = "" # Description of 'prev' menu entry.
group = copy.deepcopy(entries[istart:iend])
names = [i.name for i in group]
if unext > 0:
for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]:
if i not in names:
nnext = i
dnext = "Next %u of %u entries" % (unext, len(entries))
group.append(MenuEntry(nnext, dnext, None, None, None))
names.append("n")
break
if uprev > 0:
for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]:
if i not in names:
nprev = i
dprev = "Previous %u of %u entries" % (uprev, len(entries))
group.append(MenuEntry(nprev, dprev, None, None, None))
names.append("p")
break
tmpdft = None
if dft != None:
if dft not in names:
if "n" in names:
tmpdft = "n"
else:
tmpdft = dft
result = show_menu(group, dft=tmpdft, **kwargs)
if result == nnext or result == dnext:
istart += limit
iend += limit
elif result == nprev or result == dprev:
istart -= limit
iend -= limit
else:
return result
|
[
"def",
"show_limit",
"(",
"entries",
",",
"*",
"*",
"kwargs",
")",
":",
"limit",
"=",
"kwargs",
".",
"pop",
"(",
"'limit'",
",",
"5",
")",
"if",
"limit",
"<=",
"0",
":",
"return",
"show_menu",
"(",
"entries",
",",
"*",
"*",
"kwargs",
")",
"istart",
"=",
"0",
"# Index of group start.",
"iend",
"=",
"limit",
"# Index of group end.",
"dft",
"=",
"kwargs",
".",
"pop",
"(",
"'dft'",
",",
"None",
")",
"if",
"type",
"(",
"dft",
")",
"==",
"int",
":",
"dft",
"=",
"str",
"(",
"dft",
")",
"while",
"True",
":",
"if",
"iend",
">",
"len",
"(",
"entries",
")",
":",
"iend",
"=",
"len",
"(",
"entries",
")",
"istart",
"=",
"iend",
"-",
"limit",
"if",
"istart",
"<",
"0",
":",
"istart",
"=",
"0",
"iend",
"=",
"limit",
"unext",
"=",
"len",
"(",
"entries",
")",
"-",
"iend",
"# Number of next entries.",
"uprev",
"=",
"istart",
"# Number of previous entries.",
"nnext",
"=",
"\"\"",
"# Name of 'next' menu entry.",
"nprev",
"=",
"\"\"",
"# Name of 'prev' menu entry.",
"dnext",
"=",
"\"\"",
"# Description of 'next' menu entry.",
"dprev",
"=",
"\"\"",
"# Description of 'prev' menu entry.",
"group",
"=",
"copy",
".",
"deepcopy",
"(",
"entries",
"[",
"istart",
":",
"iend",
"]",
")",
"names",
"=",
"[",
"i",
".",
"name",
"for",
"i",
"in",
"group",
"]",
"if",
"unext",
">",
"0",
":",
"for",
"i",
"in",
"[",
"\"n\"",
",",
"\"N\"",
",",
"\"next\"",
",",
"\"NEXT\"",
",",
"\"->\"",
",",
"\">>\"",
",",
"\">>>\"",
"]",
":",
"if",
"i",
"not",
"in",
"names",
":",
"nnext",
"=",
"i",
"dnext",
"=",
"\"Next %u of %u entries\"",
"%",
"(",
"unext",
",",
"len",
"(",
"entries",
")",
")",
"group",
".",
"append",
"(",
"MenuEntry",
"(",
"nnext",
",",
"dnext",
",",
"None",
",",
"None",
",",
"None",
")",
")",
"names",
".",
"append",
"(",
"\"n\"",
")",
"break",
"if",
"uprev",
">",
"0",
":",
"for",
"i",
"in",
"[",
"\"p\"",
",",
"\"P\"",
",",
"\"prev\"",
",",
"\"PREV\"",
",",
"\"<-\"",
",",
"\"<<\"",
",",
"\"<<<\"",
"]",
":",
"if",
"i",
"not",
"in",
"names",
":",
"nprev",
"=",
"i",
"dprev",
"=",
"\"Previous %u of %u entries\"",
"%",
"(",
"uprev",
",",
"len",
"(",
"entries",
")",
")",
"group",
".",
"append",
"(",
"MenuEntry",
"(",
"nprev",
",",
"dprev",
",",
"None",
",",
"None",
",",
"None",
")",
")",
"names",
".",
"append",
"(",
"\"p\"",
")",
"break",
"tmpdft",
"=",
"None",
"if",
"dft",
"!=",
"None",
":",
"if",
"dft",
"not",
"in",
"names",
":",
"if",
"\"n\"",
"in",
"names",
":",
"tmpdft",
"=",
"\"n\"",
"else",
":",
"tmpdft",
"=",
"dft",
"result",
"=",
"show_menu",
"(",
"group",
",",
"dft",
"=",
"tmpdft",
",",
"*",
"*",
"kwargs",
")",
"if",
"result",
"==",
"nnext",
"or",
"result",
"==",
"dnext",
":",
"istart",
"+=",
"limit",
"iend",
"+=",
"limit",
"elif",
"result",
"==",
"nprev",
"or",
"result",
"==",
"dprev",
":",
"istart",
"-=",
"limit",
"iend",
"-=",
"limit",
"else",
":",
"return",
"result"
] |
Shows a menu but limits the number of entries shown at a time.
Functionally equivalent to `show_menu()` with the `limit` parameter set.
|
[
"Shows",
"a",
"menu",
"but",
"limits",
"the",
"number",
"of",
"entries",
"shown",
"at",
"a",
"time",
".",
"Functionally",
"equivalent",
"to",
"show_menu",
"()",
"with",
"the",
"limit",
"parameter",
"set",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L258-L315
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
show_menu
|
def show_menu(entries, **kwargs):
"""Shows a menu with the given list of `MenuEntry` items.
**Params**:
- header (str) - String to show above menu.
- note (str) - String to show as a note below menu.
- msg (str) - String to show below menu.
- dft (str) - Default value if input is left blank.
- compact (bool) - If true, the menu items will not be displayed
[default: False].
- returns (str) - Controls what part of the menu entry is returned,
'func' returns function result [default: name].
- limit (int) - If set, limits the number of menu entries show at a time
[default: None].
- fzf (bool) - If true, can enter FCHR at the menu prompt to search menu.
"""
global _AUTO
hdr = kwargs.get('hdr', "")
note = kwargs.get('note', "")
dft = kwargs.get('dft', "")
fzf = kwargs.pop('fzf', True)
compact = kwargs.get('compact', False)
returns = kwargs.get('returns', "name")
limit = kwargs.get('limit', None)
dft = kwargs.get('dft', None)
msg = []
if limit:
return show_limit(entries, **kwargs)
def show_banner():
banner = "-- MENU"
if hdr:
banner += ": " + hdr
banner += " --"
msg.append(banner)
if _AUTO:
return
for i in entries:
msg.append(" (%s) %s" % (i.name, i.desc))
valid = [i.name for i in entries]
if type(dft) == int:
dft = str(dft)
if dft not in valid:
dft = None
if not compact:
show_banner()
if note and not _AUTO:
msg.append("[!] " + note)
if fzf:
valid.append(FCHR)
msg.append(QSTR + kwargs.get('msg', "Enter menu selection"))
msg = os.linesep.join(msg)
entry = None
while entry not in entries:
choice = ask(msg, vld=valid, dft=dft, qstr=False)
if choice == FCHR and fzf:
try:
from iterfzf import iterfzf
choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0]
except:
warn("Issue encountered during fzf search.")
match = [i for i in entries if i.name == choice]
if match:
entry = match[0]
if entry.func:
fresult = run_func(entry)
if "func" == returns:
return fresult
try:
return getattr(entry, returns)
except:
return getattr(entry, "name")
|
python
|
def show_menu(entries, **kwargs):
"""Shows a menu with the given list of `MenuEntry` items.
**Params**:
- header (str) - String to show above menu.
- note (str) - String to show as a note below menu.
- msg (str) - String to show below menu.
- dft (str) - Default value if input is left blank.
- compact (bool) - If true, the menu items will not be displayed
[default: False].
- returns (str) - Controls what part of the menu entry is returned,
'func' returns function result [default: name].
- limit (int) - If set, limits the number of menu entries show at a time
[default: None].
- fzf (bool) - If true, can enter FCHR at the menu prompt to search menu.
"""
global _AUTO
hdr = kwargs.get('hdr', "")
note = kwargs.get('note', "")
dft = kwargs.get('dft', "")
fzf = kwargs.pop('fzf', True)
compact = kwargs.get('compact', False)
returns = kwargs.get('returns', "name")
limit = kwargs.get('limit', None)
dft = kwargs.get('dft', None)
msg = []
if limit:
return show_limit(entries, **kwargs)
def show_banner():
banner = "-- MENU"
if hdr:
banner += ": " + hdr
banner += " --"
msg.append(banner)
if _AUTO:
return
for i in entries:
msg.append(" (%s) %s" % (i.name, i.desc))
valid = [i.name for i in entries]
if type(dft) == int:
dft = str(dft)
if dft not in valid:
dft = None
if not compact:
show_banner()
if note and not _AUTO:
msg.append("[!] " + note)
if fzf:
valid.append(FCHR)
msg.append(QSTR + kwargs.get('msg', "Enter menu selection"))
msg = os.linesep.join(msg)
entry = None
while entry not in entries:
choice = ask(msg, vld=valid, dft=dft, qstr=False)
if choice == FCHR and fzf:
try:
from iterfzf import iterfzf
choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0]
except:
warn("Issue encountered during fzf search.")
match = [i for i in entries if i.name == choice]
if match:
entry = match[0]
if entry.func:
fresult = run_func(entry)
if "func" == returns:
return fresult
try:
return getattr(entry, returns)
except:
return getattr(entry, "name")
|
[
"def",
"show_menu",
"(",
"entries",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_AUTO",
"hdr",
"=",
"kwargs",
".",
"get",
"(",
"'hdr'",
",",
"\"\"",
")",
"note",
"=",
"kwargs",
".",
"get",
"(",
"'note'",
",",
"\"\"",
")",
"dft",
"=",
"kwargs",
".",
"get",
"(",
"'dft'",
",",
"\"\"",
")",
"fzf",
"=",
"kwargs",
".",
"pop",
"(",
"'fzf'",
",",
"True",
")",
"compact",
"=",
"kwargs",
".",
"get",
"(",
"'compact'",
",",
"False",
")",
"returns",
"=",
"kwargs",
".",
"get",
"(",
"'returns'",
",",
"\"name\"",
")",
"limit",
"=",
"kwargs",
".",
"get",
"(",
"'limit'",
",",
"None",
")",
"dft",
"=",
"kwargs",
".",
"get",
"(",
"'dft'",
",",
"None",
")",
"msg",
"=",
"[",
"]",
"if",
"limit",
":",
"return",
"show_limit",
"(",
"entries",
",",
"*",
"*",
"kwargs",
")",
"def",
"show_banner",
"(",
")",
":",
"banner",
"=",
"\"-- MENU\"",
"if",
"hdr",
":",
"banner",
"+=",
"\": \"",
"+",
"hdr",
"banner",
"+=",
"\" --\"",
"msg",
".",
"append",
"(",
"banner",
")",
"if",
"_AUTO",
":",
"return",
"for",
"i",
"in",
"entries",
":",
"msg",
".",
"append",
"(",
"\" (%s) %s\"",
"%",
"(",
"i",
".",
"name",
",",
"i",
".",
"desc",
")",
")",
"valid",
"=",
"[",
"i",
".",
"name",
"for",
"i",
"in",
"entries",
"]",
"if",
"type",
"(",
"dft",
")",
"==",
"int",
":",
"dft",
"=",
"str",
"(",
"dft",
")",
"if",
"dft",
"not",
"in",
"valid",
":",
"dft",
"=",
"None",
"if",
"not",
"compact",
":",
"show_banner",
"(",
")",
"if",
"note",
"and",
"not",
"_AUTO",
":",
"msg",
".",
"append",
"(",
"\"[!] \"",
"+",
"note",
")",
"if",
"fzf",
":",
"valid",
".",
"append",
"(",
"FCHR",
")",
"msg",
".",
"append",
"(",
"QSTR",
"+",
"kwargs",
".",
"get",
"(",
"'msg'",
",",
"\"Enter menu selection\"",
")",
")",
"msg",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"msg",
")",
"entry",
"=",
"None",
"while",
"entry",
"not",
"in",
"entries",
":",
"choice",
"=",
"ask",
"(",
"msg",
",",
"vld",
"=",
"valid",
",",
"dft",
"=",
"dft",
",",
"qstr",
"=",
"False",
")",
"if",
"choice",
"==",
"FCHR",
"and",
"fzf",
":",
"try",
":",
"from",
"iterfzf",
"import",
"iterfzf",
"choice",
"=",
"iterfzf",
"(",
"reversed",
"(",
"[",
"\"%s\\t%s\"",
"%",
"(",
"i",
".",
"name",
",",
"i",
".",
"desc",
")",
"for",
"i",
"in",
"entries",
"]",
")",
")",
".",
"strip",
"(",
"\"\\0\"",
")",
".",
"split",
"(",
"\"\\t\"",
",",
"1",
")",
"[",
"0",
"]",
"except",
":",
"warn",
"(",
"\"Issue encountered during fzf search.\"",
")",
"match",
"=",
"[",
"i",
"for",
"i",
"in",
"entries",
"if",
"i",
".",
"name",
"==",
"choice",
"]",
"if",
"match",
":",
"entry",
"=",
"match",
"[",
"0",
"]",
"if",
"entry",
".",
"func",
":",
"fresult",
"=",
"run_func",
"(",
"entry",
")",
"if",
"\"func\"",
"==",
"returns",
":",
"return",
"fresult",
"try",
":",
"return",
"getattr",
"(",
"entry",
",",
"returns",
")",
"except",
":",
"return",
"getattr",
"(",
"entry",
",",
"\"name\"",
")"
] |
Shows a menu with the given list of `MenuEntry` items.
**Params**:
- header (str) - String to show above menu.
- note (str) - String to show as a note below menu.
- msg (str) - String to show below menu.
- dft (str) - Default value if input is left blank.
- compact (bool) - If true, the menu items will not be displayed
[default: False].
- returns (str) - Controls what part of the menu entry is returned,
'func' returns function result [default: name].
- limit (int) - If set, limits the number of menu entries show at a time
[default: None].
- fzf (bool) - If true, can enter FCHR at the menu prompt to search menu.
|
[
"Shows",
"a",
"menu",
"with",
"the",
"given",
"list",
"of",
"MenuEntry",
"items",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L318-L388
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
run_func
|
def run_func(entry):
"""Runs the function associated with the given MenuEntry."""
if entry.func:
if entry.args and entry.krgs:
return entry.func(*entry.args, **entry.krgs)
if entry.args:
return entry.func(*entry.args)
if entry.krgs:
return entry.func(**entry.krgs)
return entry.func()
|
python
|
def run_func(entry):
"""Runs the function associated with the given MenuEntry."""
if entry.func:
if entry.args and entry.krgs:
return entry.func(*entry.args, **entry.krgs)
if entry.args:
return entry.func(*entry.args)
if entry.krgs:
return entry.func(**entry.krgs)
return entry.func()
|
[
"def",
"run_func",
"(",
"entry",
")",
":",
"if",
"entry",
".",
"func",
":",
"if",
"entry",
".",
"args",
"and",
"entry",
".",
"krgs",
":",
"return",
"entry",
".",
"func",
"(",
"*",
"entry",
".",
"args",
",",
"*",
"*",
"entry",
".",
"krgs",
")",
"if",
"entry",
".",
"args",
":",
"return",
"entry",
".",
"func",
"(",
"*",
"entry",
".",
"args",
")",
"if",
"entry",
".",
"krgs",
":",
"return",
"entry",
".",
"func",
"(",
"*",
"*",
"entry",
".",
"krgs",
")",
"return",
"entry",
".",
"func",
"(",
")"
] |
Runs the function associated with the given MenuEntry.
|
[
"Runs",
"the",
"function",
"associated",
"with",
"the",
"given",
"MenuEntry",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L390-L399
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
enum_menu
|
def enum_menu(strs, menu=None, *args, **kwargs):
"""Enumerates the given list of strings into returned menu.
**Params**:
- menu (Menu) - Existing menu to append. If not provided, a new menu will
be created.
"""
if not menu:
menu = Menu(*args, **kwargs)
for s in strs:
menu.enum(s)
return menu
|
python
|
def enum_menu(strs, menu=None, *args, **kwargs):
"""Enumerates the given list of strings into returned menu.
**Params**:
- menu (Menu) - Existing menu to append. If not provided, a new menu will
be created.
"""
if not menu:
menu = Menu(*args, **kwargs)
for s in strs:
menu.enum(s)
return menu
|
[
"def",
"enum_menu",
"(",
"strs",
",",
"menu",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"menu",
":",
"menu",
"=",
"Menu",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"s",
"in",
"strs",
":",
"menu",
".",
"enum",
"(",
"s",
")",
"return",
"menu"
] |
Enumerates the given list of strings into returned menu.
**Params**:
- menu (Menu) - Existing menu to append. If not provided, a new menu will
be created.
|
[
"Enumerates",
"the",
"given",
"list",
"of",
"strings",
"into",
"returned",
"menu",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L401-L412
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
ask
|
def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True):
"""Prompts the user for input and returns the given answer. Optionally
checks if answer is valid.
**Params**:
- msg (str) - Message to prompt the user with.
- fmt (func) - Function used to format user input.
- dft (int|float|str) - Default value if input is left blank.
- vld ([int|float|str|func]) - Valid input entries.
- shw (bool) - If true, show the user's input as typed.
- blk (bool) - If true, accept a blank string as valid input. Note that
supplying a default value will disable accepting blank input.
"""
global _AUTO
def print_help():
lst = [v for v in vld if not callable(v)]
if blk:
lst.remove("")
for v in vld:
if not callable(v):
continue
if int == v:
lst.append("<int>")
elif float == v:
lst.append("<float>")
elif str == v:
lst.append("<str>")
else:
lst.append("(" + v.__name__ + ")")
if lst:
echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst])))
if hlp:
echo("[HELP] Extra notes: " + hlp)
if blk:
echo("[HELP] Input may be blank.")
vld = vld or []
hlp = hlp or ""
if not hasattr(vld, "__iter__"):
vld = [vld]
if not hasattr(fmt, "__call__"):
fmt = lambda x: x # NOTE: Defaults to function that does nothing.
msg = "%s%s" % (QSTR if qstr else "", msg)
dft = fmt(dft) if dft != None else None # Prevents showing [None] default.
if dft != None:
msg += " [%s]" % (dft if type(dft) is str else repr(dft))
vld.append(dft)
blk = False
if vld:
# Sanitize valid inputs.
vld = list(set([fmt(v) if fmt(v) else v for v in vld]))
if blk and "" not in vld:
vld.append("")
# NOTE: The following fixes a Py3 related bug found in `0.8.1`.
try: vld = sorted(vld)
except: pass
msg += ISTR
ans = None
while ans is None:
get_input = _input if shw else getpass
ans = get_input(msg)
if _AUTO:
echo(ans)
if "?" == ans:
print_help()
ans = None
continue
if "" == ans:
if dft != None:
ans = dft if not fmt else fmt(dft)
break
if "" not in vld:
ans = None
continue
try:
ans = ans if not fmt else fmt(ans)
except:
ans = None
if vld:
for v in vld:
if type(v) is type and cast(ans, v) is not None:
ans = cast(ans, v)
break
elif hasattr(v, "__call__"):
try:
if v(ans):
break
except:
pass
elif ans in vld:
break
else:
ans = None
return ans
|
python
|
def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True):
"""Prompts the user for input and returns the given answer. Optionally
checks if answer is valid.
**Params**:
- msg (str) - Message to prompt the user with.
- fmt (func) - Function used to format user input.
- dft (int|float|str) - Default value if input is left blank.
- vld ([int|float|str|func]) - Valid input entries.
- shw (bool) - If true, show the user's input as typed.
- blk (bool) - If true, accept a blank string as valid input. Note that
supplying a default value will disable accepting blank input.
"""
global _AUTO
def print_help():
lst = [v for v in vld if not callable(v)]
if blk:
lst.remove("")
for v in vld:
if not callable(v):
continue
if int == v:
lst.append("<int>")
elif float == v:
lst.append("<float>")
elif str == v:
lst.append("<str>")
else:
lst.append("(" + v.__name__ + ")")
if lst:
echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst])))
if hlp:
echo("[HELP] Extra notes: " + hlp)
if blk:
echo("[HELP] Input may be blank.")
vld = vld or []
hlp = hlp or ""
if not hasattr(vld, "__iter__"):
vld = [vld]
if not hasattr(fmt, "__call__"):
fmt = lambda x: x # NOTE: Defaults to function that does nothing.
msg = "%s%s" % (QSTR if qstr else "", msg)
dft = fmt(dft) if dft != None else None # Prevents showing [None] default.
if dft != None:
msg += " [%s]" % (dft if type(dft) is str else repr(dft))
vld.append(dft)
blk = False
if vld:
# Sanitize valid inputs.
vld = list(set([fmt(v) if fmt(v) else v for v in vld]))
if blk and "" not in vld:
vld.append("")
# NOTE: The following fixes a Py3 related bug found in `0.8.1`.
try: vld = sorted(vld)
except: pass
msg += ISTR
ans = None
while ans is None:
get_input = _input if shw else getpass
ans = get_input(msg)
if _AUTO:
echo(ans)
if "?" == ans:
print_help()
ans = None
continue
if "" == ans:
if dft != None:
ans = dft if not fmt else fmt(dft)
break
if "" not in vld:
ans = None
continue
try:
ans = ans if not fmt else fmt(ans)
except:
ans = None
if vld:
for v in vld:
if type(v) is type and cast(ans, v) is not None:
ans = cast(ans, v)
break
elif hasattr(v, "__call__"):
try:
if v(ans):
break
except:
pass
elif ans in vld:
break
else:
ans = None
return ans
|
[
"def",
"ask",
"(",
"msg",
"=",
"\"Enter input\"",
",",
"fmt",
"=",
"None",
",",
"dft",
"=",
"None",
",",
"vld",
"=",
"None",
",",
"shw",
"=",
"True",
",",
"blk",
"=",
"False",
",",
"hlp",
"=",
"None",
",",
"qstr",
"=",
"True",
")",
":",
"global",
"_AUTO",
"def",
"print_help",
"(",
")",
":",
"lst",
"=",
"[",
"v",
"for",
"v",
"in",
"vld",
"if",
"not",
"callable",
"(",
"v",
")",
"]",
"if",
"blk",
":",
"lst",
".",
"remove",
"(",
"\"\"",
")",
"for",
"v",
"in",
"vld",
":",
"if",
"not",
"callable",
"(",
"v",
")",
":",
"continue",
"if",
"int",
"==",
"v",
":",
"lst",
".",
"append",
"(",
"\"<int>\"",
")",
"elif",
"float",
"==",
"v",
":",
"lst",
".",
"append",
"(",
"\"<float>\"",
")",
"elif",
"str",
"==",
"v",
":",
"lst",
".",
"append",
"(",
"\"<str>\"",
")",
"else",
":",
"lst",
".",
"append",
"(",
"\"(\"",
"+",
"v",
".",
"__name__",
"+",
"\")\"",
")",
"if",
"lst",
":",
"echo",
"(",
"\"[HELP] Valid input: %s\"",
"%",
"(",
"\" | \"",
".",
"join",
"(",
"[",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"lst",
"]",
")",
")",
")",
"if",
"hlp",
":",
"echo",
"(",
"\"[HELP] Extra notes: \"",
"+",
"hlp",
")",
"if",
"blk",
":",
"echo",
"(",
"\"[HELP] Input may be blank.\"",
")",
"vld",
"=",
"vld",
"or",
"[",
"]",
"hlp",
"=",
"hlp",
"or",
"\"\"",
"if",
"not",
"hasattr",
"(",
"vld",
",",
"\"__iter__\"",
")",
":",
"vld",
"=",
"[",
"vld",
"]",
"if",
"not",
"hasattr",
"(",
"fmt",
",",
"\"__call__\"",
")",
":",
"fmt",
"=",
"lambda",
"x",
":",
"x",
"# NOTE: Defaults to function that does nothing.",
"msg",
"=",
"\"%s%s\"",
"%",
"(",
"QSTR",
"if",
"qstr",
"else",
"\"\"",
",",
"msg",
")",
"dft",
"=",
"fmt",
"(",
"dft",
")",
"if",
"dft",
"!=",
"None",
"else",
"None",
"# Prevents showing [None] default.",
"if",
"dft",
"!=",
"None",
":",
"msg",
"+=",
"\" [%s]\"",
"%",
"(",
"dft",
"if",
"type",
"(",
"dft",
")",
"is",
"str",
"else",
"repr",
"(",
"dft",
")",
")",
"vld",
".",
"append",
"(",
"dft",
")",
"blk",
"=",
"False",
"if",
"vld",
":",
"# Sanitize valid inputs.",
"vld",
"=",
"list",
"(",
"set",
"(",
"[",
"fmt",
"(",
"v",
")",
"if",
"fmt",
"(",
"v",
")",
"else",
"v",
"for",
"v",
"in",
"vld",
"]",
")",
")",
"if",
"blk",
"and",
"\"\"",
"not",
"in",
"vld",
":",
"vld",
".",
"append",
"(",
"\"\"",
")",
"# NOTE: The following fixes a Py3 related bug found in `0.8.1`.",
"try",
":",
"vld",
"=",
"sorted",
"(",
"vld",
")",
"except",
":",
"pass",
"msg",
"+=",
"ISTR",
"ans",
"=",
"None",
"while",
"ans",
"is",
"None",
":",
"get_input",
"=",
"_input",
"if",
"shw",
"else",
"getpass",
"ans",
"=",
"get_input",
"(",
"msg",
")",
"if",
"_AUTO",
":",
"echo",
"(",
"ans",
")",
"if",
"\"?\"",
"==",
"ans",
":",
"print_help",
"(",
")",
"ans",
"=",
"None",
"continue",
"if",
"\"\"",
"==",
"ans",
":",
"if",
"dft",
"!=",
"None",
":",
"ans",
"=",
"dft",
"if",
"not",
"fmt",
"else",
"fmt",
"(",
"dft",
")",
"break",
"if",
"\"\"",
"not",
"in",
"vld",
":",
"ans",
"=",
"None",
"continue",
"try",
":",
"ans",
"=",
"ans",
"if",
"not",
"fmt",
"else",
"fmt",
"(",
"ans",
")",
"except",
":",
"ans",
"=",
"None",
"if",
"vld",
":",
"for",
"v",
"in",
"vld",
":",
"if",
"type",
"(",
"v",
")",
"is",
"type",
"and",
"cast",
"(",
"ans",
",",
"v",
")",
"is",
"not",
"None",
":",
"ans",
"=",
"cast",
"(",
"ans",
",",
"v",
")",
"break",
"elif",
"hasattr",
"(",
"v",
",",
"\"__call__\"",
")",
":",
"try",
":",
"if",
"v",
"(",
"ans",
")",
":",
"break",
"except",
":",
"pass",
"elif",
"ans",
"in",
"vld",
":",
"break",
"else",
":",
"ans",
"=",
"None",
"return",
"ans"
] |
Prompts the user for input and returns the given answer. Optionally
checks if answer is valid.
**Params**:
- msg (str) - Message to prompt the user with.
- fmt (func) - Function used to format user input.
- dft (int|float|str) - Default value if input is left blank.
- vld ([int|float|str|func]) - Valid input entries.
- shw (bool) - If true, show the user's input as typed.
- blk (bool) - If true, accept a blank string as valid input. Note that
supplying a default value will disable accepting blank input.
|
[
"Prompts",
"the",
"user",
"for",
"input",
"and",
"returns",
"the",
"given",
"answer",
".",
"Optionally",
"checks",
"if",
"answer",
"is",
"valid",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L424-L516
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
ask_yesno
|
def ask_yesno(msg="Proceed?", dft=None):
"""Prompts the user for a yes or no answer. Returns True for yes, False
for no."""
yes = ["y", "yes", "Y", "YES"]
no = ["n", "no", "N", "NO"]
if dft != None:
dft = yes[0] if (dft in yes or dft == True) else no[0]
return ask(msg, dft=dft, vld=yes+no) in yes
|
python
|
def ask_yesno(msg="Proceed?", dft=None):
"""Prompts the user for a yes or no answer. Returns True for yes, False
for no."""
yes = ["y", "yes", "Y", "YES"]
no = ["n", "no", "N", "NO"]
if dft != None:
dft = yes[0] if (dft in yes or dft == True) else no[0]
return ask(msg, dft=dft, vld=yes+no) in yes
|
[
"def",
"ask_yesno",
"(",
"msg",
"=",
"\"Proceed?\"",
",",
"dft",
"=",
"None",
")",
":",
"yes",
"=",
"[",
"\"y\"",
",",
"\"yes\"",
",",
"\"Y\"",
",",
"\"YES\"",
"]",
"no",
"=",
"[",
"\"n\"",
",",
"\"no\"",
",",
"\"N\"",
",",
"\"NO\"",
"]",
"if",
"dft",
"!=",
"None",
":",
"dft",
"=",
"yes",
"[",
"0",
"]",
"if",
"(",
"dft",
"in",
"yes",
"or",
"dft",
"==",
"True",
")",
"else",
"no",
"[",
"0",
"]",
"return",
"ask",
"(",
"msg",
",",
"dft",
"=",
"dft",
",",
"vld",
"=",
"yes",
"+",
"no",
")",
"in",
"yes"
] |
Prompts the user for a yes or no answer. Returns True for yes, False
for no.
|
[
"Prompts",
"the",
"user",
"for",
"a",
"yes",
"or",
"no",
"answer",
".",
"Returns",
"True",
"for",
"yes",
"False",
"for",
"no",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L519-L526
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
ask_int
|
def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None):
"""Prompts the user for an integer."""
vld = vld or [int]
return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
|
python
|
def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None):
"""Prompts the user for an integer."""
vld = vld or [int]
return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
|
[
"def",
"ask_int",
"(",
"msg",
"=",
"\"Enter an integer\"",
",",
"dft",
"=",
"None",
",",
"vld",
"=",
"None",
",",
"hlp",
"=",
"None",
")",
":",
"vld",
"=",
"vld",
"or",
"[",
"int",
"]",
"return",
"ask",
"(",
"msg",
",",
"dft",
"=",
"dft",
",",
"vld",
"=",
"vld",
",",
"fmt",
"=",
"partial",
"(",
"cast",
",",
"typ",
"=",
"int",
")",
",",
"hlp",
"=",
"hlp",
")"
] |
Prompts the user for an integer.
|
[
"Prompts",
"the",
"user",
"for",
"an",
"integer",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L529-L532
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
ask_float
|
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None):
"""Prompts the user for a float."""
vld = vld or [float]
return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
|
python
|
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None):
"""Prompts the user for a float."""
vld = vld or [float]
return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
|
[
"def",
"ask_float",
"(",
"msg",
"=",
"\"Enter a float\"",
",",
"dft",
"=",
"None",
",",
"vld",
"=",
"None",
",",
"hlp",
"=",
"None",
")",
":",
"vld",
"=",
"vld",
"or",
"[",
"float",
"]",
"return",
"ask",
"(",
"msg",
",",
"dft",
"=",
"dft",
",",
"vld",
"=",
"vld",
",",
"fmt",
"=",
"partial",
"(",
"cast",
",",
"typ",
"=",
"float",
")",
",",
"hlp",
"=",
"hlp",
")"
] |
Prompts the user for a float.
|
[
"Prompts",
"the",
"user",
"for",
"a",
"float",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L535-L538
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
ask_str
|
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None):
"""Prompts the user for a string."""
vld = vld or [str]
return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
|
python
|
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None):
"""Prompts the user for a string."""
vld = vld or [str]
return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
|
[
"def",
"ask_str",
"(",
"msg",
"=",
"\"Enter a string\"",
",",
"dft",
"=",
"None",
",",
"vld",
"=",
"None",
",",
"shw",
"=",
"True",
",",
"blk",
"=",
"True",
",",
"hlp",
"=",
"None",
")",
":",
"vld",
"=",
"vld",
"or",
"[",
"str",
"]",
"return",
"ask",
"(",
"msg",
",",
"dft",
"=",
"dft",
",",
"vld",
"=",
"vld",
",",
"shw",
"=",
"shw",
",",
"blk",
"=",
"blk",
",",
"hlp",
"=",
"hlp",
")"
] |
Prompts the user for a string.
|
[
"Prompts",
"the",
"user",
"for",
"a",
"string",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L541-L544
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
ask_captcha
|
def ask_captcha(length=4):
"""Prompts the user for a random string."""
captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length))
ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
|
python
|
def ask_captcha(length=4):
"""Prompts the user for a random string."""
captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length))
ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
|
[
"def",
"ask_captcha",
"(",
"length",
"=",
"4",
")",
":",
"captcha",
"=",
"\"\"",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_lowercase",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
")",
"ask_str",
"(",
"'Enter the following letters, \"%s\"'",
"%",
"(",
"captcha",
")",
",",
"vld",
"=",
"[",
"captcha",
",",
"captcha",
".",
"upper",
"(",
")",
"]",
",",
"blk",
"=",
"False",
")"
] |
Prompts the user for a random string.
|
[
"Prompts",
"the",
"user",
"for",
"a",
"random",
"string",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L549-L552
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
clear
|
def clear():
"""Clears the console."""
if sys.platform.startswith("win"):
call("cls", shell=True)
else:
call("clear", shell=True)
|
python
|
def clear():
"""Clears the console."""
if sys.platform.startswith("win"):
call("cls", shell=True)
else:
call("clear", shell=True)
|
[
"def",
"clear",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"call",
"(",
"\"cls\"",
",",
"shell",
"=",
"True",
")",
"else",
":",
"call",
"(",
"\"clear\"",
",",
"shell",
"=",
"True",
")"
] |
Clears the console.
|
[
"Clears",
"the",
"console",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L558-L563
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
status
|
def status(*args, **kwargs):
"""Prints a status message at the start and finish of an associated
function. Can be used as a function decorator or as a function that accepts
another function as the first parameter.
**Params**:
The following parameters are available when used as a decorator:
- msg (str) [args] - Message to print at start of `func`.
The following parameters are available when used as a function:
- msg (str) [args] - Message to print at start of `func`.
- func (func) - Function to call. First `args` if using `status()` as a
function. Automatically provided if using `status()` as a decorator.
- fargs (list) - List of `args` passed to `func`.
- fkrgs (dict) - Dictionary of `kwargs` passed to `func`.
- fin (str) [kwargs] - Message to print when `func` finishes.
**Examples**:
::
@qprompt.status("Something is happening...")
def do_something(a):
time.sleep(a)
do_something()
# [!] Something is happening... DONE.
qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv})
# [!] Doing a thing... DONE.
"""
def decor(func):
@wraps(func)
def wrapper(*args, **krgs):
echo("[!] " + msg, end=" ", flush=True)
result = func(*args, **krgs)
echo(fin, flush=True)
return result
return wrapper
fin = kwargs.pop('fin', "DONE.")
args = list(args)
if len(args) > 1 and callable(args[1]):
msg = args.pop(0)
func = args.pop(0)
try: fargs = args.pop(0)
except: fargs = []
try: fkrgs = args.pop(0)
except: fkrgs = {}
return decor(func)(*fargs, **fkrgs)
msg = args.pop(0)
return decor
|
python
|
def status(*args, **kwargs):
"""Prints a status message at the start and finish of an associated
function. Can be used as a function decorator or as a function that accepts
another function as the first parameter.
**Params**:
The following parameters are available when used as a decorator:
- msg (str) [args] - Message to print at start of `func`.
The following parameters are available when used as a function:
- msg (str) [args] - Message to print at start of `func`.
- func (func) - Function to call. First `args` if using `status()` as a
function. Automatically provided if using `status()` as a decorator.
- fargs (list) - List of `args` passed to `func`.
- fkrgs (dict) - Dictionary of `kwargs` passed to `func`.
- fin (str) [kwargs] - Message to print when `func` finishes.
**Examples**:
::
@qprompt.status("Something is happening...")
def do_something(a):
time.sleep(a)
do_something()
# [!] Something is happening... DONE.
qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv})
# [!] Doing a thing... DONE.
"""
def decor(func):
@wraps(func)
def wrapper(*args, **krgs):
echo("[!] " + msg, end=" ", flush=True)
result = func(*args, **krgs)
echo(fin, flush=True)
return result
return wrapper
fin = kwargs.pop('fin', "DONE.")
args = list(args)
if len(args) > 1 and callable(args[1]):
msg = args.pop(0)
func = args.pop(0)
try: fargs = args.pop(0)
except: fargs = []
try: fkrgs = args.pop(0)
except: fkrgs = {}
return decor(func)(*fargs, **fkrgs)
msg = args.pop(0)
return decor
|
[
"def",
"status",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decor",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"krgs",
")",
":",
"echo",
"(",
"\"[!] \"",
"+",
"msg",
",",
"end",
"=",
"\" \"",
",",
"flush",
"=",
"True",
")",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"krgs",
")",
"echo",
"(",
"fin",
",",
"flush",
"=",
"True",
")",
"return",
"result",
"return",
"wrapper",
"fin",
"=",
"kwargs",
".",
"pop",
"(",
"'fin'",
",",
"\"DONE.\"",
")",
"args",
"=",
"list",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
">",
"1",
"and",
"callable",
"(",
"args",
"[",
"1",
"]",
")",
":",
"msg",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"func",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"try",
":",
"fargs",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"except",
":",
"fargs",
"=",
"[",
"]",
"try",
":",
"fkrgs",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"except",
":",
"fkrgs",
"=",
"{",
"}",
"return",
"decor",
"(",
"func",
")",
"(",
"*",
"fargs",
",",
"*",
"*",
"fkrgs",
")",
"msg",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"return",
"decor"
] |
Prints a status message at the start and finish of an associated
function. Can be used as a function decorator or as a function that accepts
another function as the first parameter.
**Params**:
The following parameters are available when used as a decorator:
- msg (str) [args] - Message to print at start of `func`.
The following parameters are available when used as a function:
- msg (str) [args] - Message to print at start of `func`.
- func (func) - Function to call. First `args` if using `status()` as a
function. Automatically provided if using `status()` as a decorator.
- fargs (list) - List of `args` passed to `func`.
- fkrgs (dict) - Dictionary of `kwargs` passed to `func`.
- fin (str) [kwargs] - Message to print when `func` finishes.
**Examples**:
::
@qprompt.status("Something is happening...")
def do_something(a):
time.sleep(a)
do_something()
# [!] Something is happening... DONE.
qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv})
# [!] Doing a thing... DONE.
|
[
"Prints",
"a",
"status",
"message",
"at",
"the",
"start",
"and",
"finish",
"of",
"an",
"associated",
"function",
".",
"Can",
"be",
"used",
"as",
"a",
"function",
"decorator",
"or",
"as",
"a",
"function",
"that",
"accepts",
"another",
"function",
"as",
"the",
"first",
"parameter",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L565-L616
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
fatal
|
def fatal(msg, exitcode=1, **kwargs):
"""Prints a message then exits the program. Optionally pause before exit
with `pause=True` kwarg."""
# NOTE: Can't use normal arg named `pause` since function has same name.
pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False
echo("[FATAL] " + msg, **kwargs)
if pause_before_exit:
pause()
sys.exit(exitcode)
|
python
|
def fatal(msg, exitcode=1, **kwargs):
"""Prints a message then exits the program. Optionally pause before exit
with `pause=True` kwarg."""
# NOTE: Can't use normal arg named `pause` since function has same name.
pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False
echo("[FATAL] " + msg, **kwargs)
if pause_before_exit:
pause()
sys.exit(exitcode)
|
[
"def",
"fatal",
"(",
"msg",
",",
"exitcode",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"# NOTE: Can't use normal arg named `pause` since function has same name.",
"pause_before_exit",
"=",
"kwargs",
".",
"pop",
"(",
"\"pause\"",
")",
"if",
"\"pause\"",
"in",
"kwargs",
".",
"keys",
"(",
")",
"else",
"False",
"echo",
"(",
"\"[FATAL] \"",
"+",
"msg",
",",
"*",
"*",
"kwargs",
")",
"if",
"pause_before_exit",
":",
"pause",
"(",
")",
"sys",
".",
"exit",
"(",
"exitcode",
")"
] |
Prints a message then exits the program. Optionally pause before exit
with `pause=True` kwarg.
|
[
"Prints",
"a",
"message",
"then",
"exits",
"the",
"program",
".",
"Optionally",
"pause",
"before",
"exit",
"with",
"pause",
"=",
"True",
"kwarg",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L618-L626
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
hrule
|
def hrule(width=None, char=None):
"""Outputs or returns a horizontal line of the given character and width.
Returns printed string."""
width = width or HRWIDTH
char = char or HRCHAR
return echo(getline(char, width))
|
python
|
def hrule(width=None, char=None):
"""Outputs or returns a horizontal line of the given character and width.
Returns printed string."""
width = width or HRWIDTH
char = char or HRCHAR
return echo(getline(char, width))
|
[
"def",
"hrule",
"(",
"width",
"=",
"None",
",",
"char",
"=",
"None",
")",
":",
"width",
"=",
"width",
"or",
"HRWIDTH",
"char",
"=",
"char",
"or",
"HRCHAR",
"return",
"echo",
"(",
"getline",
"(",
"char",
",",
"width",
")",
")"
] |
Outputs or returns a horizontal line of the given character and width.
Returns printed string.
|
[
"Outputs",
"or",
"returns",
"a",
"horizontal",
"line",
"of",
"the",
"given",
"character",
"and",
"width",
".",
"Returns",
"printed",
"string",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L644-L649
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
title
|
def title(msg):
"""Sets the title of the console window."""
if sys.platform.startswith("win"):
ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
|
python
|
def title(msg):
"""Sets the title of the console window."""
if sys.platform.startswith("win"):
ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
|
[
"def",
"title",
"(",
"msg",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"SetConsoleTitleW",
"(",
"tounicode",
"(",
"msg",
")",
")"
] |
Sets the title of the console window.
|
[
"Sets",
"the",
"title",
"of",
"the",
"console",
"window",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L651-L654
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
wrap
|
def wrap(item, args=None, krgs=None, **kwargs):
"""Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
"""
with Wrap(**kwargs):
if callable(item):
args = args or []
krgs = krgs or {}
item(*args, **krgs)
else:
echo(item)
|
python
|
def wrap(item, args=None, krgs=None, **kwargs):
"""Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
"""
with Wrap(**kwargs):
if callable(item):
args = args or []
krgs = krgs or {}
item(*args, **krgs)
else:
echo(item)
|
[
"def",
"wrap",
"(",
"item",
",",
"args",
"=",
"None",
",",
"krgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Wrap",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"item",
")",
":",
"args",
"=",
"args",
"or",
"[",
"]",
"krgs",
"=",
"krgs",
"or",
"{",
"}",
"item",
"(",
"*",
"args",
",",
"*",
"*",
"krgs",
")",
"else",
":",
"echo",
"(",
"item",
")"
] |
Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
|
[
"Wraps",
"the",
"given",
"item",
"content",
"between",
"horizontal",
"lines",
".",
"Item",
"can",
"be",
"a",
"string",
"or",
"a",
"function",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L657-L672
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
_guess_name
|
def _guess_name(desc, taken=None):
"""Attempts to guess the menu entry name from the function name."""
taken = taken or []
name = ""
# Try to find the shortest name based on the given description.
for word in desc.split():
c = word[0].lower()
if not c.isalnum():
continue
name += c
if name not in taken:
break
# If name is still taken, add a number postfix.
count = 2
while name in taken:
name = name + str(count)
count += 1
return name
|
python
|
def _guess_name(desc, taken=None):
"""Attempts to guess the menu entry name from the function name."""
taken = taken or []
name = ""
# Try to find the shortest name based on the given description.
for word in desc.split():
c = word[0].lower()
if not c.isalnum():
continue
name += c
if name not in taken:
break
# If name is still taken, add a number postfix.
count = 2
while name in taken:
name = name + str(count)
count += 1
return name
|
[
"def",
"_guess_name",
"(",
"desc",
",",
"taken",
"=",
"None",
")",
":",
"taken",
"=",
"taken",
"or",
"[",
"]",
"name",
"=",
"\"\"",
"# Try to find the shortest name based on the given description.",
"for",
"word",
"in",
"desc",
".",
"split",
"(",
")",
":",
"c",
"=",
"word",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"not",
"c",
".",
"isalnum",
"(",
")",
":",
"continue",
"name",
"+=",
"c",
"if",
"name",
"not",
"in",
"taken",
":",
"break",
"# If name is still taken, add a number postfix.",
"count",
"=",
"2",
"while",
"name",
"in",
"taken",
":",
"name",
"=",
"name",
"+",
"str",
"(",
"count",
")",
"count",
"+=",
"1",
"return",
"name"
] |
Attempts to guess the menu entry name from the function name.
|
[
"Attempts",
"to",
"guess",
"the",
"menu",
"entry",
"name",
"from",
"the",
"function",
"name",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L674-L691
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
Menu.add
|
def add(self, name, desc, func=None, args=None, krgs=None):
"""Add a menu entry."""
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
|
python
|
def add(self, name, desc, func=None, args=None, krgs=None):
"""Add a menu entry."""
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
|
[
"def",
"add",
"(",
"self",
",",
"name",
",",
"desc",
",",
"func",
"=",
"None",
",",
"args",
"=",
"None",
",",
"krgs",
"=",
"None",
")",
":",
"self",
".",
"entries",
".",
"append",
"(",
"MenuEntry",
"(",
"name",
",",
"desc",
",",
"func",
",",
"args",
"or",
"[",
"]",
",",
"krgs",
"or",
"{",
"}",
")",
")"
] |
Add a menu entry.
|
[
"Add",
"a",
"menu",
"entry",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L141-L143
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
Menu.enum
|
def enum(self, desc, func=None, args=None, krgs=None):
"""Add a menu entry whose name will be an auto indexed number."""
name = str(len(self.entries)+1)
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
|
python
|
def enum(self, desc, func=None, args=None, krgs=None):
"""Add a menu entry whose name will be an auto indexed number."""
name = str(len(self.entries)+1)
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
|
[
"def",
"enum",
"(",
"self",
",",
"desc",
",",
"func",
"=",
"None",
",",
"args",
"=",
"None",
",",
"krgs",
"=",
"None",
")",
":",
"name",
"=",
"str",
"(",
"len",
"(",
"self",
".",
"entries",
")",
"+",
"1",
")",
"self",
".",
"entries",
".",
"append",
"(",
"MenuEntry",
"(",
"name",
",",
"desc",
",",
"func",
",",
"args",
"or",
"[",
"]",
",",
"krgs",
"or",
"{",
"}",
")",
")"
] |
Add a menu entry whose name will be an auto indexed number.
|
[
"Add",
"a",
"menu",
"entry",
"whose",
"name",
"will",
"be",
"an",
"auto",
"indexed",
"number",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L144-L147
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
Menu.show
|
def show(self, **kwargs):
"""Shows the menu. Any `kwargs` supplied will be passed to
`show_menu()`."""
show_kwargs = copy.deepcopy(self._show_kwargs)
show_kwargs.update(kwargs)
return show_menu(self.entries, **show_kwargs)
|
python
|
def show(self, **kwargs):
"""Shows the menu. Any `kwargs` supplied will be passed to
`show_menu()`."""
show_kwargs = copy.deepcopy(self._show_kwargs)
show_kwargs.update(kwargs)
return show_menu(self.entries, **show_kwargs)
|
[
"def",
"show",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"show_kwargs",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_show_kwargs",
")",
"show_kwargs",
".",
"update",
"(",
"kwargs",
")",
"return",
"show_menu",
"(",
"self",
".",
"entries",
",",
"*",
"*",
"show_kwargs",
")"
] |
Shows the menu. Any `kwargs` supplied will be passed to
`show_menu()`.
|
[
"Shows",
"the",
"menu",
".",
"Any",
"kwargs",
"supplied",
"will",
"be",
"passed",
"to",
"show_menu",
"()",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L148-L153
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
Menu.run
|
def run(self, name):
"""Runs the function associated with the given entry `name`."""
for entry in self.entries:
if entry.name == name:
run_func(entry)
break
|
python
|
def run(self, name):
"""Runs the function associated with the given entry `name`."""
for entry in self.entries:
if entry.name == name:
run_func(entry)
break
|
[
"def",
"run",
"(",
"self",
",",
"name",
")",
":",
"for",
"entry",
"in",
"self",
".",
"entries",
":",
"if",
"entry",
".",
"name",
"==",
"name",
":",
"run_func",
"(",
"entry",
")",
"break"
] |
Runs the function associated with the given entry `name`.
|
[
"Runs",
"the",
"function",
"associated",
"with",
"the",
"given",
"entry",
"name",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L154-L159
|
train
|
jeffrimko/Qprompt
|
lib/qprompt.py
|
Menu.main
|
def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs):
"""Runs the standard menu main logic. Any `kwargs` supplied will be
pass to `Menu.show()`. If `argv` is provided to the script, it will be
used as the `auto` parameter.
**Params**:
- auto ([str]) - If provided, the list of strings with be used as
input for the menu prompts.
- loop (bool) - If true, the menu will loop until quit.
- quit ((str,str)) - If provided, adds a quit option to the menu.
"""
def _main():
global _AUTO
if quit:
if self.entries[-1][:2] != quit:
self.add(*quit, func=lambda: quit[0])
if stdin_auto.auto:
_AUTO = True
result = None
if loop:
note = "Menu loops until quit."
try:
while True:
mresult = self.show(note=note, **kwargs)
if mresult in quit:
break
result = mresult
except EOFError:
pass
return result
else:
note = "Menu does not loop, single entry."
result = self.show(note=note, **kwargs)
return result
global _AUTO
if _AUTO:
return _main()
else:
with stdin_auto:
return _main()
|
python
|
def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs):
"""Runs the standard menu main logic. Any `kwargs` supplied will be
pass to `Menu.show()`. If `argv` is provided to the script, it will be
used as the `auto` parameter.
**Params**:
- auto ([str]) - If provided, the list of strings with be used as
input for the menu prompts.
- loop (bool) - If true, the menu will loop until quit.
- quit ((str,str)) - If provided, adds a quit option to the menu.
"""
def _main():
global _AUTO
if quit:
if self.entries[-1][:2] != quit:
self.add(*quit, func=lambda: quit[0])
if stdin_auto.auto:
_AUTO = True
result = None
if loop:
note = "Menu loops until quit."
try:
while True:
mresult = self.show(note=note, **kwargs)
if mresult in quit:
break
result = mresult
except EOFError:
pass
return result
else:
note = "Menu does not loop, single entry."
result = self.show(note=note, **kwargs)
return result
global _AUTO
if _AUTO:
return _main()
else:
with stdin_auto:
return _main()
|
[
"def",
"main",
"(",
"self",
",",
"auto",
"=",
"None",
",",
"loop",
"=",
"False",
",",
"quit",
"=",
"(",
"\"q\"",
",",
"\"Quit\"",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_main",
"(",
")",
":",
"global",
"_AUTO",
"if",
"quit",
":",
"if",
"self",
".",
"entries",
"[",
"-",
"1",
"]",
"[",
":",
"2",
"]",
"!=",
"quit",
":",
"self",
".",
"add",
"(",
"*",
"quit",
",",
"func",
"=",
"lambda",
":",
"quit",
"[",
"0",
"]",
")",
"if",
"stdin_auto",
".",
"auto",
":",
"_AUTO",
"=",
"True",
"result",
"=",
"None",
"if",
"loop",
":",
"note",
"=",
"\"Menu loops until quit.\"",
"try",
":",
"while",
"True",
":",
"mresult",
"=",
"self",
".",
"show",
"(",
"note",
"=",
"note",
",",
"*",
"*",
"kwargs",
")",
"if",
"mresult",
"in",
"quit",
":",
"break",
"result",
"=",
"mresult",
"except",
"EOFError",
":",
"pass",
"return",
"result",
"else",
":",
"note",
"=",
"\"Menu does not loop, single entry.\"",
"result",
"=",
"self",
".",
"show",
"(",
"note",
"=",
"note",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"global",
"_AUTO",
"if",
"_AUTO",
":",
"return",
"_main",
"(",
")",
"else",
":",
"with",
"stdin_auto",
":",
"return",
"_main",
"(",
")"
] |
Runs the standard menu main logic. Any `kwargs` supplied will be
pass to `Menu.show()`. If `argv` is provided to the script, it will be
used as the `auto` parameter.
**Params**:
- auto ([str]) - If provided, the list of strings with be used as
input for the menu prompts.
- loop (bool) - If true, the menu will loop until quit.
- quit ((str,str)) - If provided, adds a quit option to the menu.
|
[
"Runs",
"the",
"standard",
"menu",
"main",
"logic",
".",
"Any",
"kwargs",
"supplied",
"will",
"be",
"pass",
"to",
"Menu",
".",
"show",
"()",
".",
"If",
"argv",
"is",
"provided",
"to",
"the",
"script",
"it",
"will",
"be",
"used",
"as",
"the",
"auto",
"parameter",
"."
] |
1887c53656dfecac49e0650e0f912328801cbb83
|
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L160-L199
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/initialization.py
|
partition_scripts
|
def partition_scripts(scripts, start_type1, start_type2):
"""Return two lists of scripts out of the original `scripts` list.
Scripts that begin with a `start_type1` or `start_type2` blocks
are returned first. All other scripts are returned second.
"""
match, other = [], []
for script in scripts:
if (HairballPlugin.script_start_type(script) == start_type1 or
HairballPlugin.script_start_type(script) == start_type2):
match.append(script)
else:
other.append(script)
return match, other
|
python
|
def partition_scripts(scripts, start_type1, start_type2):
"""Return two lists of scripts out of the original `scripts` list.
Scripts that begin with a `start_type1` or `start_type2` blocks
are returned first. All other scripts are returned second.
"""
match, other = [], []
for script in scripts:
if (HairballPlugin.script_start_type(script) == start_type1 or
HairballPlugin.script_start_type(script) == start_type2):
match.append(script)
else:
other.append(script)
return match, other
|
[
"def",
"partition_scripts",
"(",
"scripts",
",",
"start_type1",
",",
"start_type2",
")",
":",
"match",
",",
"other",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"script",
"in",
"scripts",
":",
"if",
"(",
"HairballPlugin",
".",
"script_start_type",
"(",
"script",
")",
"==",
"start_type1",
"or",
"HairballPlugin",
".",
"script_start_type",
"(",
"script",
")",
"==",
"start_type2",
")",
":",
"match",
".",
"append",
"(",
"script",
")",
"else",
":",
"other",
".",
"append",
"(",
"script",
")",
"return",
"match",
",",
"other"
] |
Return two lists of scripts out of the original `scripts` list.
Scripts that begin with a `start_type1` or `start_type2` blocks
are returned first. All other scripts are returned second.
|
[
"Return",
"two",
"lists",
"of",
"scripts",
"out",
"of",
"the",
"original",
"scripts",
"list",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L7-L21
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/initialization.py
|
AttributeInitialization.attribute_result
|
def attribute_result(cls, sprites):
"""Return mapping of attributes to if they were initialized or not."""
retval = dict((x, True) for x in cls.ATTRIBUTES)
for properties in sprites.values():
for attribute, state in properties.items():
retval[attribute] &= state != cls.STATE_MODIFIED
return retval
|
python
|
def attribute_result(cls, sprites):
"""Return mapping of attributes to if they were initialized or not."""
retval = dict((x, True) for x in cls.ATTRIBUTES)
for properties in sprites.values():
for attribute, state in properties.items():
retval[attribute] &= state != cls.STATE_MODIFIED
return retval
|
[
"def",
"attribute_result",
"(",
"cls",
",",
"sprites",
")",
":",
"retval",
"=",
"dict",
"(",
"(",
"x",
",",
"True",
")",
"for",
"x",
"in",
"cls",
".",
"ATTRIBUTES",
")",
"for",
"properties",
"in",
"sprites",
".",
"values",
"(",
")",
":",
"for",
"attribute",
",",
"state",
"in",
"properties",
".",
"items",
"(",
")",
":",
"retval",
"[",
"attribute",
"]",
"&=",
"state",
"!=",
"cls",
".",
"STATE_MODIFIED",
"return",
"retval"
] |
Return mapping of attributes to if they were initialized or not.
|
[
"Return",
"mapping",
"of",
"attributes",
"to",
"if",
"they",
"were",
"initialized",
"or",
"not",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L36-L42
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/initialization.py
|
AttributeInitialization.attribute_state
|
def attribute_state(cls, scripts, attribute):
"""Return the state of the scripts for the given attribute.
If there is more than one 'when green flag clicked' script and they
both modify the attribute, then the attribute is considered to not be
initialized.
"""
green_flag, other = partition_scripts(scripts, cls.HAT_GREEN_FLAG, cls.HAT_CLONE)
block_set = cls.BLOCKMAPPING[attribute]
state = cls.STATE_NOT_MODIFIED
# TODO: Any regular broadcast blocks encountered in the initialization
# zone should be added to this loop for conflict checking.
for script in green_flag:
in_zone = True
for name, level, _ in cls.iter_blocks(script.blocks):
if name == 'broadcast %s and wait':
# TODO: Follow the broadcast and wait scripts that occur in
# the initialization zone
in_zone = False
if (name, 'absolute') in block_set:
if in_zone and level == 0: # Success!
if state == cls.STATE_NOT_MODIFIED:
state = cls.STATE_INITIALIZED
else: # Multiple when green flag clicked conflict
state = cls.STATE_MODIFIED
elif in_zone:
continue # Conservative ignore for nested absolutes
else:
state = cls.STATE_MODIFIED
break # The state of the script has been determined
elif (name, 'relative') in block_set:
state = cls.STATE_MODIFIED
break
if state != cls.STATE_NOT_MODIFIED:
return state
# Check the other scripts to see if the attribute was ever modified
for script in other:
for name, _, _ in cls.iter_blocks(script.blocks):
if name in [x[0] for x in block_set]:
return cls.STATE_MODIFIED
return cls.STATE_NOT_MODIFIED
|
python
|
def attribute_state(cls, scripts, attribute):
"""Return the state of the scripts for the given attribute.
If there is more than one 'when green flag clicked' script and they
both modify the attribute, then the attribute is considered to not be
initialized.
"""
green_flag, other = partition_scripts(scripts, cls.HAT_GREEN_FLAG, cls.HAT_CLONE)
block_set = cls.BLOCKMAPPING[attribute]
state = cls.STATE_NOT_MODIFIED
# TODO: Any regular broadcast blocks encountered in the initialization
# zone should be added to this loop for conflict checking.
for script in green_flag:
in_zone = True
for name, level, _ in cls.iter_blocks(script.blocks):
if name == 'broadcast %s and wait':
# TODO: Follow the broadcast and wait scripts that occur in
# the initialization zone
in_zone = False
if (name, 'absolute') in block_set:
if in_zone and level == 0: # Success!
if state == cls.STATE_NOT_MODIFIED:
state = cls.STATE_INITIALIZED
else: # Multiple when green flag clicked conflict
state = cls.STATE_MODIFIED
elif in_zone:
continue # Conservative ignore for nested absolutes
else:
state = cls.STATE_MODIFIED
break # The state of the script has been determined
elif (name, 'relative') in block_set:
state = cls.STATE_MODIFIED
break
if state != cls.STATE_NOT_MODIFIED:
return state
# Check the other scripts to see if the attribute was ever modified
for script in other:
for name, _, _ in cls.iter_blocks(script.blocks):
if name in [x[0] for x in block_set]:
return cls.STATE_MODIFIED
return cls.STATE_NOT_MODIFIED
|
[
"def",
"attribute_state",
"(",
"cls",
",",
"scripts",
",",
"attribute",
")",
":",
"green_flag",
",",
"other",
"=",
"partition_scripts",
"(",
"scripts",
",",
"cls",
".",
"HAT_GREEN_FLAG",
",",
"cls",
".",
"HAT_CLONE",
")",
"block_set",
"=",
"cls",
".",
"BLOCKMAPPING",
"[",
"attribute",
"]",
"state",
"=",
"cls",
".",
"STATE_NOT_MODIFIED",
"# TODO: Any regular broadcast blocks encountered in the initialization",
"# zone should be added to this loop for conflict checking.",
"for",
"script",
"in",
"green_flag",
":",
"in_zone",
"=",
"True",
"for",
"name",
",",
"level",
",",
"_",
"in",
"cls",
".",
"iter_blocks",
"(",
"script",
".",
"blocks",
")",
":",
"if",
"name",
"==",
"'broadcast %s and wait'",
":",
"# TODO: Follow the broadcast and wait scripts that occur in",
"# the initialization zone",
"in_zone",
"=",
"False",
"if",
"(",
"name",
",",
"'absolute'",
")",
"in",
"block_set",
":",
"if",
"in_zone",
"and",
"level",
"==",
"0",
":",
"# Success!",
"if",
"state",
"==",
"cls",
".",
"STATE_NOT_MODIFIED",
":",
"state",
"=",
"cls",
".",
"STATE_INITIALIZED",
"else",
":",
"# Multiple when green flag clicked conflict",
"state",
"=",
"cls",
".",
"STATE_MODIFIED",
"elif",
"in_zone",
":",
"continue",
"# Conservative ignore for nested absolutes",
"else",
":",
"state",
"=",
"cls",
".",
"STATE_MODIFIED",
"break",
"# The state of the script has been determined",
"elif",
"(",
"name",
",",
"'relative'",
")",
"in",
"block_set",
":",
"state",
"=",
"cls",
".",
"STATE_MODIFIED",
"break",
"if",
"state",
"!=",
"cls",
".",
"STATE_NOT_MODIFIED",
":",
"return",
"state",
"# Check the other scripts to see if the attribute was ever modified",
"for",
"script",
"in",
"other",
":",
"for",
"name",
",",
"_",
",",
"_",
"in",
"cls",
".",
"iter_blocks",
"(",
"script",
".",
"blocks",
")",
":",
"if",
"name",
"in",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"block_set",
"]",
":",
"return",
"cls",
".",
"STATE_MODIFIED",
"return",
"cls",
".",
"STATE_NOT_MODIFIED"
] |
Return the state of the scripts for the given attribute.
If there is more than one 'when green flag clicked' script and they
both modify the attribute, then the attribute is considered to not be
initialized.
|
[
"Return",
"the",
"state",
"of",
"the",
"scripts",
"for",
"the",
"given",
"attribute",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L45-L86
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/initialization.py
|
AttributeInitialization.output_results
|
def output_results(cls, sprites):
"""Output whether or not each attribute was correctly initialized.
Attributes that were not modified at all are considered to be properly
initialized.
"""
print(' '.join(cls.ATTRIBUTES))
format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) for x in
cls.ATTRIBUTES]
print(' '.join(format_strs).format(**cls.attribute_result(sprites)))
|
python
|
def output_results(cls, sprites):
"""Output whether or not each attribute was correctly initialized.
Attributes that were not modified at all are considered to be properly
initialized.
"""
print(' '.join(cls.ATTRIBUTES))
format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) for x in
cls.ATTRIBUTES]
print(' '.join(format_strs).format(**cls.attribute_result(sprites)))
|
[
"def",
"output_results",
"(",
"cls",
",",
"sprites",
")",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"cls",
".",
"ATTRIBUTES",
")",
")",
"format_strs",
"=",
"[",
"'{{{}!s:^{}}}'",
".",
"format",
"(",
"x",
",",
"len",
"(",
"x",
")",
")",
"for",
"x",
"in",
"cls",
".",
"ATTRIBUTES",
"]",
"print",
"(",
"' '",
".",
"join",
"(",
"format_strs",
")",
".",
"format",
"(",
"*",
"*",
"cls",
".",
"attribute_result",
"(",
"sprites",
")",
")",
")"
] |
Output whether or not each attribute was correctly initialized.
Attributes that were not modified at all are considered to be properly
initialized.
|
[
"Output",
"whether",
"or",
"not",
"each",
"attribute",
"was",
"correctly",
"initialized",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L89-L99
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/initialization.py
|
AttributeInitialization.sprite_changes
|
def sprite_changes(cls, sprite):
"""Return a mapping of attributes to their initilization state."""
retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in
(x for x in cls.ATTRIBUTES if x != 'background'))
return retval
|
python
|
def sprite_changes(cls, sprite):
"""Return a mapping of attributes to their initilization state."""
retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in
(x for x in cls.ATTRIBUTES if x != 'background'))
return retval
|
[
"def",
"sprite_changes",
"(",
"cls",
",",
"sprite",
")",
":",
"retval",
"=",
"dict",
"(",
"(",
"x",
",",
"cls",
".",
"attribute_state",
"(",
"sprite",
".",
"scripts",
",",
"x",
")",
")",
"for",
"x",
"in",
"(",
"x",
"for",
"x",
"in",
"cls",
".",
"ATTRIBUTES",
"if",
"x",
"!=",
"'background'",
")",
")",
"return",
"retval"
] |
Return a mapping of attributes to their initilization state.
|
[
"Return",
"a",
"mapping",
"of",
"attributes",
"to",
"their",
"initilization",
"state",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L102-L106
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.