repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
tehmaze-labs/wright
wright/stage/env.py
Generate._lib
def _lib(self, name, only_if_have=False): """Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`. """ ...
python
def _lib(self, name, only_if_have=False): """Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`. """ ...
[ "def", "_lib", "(", "self", ",", "name", ",", "only_if_have", "=", "False", ")", ":", "emit", "=", "True", "if", "only_if_have", ":", "emit", "=", "self", ".", "env", ".", "get", "(", "'HAVE_LIB'", "+", "self", ".", "env_key", "(", "name", ")", ")"...
Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`.
[ "Specify", "a", "linker", "library", "." ]
train
https://github.com/tehmaze-labs/wright/blob/79b2d816f541e69d5fb7f36a3c39fa0d432157a6/wright/stage/env.py#L48-L63
tehmaze-labs/wright
wright/stage/env.py
Generate._with
def _with(self, option=None): """Check if a build option is enabled. If called without argument, it returns all WITH_* items. Example: {% if with('foo') %}...{% endif %} """ if option is None: return ( (k, v) for k, v in self.env.items()...
python
def _with(self, option=None): """Check if a build option is enabled. If called without argument, it returns all WITH_* items. Example: {% if with('foo') %}...{% endif %} """ if option is None: return ( (k, v) for k, v in self.env.items()...
[ "def", "_with", "(", "self", ",", "option", "=", "None", ")", ":", "if", "option", "is", "None", ":", "return", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "env", ".", "items", "(", ")", "if", "k", ".", "startswith"...
Check if a build option is enabled. If called without argument, it returns all WITH_* items. Example: {% if with('foo') %}...{% endif %}
[ "Check", "if", "a", "build", "option", "is", "enabled", "." ]
train
https://github.com/tehmaze-labs/wright/blob/79b2d816f541e69d5fb7f36a3c39fa0d432157a6/wright/stage/env.py#L65-L79
alexandershov/mess
mess/iters.py
pairs
def pairs(iterable): """ :return: iterator yielding overlapping pairs from iterable :Example: >>> list(pairs([1, 2, 3, 4]) [(1, 2), (2, 3), (3, 4)] """ a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
python
def pairs(iterable): """ :return: iterator yielding overlapping pairs from iterable :Example: >>> list(pairs([1, 2, 3, 4]) [(1, 2), (2, 3), (3, 4)] """ a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
[ "def", "pairs", "(", "iterable", ")", ":", "a", ",", "b", "=", "itertools", ".", "tee", "(", "iterable", ")", "next", "(", "b", ",", "None", ")", "return", "zip", "(", "a", ",", "b", ")" ]
:return: iterator yielding overlapping pairs from iterable :Example: >>> list(pairs([1, 2, 3, 4]) [(1, 2), (2, 3), (3, 4)]
[ ":", "return", ":", "iterator", "yielding", "overlapping", "pairs", "from", "iterable" ]
train
https://github.com/alexandershov/mess/blob/7b0d956c1fd39cca2e4adcd5dc35952ec3ed3fd5/mess/iters.py#L9-L20
klmitch/bark
bark/conversions.py
Modifier.set_codes
def set_codes(self, codes, reject=False): """ Set the accepted or rejected codes codes list. :param codes: A list of the response codes. :param reject: If True, the listed codes will be rejected, and the conversion will format as "-"; if False, ...
python
def set_codes(self, codes, reject=False): """ Set the accepted or rejected codes codes list. :param codes: A list of the response codes. :param reject: If True, the listed codes will be rejected, and the conversion will format as "-"; if False, ...
[ "def", "set_codes", "(", "self", ",", "codes", ",", "reject", "=", "False", ")", ":", "self", ".", "codes", "=", "set", "(", "codes", ")", "self", ".", "reject", "=", "reject" ]
Set the accepted or rejected codes codes list. :param codes: A list of the response codes. :param reject: If True, the listed codes will be rejected, and the conversion will format as "-"; if False, only the listed codes will be accepted, and the ...
[ "Set", "the", "accepted", "or", "rejected", "codes", "codes", "list", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L60-L73
klmitch/bark
bark/conversions.py
Modifier.accept
def accept(self, code): """ Determine whether to accept the given code. :param code: The response code. :returns: True if the code should be accepted, False otherwise. """ if code in self.codes: return not self.reject return self.r...
python
def accept(self, code): """ Determine whether to accept the given code. :param code: The response code. :returns: True if the code should be accepted, False otherwise. """ if code in self.codes: return not self.reject return self.r...
[ "def", "accept", "(", "self", ",", "code", ")", ":", "if", "code", "in", "self", ".", "codes", ":", "return", "not", "self", ".", "reject", "return", "self", ".", "reject" ]
Determine whether to accept the given code. :param code: The response code. :returns: True if the code should be accepted, False otherwise.
[ "Determine", "whether", "to", "accept", "the", "given", "code", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L84-L96
klmitch/bark
bark/conversions.py
Conversion._needescape
def _needescape(c): """ Return True if character needs escaping, else False. """ return not ascii.isprint(c) or c == '"' or c == '\\' or ascii.isctrl(c)
python
def _needescape(c): """ Return True if character needs escaping, else False. """ return not ascii.isprint(c) or c == '"' or c == '\\' or ascii.isctrl(c)
[ "def", "_needescape", "(", "c", ")", ":", "return", "not", "ascii", ".", "isprint", "(", "c", ")", "or", "c", "==", "'\"'", "or", "c", "==", "'\\\\'", "or", "ascii", ".", "isctrl", "(", "c", ")" ]
Return True if character needs escaping, else False.
[ "Return", "True", "if", "character", "needs", "escaping", "else", "False", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L118-L123
klmitch/bark
bark/conversions.py
Conversion.escape
def escape(cls, string): """ Utility method to produce an escaped version of a given string. :param string: The string to escape. :returns: The escaped version of the string. """ return ''.join([cls._escapes[c] if cls._needescape(c) else c ...
python
def escape(cls, string): """ Utility method to produce an escaped version of a given string. :param string: The string to escape. :returns: The escaped version of the string. """ return ''.join([cls._escapes[c] if cls._needescape(c) else c ...
[ "def", "escape", "(", "cls", ",", "string", ")", ":", "return", "''", ".", "join", "(", "[", "cls", ".", "_escapes", "[", "c", "]", "if", "cls", ".", "_needescape", "(", "c", ")", "else", "c", "for", "c", "in", "string", ".", "encode", "(", "'u...
Utility method to produce an escaped version of a given string. :param string: The string to escape. :returns: The escaped version of the string.
[ "Utility", "method", "to", "produce", "an", "escaped", "version", "of", "a", "given", "string", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L126-L137
klmitch/bark
bark/conversions.py
AddressConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "client_addr", "=", "request", ".", "environ", ".", "get", "(", "'REMOTE_ADDR'", ",", "'-'", ")", "if", "(", "self", ".", "modifier", ".", "param", "!=", "'c'", "a...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L238-L258
klmitch/bark
bark/conversions.py
FirstLineConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "# Chop up the URL", "uri", "=", "urlparse", ".", "urlparse", "(", "request", ".", "url", ")", "# If there's a password, recompute the URI without it", "if", "uri", ".", "pass...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L319-L349
klmitch/bark
bark/conversions.py
NoteConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "# Notes are in bark.notes dictionary", "return", "self", ".", "escape", "(", "request", ".", "environ", ".", "get", "(", "'bark.notes'", ",", "{", "}", ")", ".", "get",...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L411-L428
klmitch/bark
bark/conversions.py
ProcessIDConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "if", "self", ".", "modifier", ".", "param", "is", "None", "or", "self", ".", "modifier", ".", "param", "==", "'pid'", ":", "return", "str", "(", "os", ".", "get...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L432-L453
klmitch/bark
bark/conversions.py
QueryStringConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "qstr", "=", "request", ".", "query_string", "return", "self", ".", "escape", "(", "'?%s'", "%", "qstr", ")", "if", "qstr", "else", "''" ]
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L476-L493
klmitch/bark
bark/conversions.py
RemoteUserConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "# None specified", "if", "request", ".", "remote_user", "is", "None", ":", "return", "\"-\"", "elif", "not", "request", ".", "remote_user", ":", "# Empty string...", "ret...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L497-L518
klmitch/bark
bark/conversions.py
ResponseSizeConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "size", "=", "response", ".", "content_length", "if", "not", "size", ":", "size", "=", "\"-\"", "if", "self", ".", "conv_chr", "==", "'b'", "else", "0", "return", ...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L579-L598
klmitch/bark
bark/conversions.py
PortConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "if", "self", ".", "modifier", ".", "param", "in", "(", "None", ",", "'canonical'", ",", "'local'", ")", ":", "return", "str", "(", "request", ".", "environ", "[",...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L621-L641
klmitch/bark
bark/conversions.py
ServeTimeConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "delta", "=", "time", ".", "time", "(", ")", "-", "data", "[", "'start'", "]", "if", "self", ".", "conv_chr", "==", "'D'", ":", "delta", "*=", "1000000", "return...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L658-L678
klmitch/bark
bark/conversions.py
TimeConversion.convert
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
python
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "# Determine which time to use", "fmtstr", "=", "self", ".", "modifier", ".", "param", "if", "fmtstr", "is", "None", ":", "log_time", "=", "data", "[", "'start'", "]", ...
Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary returned by the prepare() ...
[ "Performs", "the", "desired", "Conversion", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L714-L773
jmgilman/Neolib
neolib/http/HTTPForm.py
HTTPForm.submit
def submit(self): """ Posts the form's data and returns the resulting Page Returns Page - The resulting page """ u = urlparse(self.url) if not self.action: self.action = self.url elif self.action == u.path: self.acti...
python
def submit(self): """ Posts the form's data and returns the resulting Page Returns Page - The resulting page """ u = urlparse(self.url) if not self.action: self.action = self.url elif self.action == u.path: self.acti...
[ "def", "submit", "(", "self", ")", ":", "u", "=", "urlparse", "(", "self", ".", "url", ")", "if", "not", "self", ".", "action", ":", "self", ".", "action", "=", "self", ".", "url", "elif", "self", ".", "action", "==", "u", ".", "path", ":", "se...
Posts the form's data and returns the resulting Page Returns Page - The resulting page
[ "Posts", "the", "form", "s", "data", "and", "returns", "the", "resulting", "Page", "Returns", "Page", "-", "The", "resulting", "page" ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/http/HTTPForm.py#L73-L94
lehins/python-wepay
wepay/calls/batch.py
Batch.__create
def __create(self, client_id, client_secret, calls, **kwargs): """Call documentation: `/batch/create <https://www.wepay.com/developer/reference/batch#create>`_, plus extra keyword parameter: :keyword str access_token: will be used instead of instance's ``access_token...
python
def __create(self, client_id, client_secret, calls, **kwargs): """Call documentation: `/batch/create <https://www.wepay.com/developer/reference/batch#create>`_, plus extra keyword parameter: :keyword str access_token: will be used instead of instance's ``access_token...
[ "def", "__create", "(", "self", ",", "client_id", ",", "client_secret", ",", "calls", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "client_secret", ",", "'calls'", ":", "calls", "}", ...
Call documentation: `/batch/create <https://www.wepay.com/developer/reference/batch#create>`_, plus extra keyword parameter: :keyword str access_token: will be used instead of instance's ``access_token``
[ "Call", "documentation", ":", "/", "batch", "/", "create", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "batch#create", ">", "_", "plus", "extra", "keyword", "parameter", ":", ":", "keyword", "str", "acce...
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/batch.py#L8-L22
amaas-fintech/amaas-utils-python
amaasutils/hash.py
compute_hash
def compute_hash(attributes, ignored_attributes=None): """ Computes a hash code for the given dictionary that is safe for persistence round trips """ ignored_attributes = list(ignored_attributes) if ignored_attributes else [] tuple_attributes = _convert(attributes.copy(), ignored_attributes) ha...
python
def compute_hash(attributes, ignored_attributes=None): """ Computes a hash code for the given dictionary that is safe for persistence round trips """ ignored_attributes = list(ignored_attributes) if ignored_attributes else [] tuple_attributes = _convert(attributes.copy(), ignored_attributes) ha...
[ "def", "compute_hash", "(", "attributes", ",", "ignored_attributes", "=", "None", ")", ":", "ignored_attributes", "=", "list", "(", "ignored_attributes", ")", "if", "ignored_attributes", "else", "[", "]", "tuple_attributes", "=", "_convert", "(", "attributes", "."...
Computes a hash code for the given dictionary that is safe for persistence round trips
[ "Computes", "a", "hash", "code", "for", "the", "given", "dictionary", "that", "is", "safe", "for", "persistence", "round", "trips" ]
train
https://github.com/amaas-fintech/amaas-utils-python/blob/5aa64ca65ce0c77b513482d943345d94c9ae58e8/amaasutils/hash.py#L3-L10
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py
SimpleRowColumn
def SimpleRowColumn(field, *args, **kwargs): """ Shortcut for simple row with only a full column """ if isinstance(field, basestring): field = Field(field, *args, **kwargs) return Row( Column(field), )
python
def SimpleRowColumn(field, *args, **kwargs): """ Shortcut for simple row with only a full column """ if isinstance(field, basestring): field = Field(field, *args, **kwargs) return Row( Column(field), )
[ "def", "SimpleRowColumn", "(", "field", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "field", ",", "basestring", ")", ":", "field", "=", "Field", "(", "field", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return...
Shortcut for simple row with only a full column
[ "Shortcut", "for", "simple", "row", "with", "only", "a", "full", "column" ]
train
https://github.com/emencia/emencia_paste_djangocms_3/blob/29eabbcb17e21996a6e1d99592fc719dc8833b59/emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py#L21-L29
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py
ContactFormBase.save
def save(self, commit=True): """Save and send""" contact = super(ContactFormBase, self).save() context = {'contact': contact} context.update(get_site_metas()) subject = ''.join(render_to_string(self.mail_subject_template, context).splitlines()) content = render_to_string...
python
def save(self, commit=True): """Save and send""" contact = super(ContactFormBase, self).save() context = {'contact': contact} context.update(get_site_metas()) subject = ''.join(render_to_string(self.mail_subject_template, context).splitlines()) content = render_to_string...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "contact", "=", "super", "(", "ContactFormBase", ",", "self", ")", ".", "save", "(", ")", "context", "=", "{", "'contact'", ":", "contact", "}", "context", ".", "update", "(", "get_sit...
Save and send
[ "Save", "and", "send" ]
train
https://github.com/emencia/emencia_paste_djangocms_3/blob/29eabbcb17e21996a6e1d99592fc719dc8833b59/emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py#L47-L61
klmitch/bark
bark/middleware.py
bark_filter
def bark_filter(global_conf, **local_conf): """ Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMiddleware. :param global_conf: The global configuration, from the [DEFAULT] section of the PasteDeploy configuration fil...
python
def bark_filter(global_conf, **local_conf): """ Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMiddleware. :param global_conf: The global configuration, from the [DEFAULT] section of the PasteDeploy configuration fil...
[ "def", "bark_filter", "(", "global_conf", ",", "*", "*", "local_conf", ")", ":", "# First, parse the configuration", "conf_file", "=", "None", "sections", "=", "{", "}", "for", "key", ",", "value", "in", "local_conf", ".", "items", "(", ")", ":", "# 'config'...
Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMiddleware. :param global_conf: The global configuration, from the [DEFAULT] section of the PasteDeploy configuration file. :param local_conf: The local configuration, from ...
[ "Factory", "function", "for", "Bark", ".", "Returns", "a", "function", "which", "when", "passed", "the", "application", "returns", "an", "instance", "of", "BarkMiddleware", "." ]
train
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/middleware.py#L29-L106
monkeython/scriba
scriba/content_encodings/gzip.py
decode
def decode(binary): """Decode (gunzip) binary data.""" encoded = io.BytesIO(binary) with gzip.GzipFile(mode='rb', fileobj=encoded) as file_: decoded = file_.read() return decoded
python
def decode(binary): """Decode (gunzip) binary data.""" encoded = io.BytesIO(binary) with gzip.GzipFile(mode='rb', fileobj=encoded) as file_: decoded = file_.read() return decoded
[ "def", "decode", "(", "binary", ")", ":", "encoded", "=", "io", ".", "BytesIO", "(", "binary", ")", "with", "gzip", ".", "GzipFile", "(", "mode", "=", "'rb'", ",", "fileobj", "=", "encoded", ")", "as", "file_", ":", "decoded", "=", "file_", ".", "r...
Decode (gunzip) binary data.
[ "Decode", "(", "gunzip", ")", "binary", "data", "." ]
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_encodings/gzip.py#L9-L14
monkeython/scriba
scriba/content_encodings/gzip.py
encode
def encode(binary): """Encode (gzip) binary data.""" encoded = io.BytesIO() gzip_file = dict(mode='wb', fileobj=encoded, compresslevel=LEVEL) with gzip.GzipFile(**gzip_file) as file_: file_.write(binary) encoded.seek(0) return encoded.read()
python
def encode(binary): """Encode (gzip) binary data.""" encoded = io.BytesIO() gzip_file = dict(mode='wb', fileobj=encoded, compresslevel=LEVEL) with gzip.GzipFile(**gzip_file) as file_: file_.write(binary) encoded.seek(0) return encoded.read()
[ "def", "encode", "(", "binary", ")", ":", "encoded", "=", "io", ".", "BytesIO", "(", ")", "gzip_file", "=", "dict", "(", "mode", "=", "'wb'", ",", "fileobj", "=", "encoded", ",", "compresslevel", "=", "LEVEL", ")", "with", "gzip", ".", "GzipFile", "(...
Encode (gzip) binary data.
[ "Encode", "(", "gzip", ")", "binary", "data", "." ]
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_encodings/gzip.py#L17-L24
minhhoit/yacms
yacms/blog/views.py
blog_post_list
def blog_post_list(request, tag=None, year=None, month=None, username=None, category=None, template="blog/blog_post_list.html", extra_context=None): """ Display a list of blog posts that are filtered by tag, year, month, author or category. Custom templates are checked ...
python
def blog_post_list(request, tag=None, year=None, month=None, username=None, category=None, template="blog/blog_post_list.html", extra_context=None): """ Display a list of blog posts that are filtered by tag, year, month, author or category. Custom templates are checked ...
[ "def", "blog_post_list", "(", "request", ",", "tag", "=", "None", ",", "year", "=", "None", ",", "month", "=", "None", ",", "username", "=", "None", ",", "category", "=", "None", ",", "template", "=", "\"blog/blog_post_list.html\"", ",", "extra_context", "...
Display a list of blog posts that are filtered by tag, year, month, author or category. Custom templates are checked for using the name ``blog/blog_post_list_XXX.html`` where ``XXX`` is either the category slug or author's username if given.
[ "Display", "a", "list", "of", "blog", "posts", "that", "are", "filtered", "by", "tag", "year", "month", "author", "or", "category", ".", "Custom", "templates", "are", "checked", "for", "using", "the", "name", "blog", "/", "blog_post_list_XXX", ".", "html", ...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/views.py#L21-L63
minhhoit/yacms
yacms/blog/views.py
blog_post_detail
def blog_post_detail(request, slug, year=None, month=None, day=None, template="blog/blog_post_detail.html", extra_context=None): """. Custom templates are checked for using the name ``blog/blog_post_detail_XXX.html`` where ``XXX`` is the blog posts's slug. """ ...
python
def blog_post_detail(request, slug, year=None, month=None, day=None, template="blog/blog_post_detail.html", extra_context=None): """. Custom templates are checked for using the name ``blog/blog_post_detail_XXX.html`` where ``XXX`` is the blog posts's slug. """ ...
[ "def", "blog_post_detail", "(", "request", ",", "slug", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "template", "=", "\"blog/blog_post_detail.html\"", ",", "extra_context", "=", "None", ")", ":", "blog_posts", "=", "B...
. Custom templates are checked for using the name ``blog/blog_post_detail_XXX.html`` where ``XXX`` is the blog posts's slug.
[ ".", "Custom", "templates", "are", "checked", "for", "using", "the", "name", "blog", "/", "blog_post_detail_XXX", ".", "html", "where", "XXX", "is", "the", "blog", "posts", "s", "slug", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/views.py#L66-L81
minhhoit/yacms
yacms/blog/views.py
blog_post_feed
def blog_post_feed(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """ try: return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request) except KeyError: raise Http404()
python
def blog_post_feed(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """ try: return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request) except KeyError: raise Http404()
[ "def", "blog_post_feed", "(", "request", ",", "format", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "{", "\"rss\"", ":", "PostsRSS", ",", "\"atom\"", ":", "PostsAtom", "}", "[", "format", "]", "(", "*", "*", "kwargs", ")", "(", "request"...
Blog posts feeds - maps format to the correct feed view.
[ "Blog", "posts", "feeds", "-", "maps", "format", "to", "the", "correct", "feed", "view", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/views.py#L84-L91
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQBackendMixin.connect
def connect(self): """ Connects to RabbitMQ """ self.connection = Connection(self.broker_url) e = Exchange('mease', type='fanout', durable=False, delivery_mode=1) self.exchange = e(self.connection.default_channel) self.exchange.declare()
python
def connect(self): """ Connects to RabbitMQ """ self.connection = Connection(self.broker_url) e = Exchange('mease', type='fanout', durable=False, delivery_mode=1) self.exchange = e(self.connection.default_channel) self.exchange.declare()
[ "def", "connect", "(", "self", ")", ":", "self", ".", "connection", "=", "Connection", "(", "self", ".", "broker_url", ")", "e", "=", "Exchange", "(", "'mease'", ",", "type", "=", "'fanout'", ",", "durable", "=", "False", ",", "delivery_mode", "=", "1"...
Connects to RabbitMQ
[ "Connects", "to", "RabbitMQ" ]
train
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L32-L40
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQPublisher.publish
def publish(self, message_type, client_id, client_storage, *args, **kwargs): """ Publishes a message Uses `self.pack` instead of 'msgpack' serializer on kombu for backend consistency """ if self.connection.connected: message = self.exchange.Message( se...
python
def publish(self, message_type, client_id, client_storage, *args, **kwargs): """ Publishes a message Uses `self.pack` instead of 'msgpack' serializer on kombu for backend consistency """ if self.connection.connected: message = self.exchange.Message( se...
[ "def", "publish", "(", "self", ",", "message_type", ",", "client_id", ",", "client_storage", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "connection", ".", "connected", ":", "message", "=", "self", ".", "exchange", ".", "Mes...
Publishes a message Uses `self.pack` instead of 'msgpack' serializer on kombu for backend consistency
[ "Publishes", "a", "message", "Uses", "self", ".", "pack", "instead", "of", "msgpack", "serializer", "on", "kombu", "for", "backend", "consistency" ]
train
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L53-L61
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQSubscriber.connect
def connect(self): """ Connects to RabbitMQ and starts listening """ logger.info("Connecting to RabbitMQ on {broker_url}...".format( broker_url=self.broker_url)) super(RabbitMQSubscriber, self).connect() q = Queue(exchange=self.exchange, exclusive=True, dura...
python
def connect(self): """ Connects to RabbitMQ and starts listening """ logger.info("Connecting to RabbitMQ on {broker_url}...".format( broker_url=self.broker_url)) super(RabbitMQSubscriber, self).connect() q = Queue(exchange=self.exchange, exclusive=True, dura...
[ "def", "connect", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Connecting to RabbitMQ on {broker_url}...\"", ".", "format", "(", "broker_url", "=", "self", ".", "broker_url", ")", ")", "super", "(", "RabbitMQSubscriber", ",", "self", ")", ".", "connec...
Connects to RabbitMQ and starts listening
[ "Connects", "to", "RabbitMQ", "and", "starts", "listening" ]
train
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L68-L84
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQSubscriber.listen
def listen(self): """ Listens to messages """ with Consumer(self.connection, queues=self.queue, on_message=self.on_message, auto_declare=False): for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True): pass
python
def listen(self): """ Listens to messages """ with Consumer(self.connection, queues=self.queue, on_message=self.on_message, auto_declare=False): for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True): pass
[ "def", "listen", "(", "self", ")", ":", "with", "Consumer", "(", "self", ".", "connection", ",", "queues", "=", "self", ".", "queue", ",", "on_message", "=", "self", ".", "on_message", ",", "auto_declare", "=", "False", ")", ":", "for", "_", "in", "e...
Listens to messages
[ "Listens", "to", "messages" ]
train
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L86-L93
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQSubscriber.on_message
def on_message(self, message): """ Handles message """ message_type, client_id, client_storage, args, kwargs = self.unpack( message.body) self.dispatch_message( message_type, client_id, client_storage, args, kwargs) message.ack()
python
def on_message(self, message): """ Handles message """ message_type, client_id, client_storage, args, kwargs = self.unpack( message.body) self.dispatch_message( message_type, client_id, client_storage, args, kwargs) message.ack()
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "message_type", ",", "client_id", ",", "client_storage", ",", "args", ",", "kwargs", "=", "self", ".", "unpack", "(", "message", ".", "body", ")", "self", ".", "dispatch_message", "(", "message_ty...
Handles message
[ "Handles", "message" ]
train
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L95-L105
tbreitenfeldt/invisible_ui
invisible_ui/session.py
Session.main_loop
def main_loop(self): """Runs the main game loop.""" while True: for e in pygame.event.get(): self.handle_event(e) self.step() pygame.time.wait(5)
python
def main_loop(self): """Runs the main game loop.""" while True: for e in pygame.event.get(): self.handle_event(e) self.step() pygame.time.wait(5)
[ "def", "main_loop", "(", "self", ")", ":", "while", "True", ":", "for", "e", "in", "pygame", ".", "event", ".", "get", "(", ")", ":", "self", ".", "handle_event", "(", "e", ")", "self", ".", "step", "(", ")", "pygame", ".", "time", ".", "wait", ...
Runs the main game loop.
[ "Runs", "the", "main", "game", "loop", "." ]
train
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/session.py#L48-L55
tbreitenfeldt/invisible_ui
invisible_ui/session.py
Session.quit
def quit(self, event): """Quit the game.""" self.logger.info("Quitting.") self.on_exit() sys.exit()
python
def quit(self, event): """Quit the game.""" self.logger.info("Quitting.") self.on_exit() sys.exit()
[ "def", "quit", "(", "self", ",", "event", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Quitting.\"", ")", "self", ".", "on_exit", "(", ")", "sys", ".", "exit", "(", ")" ]
Quit the game.
[ "Quit", "the", "game", "." ]
train
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/session.py#L84-L88
mqopen/mqreceive
mqreceive/broker.py
Broker.setCredentials
def setCredentials(self, user, password): """! Set authentication credentials. @param user Username. @param password Password. """ self._checkUserAndPass(user, password) self.user = user self.password = password
python
def setCredentials(self, user, password): """! Set authentication credentials. @param user Username. @param password Password. """ self._checkUserAndPass(user, password) self.user = user self.password = password
[ "def", "setCredentials", "(", "self", ",", "user", ",", "password", ")", ":", "self", ".", "_checkUserAndPass", "(", "user", ",", "password", ")", "self", ".", "user", "=", "user", "self", ".", "password", "=", "password" ]
! Set authentication credentials. @param user Username. @param password Password.
[ "!", "Set", "authentication", "credentials", "." ]
train
https://github.com/mqopen/mqreceive/blob/cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf/mqreceive/broker.py#L48-L57
espenak/django_seleniumhelpers
seleniumhelpers/seleniumhelpers.py
get_setting_with_envfallback
def get_setting_with_envfallback(setting, default=None, typecast=None): """ Get the given setting and fall back to the default of not found in ``django.conf.settings`` or ``os.environ``. :param settings: The setting as a string. :param default: The fallback if ``setting`` is not found. :param t...
python
def get_setting_with_envfallback(setting, default=None, typecast=None): """ Get the given setting and fall back to the default of not found in ``django.conf.settings`` or ``os.environ``. :param settings: The setting as a string. :param default: The fallback if ``setting`` is not found. :param t...
[ "def", "get_setting_with_envfallback", "(", "setting", ",", "default", "=", "None", ",", "typecast", "=", "None", ")", ":", "try", ":", "from", "django", ".", "conf", "import", "settings", "except", "ImportError", ":", "return", "default", "else", ":", "fall...
Get the given setting and fall back to the default of not found in ``django.conf.settings`` or ``os.environ``. :param settings: The setting as a string. :param default: The fallback if ``setting`` is not found. :param typecast: A function that converts the given value from string to another typ...
[ "Get", "the", "given", "setting", "and", "fall", "back", "to", "the", "default", "of", "not", "found", "in", "django", ".", "conf", ".", "settings", "or", "os", ".", "environ", "." ]
train
https://github.com/espenak/django_seleniumhelpers/blob/c86781f2c89b850780945621c78fb6776da64f28/seleniumhelpers/seleniumhelpers.py#L11-L31
Wessie/hurler
hurler/callbacks.py
Callbacks.register
def register(self, event_name): """ Decorator, Registers the decorated function as a callback for the `event_name` given. :param event_name: The name of the event to register for. Example: >>> callbacks = Callbacks() >>> @callbacks.register("my_...
python
def register(self, event_name): """ Decorator, Registers the decorated function as a callback for the `event_name` given. :param event_name: The name of the event to register for. Example: >>> callbacks = Callbacks() >>> @callbacks.register("my_...
[ "def", "register", "(", "self", ",", "event_name", ")", ":", "def", "registrar", "(", "func", ")", ":", "self", ".", "callbacks", "[", "event_name", "]", ".", "append", "(", "func", ")", "return", "func", "return", "registrar" ]
Decorator, Registers the decorated function as a callback for the `event_name` given. :param event_name: The name of the event to register for. Example: >>> callbacks = Callbacks() >>> @callbacks.register("my_event") ... def hello(): ......
[ "Decorator" ]
train
https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/callbacks.py#L12-L37
Wessie/hurler
hurler/callbacks.py
Callbacks.send
def send(self, event_name, *args, **kwargs): """ Method, Calls all callbacks registered for `event_name`. The arguments given are passed to each callback. :param event_name: The event name to call the callbacks for. :param args: The positional arguments passed to the ca...
python
def send(self, event_name, *args, **kwargs): """ Method, Calls all callbacks registered for `event_name`. The arguments given are passed to each callback. :param event_name: The event name to call the callbacks for. :param args: The positional arguments passed to the ca...
[ "def", "send", "(", "self", ",", "event_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "callback", "in", "self", ".", "callbacks", "[", "event_name", "]", ":", "# Handle errors (and maybe return values)", "callback", "(", "*", "args", "...
Method, Calls all callbacks registered for `event_name`. The arguments given are passed to each callback. :param event_name: The event name to call the callbacks for. :param args: The positional arguments passed to the callbacks. :param kwargs: The keyword arguments passed to t...
[ "Method" ]
train
https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/callbacks.py#L39-L62
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.add_file_locations
def add_file_locations(self, file_locations=[]): """ Adds a list of file locations to the current list Args: file_locations: list of file location tuples """ if not hasattr(self, '__file_locations__'): self.__file_locations__ = copy.copy(file_locations) ...
python
def add_file_locations(self, file_locations=[]): """ Adds a list of file locations to the current list Args: file_locations: list of file location tuples """ if not hasattr(self, '__file_locations__'): self.__file_locations__ = copy.copy(file_locations) ...
[ "def", "add_file_locations", "(", "self", ",", "file_locations", "=", "[", "]", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'__file_locations__'", ")", ":", "self", ".", "__file_locations__", "=", "copy", ".", "copy", "(", "file_locations", ")", "...
Adds a list of file locations to the current list Args: file_locations: list of file location tuples
[ "Adds", "a", "list", "of", "file", "locations", "to", "the", "current", "list" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L50-L60
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.reset
def reset(self, **kwargs): """ Reset the triplestore with all of the data """ self.drop_all(**kwargs) file_locations = self.__file_locations__ self.__file_locations__ = [] self.load(file_locations, **kwargs)
python
def reset(self, **kwargs): """ Reset the triplestore with all of the data """ self.drop_all(**kwargs) file_locations = self.__file_locations__ self.__file_locations__ = [] self.load(file_locations, **kwargs)
[ "def", "reset", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "drop_all", "(", "*", "*", "kwargs", ")", "file_locations", "=", "self", ".", "__file_locations__", "self", ".", "__file_locations__", "=", "[", "]", "self", ".", "load", "(",...
Reset the triplestore with all of the data
[ "Reset", "the", "triplestore", "with", "all", "of", "the", "data" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L63-L69
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.drop_all
def drop_all(self, **kwargs): """ Drops all definitions""" conn = self.__get_conn__(**kwargs) conn.update_query("DROP ALL") self.loaded = [] self.loaded_times = {}
python
def drop_all(self, **kwargs): """ Drops all definitions""" conn = self.__get_conn__(**kwargs) conn.update_query("DROP ALL") self.loaded = [] self.loaded_times = {}
[ "def", "drop_all", "(", "self", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "self", ".", "__get_conn__", "(", "*", "*", "kwargs", ")", "conn", ".", "update_query", "(", "\"DROP ALL\"", ")", "self", ".", "loaded", "=", "[", "]", "self", ".", "lo...
Drops all definitions
[ "Drops", "all", "definitions" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L76-L81
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.load
def load(self, file_locations=[], **kwargs): """ Loads the file_locations into the triplestores args: file_locations: list of tuples to load [('vocabularies', [list of vocabs to load]) ('directory', '/directory/path') ('filepath'...
python
def load(self, file_locations=[], **kwargs): """ Loads the file_locations into the triplestores args: file_locations: list of tuples to load [('vocabularies', [list of vocabs to load]) ('directory', '/directory/path') ('filepath'...
[ "def", "load", "(", "self", ",", "file_locations", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "self", ".", "set_load_state", "(", "*", "*", "kwargs", ")", "if", "file_locations", ":", "self", ".", "__file_locations__", "+=", "file_locations", "els...
Loads the file_locations into the triplestores args: file_locations: list of tuples to load [('vocabularies', [list of vocabs to load]) ('directory', '/directory/path') ('filepath', '/path/to/a/file') ('package_all',...
[ "Loads", "the", "file_locations", "into", "the", "triplestores" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L88-L134
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.load_file
def load_file(self, filepath, **kwargs): """ loads a file into the defintion triplestore args: filepath: the path to the file """ log.setLevel(kwargs.get("log_level", self.log_level)) filename = os.path.split(filepath)[-1] if filename in self.loaded: ...
python
def load_file(self, filepath, **kwargs): """ loads a file into the defintion triplestore args: filepath: the path to the file """ log.setLevel(kwargs.get("log_level", self.log_level)) filename = os.path.split(filepath)[-1] if filename in self.loaded: ...
[ "def", "load_file", "(", "self", ",", "filepath", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "\"log_level\"", ",", "self", ".", "log_level", ")", ")", "filename", "=", "os", ".", "path", ".", "split", ...
loads a file into the defintion triplestore args: filepath: the path to the file
[ "loads", "a", "file", "into", "the", "defintion", "triplestore" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L165-L190
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.drop_file
def drop_file(self, filename, **kwargs): """ removes the passed in file from the connected triplestore args: filename: the filename to remove """ log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) result = conn.update_que...
python
def drop_file(self, filename, **kwargs): """ removes the passed in file from the connected triplestore args: filename: the filename to remove """ log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) result = conn.update_que...
[ "def", "drop_file", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "\"log_level\"", ",", "self", ".", "log_level", ")", ")", "conn", "=", "self", ".", "__get_conn__", "(", "*",...
removes the passed in file from the connected triplestore args: filename: the filename to remove
[ "removes", "the", "passed", "in", "file", "from", "the", "connected", "triplestore" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L223-L250
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.load_times
def load_times(self, **kwargs): """ get the load times for the all of the definition files""" log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) try: result = conn.query(""" SELECT ?file ?time { ...
python
def load_times(self, **kwargs): """ get the load times for the all of the definition files""" log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) try: result = conn.query(""" SELECT ?file ?time { ...
[ "def", "load_times", "(", "self", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "\"log_level\"", ",", "self", ".", "log_level", ")", ")", "conn", "=", "self", ".", "__get_conn__", "(", "*", "*", "kwargs", ...
get the load times for the all of the definition files
[ "get", "the", "load", "times", "for", "the", "all", "of", "the", "definition", "files" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L253-L277
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.load_directory
def load_directory(self, directory, **kwargs): """ loads all rdf files in a directory args: directory: full path to the directory """ log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) file_extensions = kwargs.get('file_e...
python
def load_directory(self, directory, **kwargs): """ loads all rdf files in a directory args: directory: full path to the directory """ log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) file_extensions = kwargs.get('file_e...
[ "def", "load_directory", "(", "self", ",", "directory", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "\"log_level\"", ",", "self", ".", "log_level", ")", ")", "conn", "=", "self", ".", "__get_conn__", "(", ...
loads all rdf files in a directory args: directory: full path to the directory
[ "loads", "all", "rdf", "files", "in", "a", "directory" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L279-L294
abalkin/tz
tz/tzfile.py
read
def read(fileobj, version=None): """Read tz data from a binary file. @param fileobj: @param version: @return: TZFileData """ magic = fileobj.read(5) if magic[:4] != b"TZif": raise ValueError("not a zoneinfo file") if version is None: version = int(magic[4:]) if magic[4] ...
python
def read(fileobj, version=None): """Read tz data from a binary file. @param fileobj: @param version: @return: TZFileData """ magic = fileobj.read(5) if magic[:4] != b"TZif": raise ValueError("not a zoneinfo file") if version is None: version = int(magic[4:]) if magic[4] ...
[ "def", "read", "(", "fileobj", ",", "version", "=", "None", ")", ":", "magic", "=", "fileobj", ".", "read", "(", "5", ")", "if", "magic", "[", ":", "4", "]", "!=", "b\"TZif\"", ":", "raise", "ValueError", "(", "\"not a zoneinfo file\"", ")", "if", "v...
Read tz data from a binary file. @param fileobj: @param version: @return: TZFileData
[ "Read", "tz", "data", "from", "a", "binary", "file", "." ]
train
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/tz/tzfile.py#L31-L101
openpermissions/chub
chub/handlers.py
convert
def convert(data): """ convert a standalone unicode string or unicode strings in a mapping or iterable into byte strings. """ if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, str): return data elif isinstance(data, collections.Mapping): ...
python
def convert(data): """ convert a standalone unicode string or unicode strings in a mapping or iterable into byte strings. """ if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, str): return data elif isinstance(data, collections.Mapping): ...
[ "def", "convert", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "unicode", ")", ":", "return", "data", ".", "encode", "(", "'utf-8'", ")", "elif", "isinstance", "(", "data", ",", "str", ")", ":", "return", "data", "elif", "isinstance", ...
convert a standalone unicode string or unicode strings in a mapping or iterable into byte strings.
[ "convert", "a", "standalone", "unicode", "string", "or", "unicode", "strings", "in", "a", "mapping", "or", "iterable", "into", "byte", "strings", "." ]
train
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L26-L40
openpermissions/chub
chub/handlers.py
make_request
def make_request(request, method, default_headers=None, **kwargs): """ convert parameters into relevant parts of the an http request :param request: either url or an HTTPRequest object :param method: http request method :param default_headers: default headers :param kwargs: headers, query st...
python
def make_request(request, method, default_headers=None, **kwargs): """ convert parameters into relevant parts of the an http request :param request: either url or an HTTPRequest object :param method: http request method :param default_headers: default headers :param kwargs: headers, query st...
[ "def", "make_request", "(", "request", ",", "method", ",", "default_headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "convert", "(", "kwargs", ")", "if", "not", "default_headers", ":", "headers", "=", "dict", "(", "DEFAULT_HEADERS",...
convert parameters into relevant parts of the an http request :param request: either url or an HTTPRequest object :param method: http request method :param default_headers: default headers :param kwargs: headers, query string params for GET and DELETE, data for POST and PUT
[ "convert", "parameters", "into", "relevant", "parts", "of", "the", "an", "http", "request", ":", "param", "request", ":", "either", "url", "or", "an", "HTTPRequest", "object", ":", "param", "method", ":", "http", "request", "method", ":", "param", "default_h...
train
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L43-L75
openpermissions/chub
chub/handlers.py
parse_response
def parse_response(response): """ parse response and return a dictionary if the content type. is json/application. :param response: HTTPRequest :return dictionary for json content type otherwise response body """ if response.headers.get('Content-Type', JSON_TYPE).startswith(JSON_TYPE): ...
python
def parse_response(response): """ parse response and return a dictionary if the content type. is json/application. :param response: HTTPRequest :return dictionary for json content type otherwise response body """ if response.headers.get('Content-Type', JSON_TYPE).startswith(JSON_TYPE): ...
[ "def", "parse_response", "(", "response", ")", ":", "if", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ",", "JSON_TYPE", ")", ".", "startswith", "(", "JSON_TYPE", ")", ":", "return", "ResponseObject", "(", "json", ".", "loads", "(", "resp...
parse response and return a dictionary if the content type. is json/application. :param response: HTTPRequest :return dictionary for json content type otherwise response body
[ "parse", "response", "and", "return", "a", "dictionary", "if", "the", "content", "type", ".", "is", "json", "/", "application", ".", ":", "param", "response", ":", "HTTPRequest", ":", "return", "dictionary", "for", "json", "content", "type", "otherwise", "re...
train
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L91-L101
openpermissions/chub
chub/handlers.py
sync_fetch
def sync_fetch(request, method, default_headers=None, httpclient=None, **kwargs): """ fetch resource using the synchronous HTTPClient :param request: HTTPRequest object or a url :param method: HTTP method in string format, e.g. GET, POST :param kwargs: query string entities or POST da...
python
def sync_fetch(request, method, default_headers=None, httpclient=None, **kwargs): """ fetch resource using the synchronous HTTPClient :param request: HTTPRequest object or a url :param method: HTTP method in string format, e.g. GET, POST :param kwargs: query string entities or POST da...
[ "def", "sync_fetch", "(", "request", ",", "method", ",", "default_headers", "=", "None", ",", "httpclient", "=", "None", ",", "*", "*", "kwargs", ")", ":", "updated_request", "=", "make_request", "(", "request", ",", "method", ",", "default_headers", ",", ...
fetch resource using the synchronous HTTPClient :param request: HTTPRequest object or a url :param method: HTTP method in string format, e.g. GET, POST :param kwargs: query string entities or POST data
[ "fetch", "resource", "using", "the", "synchronous", "HTTPClient", ":", "param", "request", ":", "HTTPRequest", "object", "or", "a", "url", ":", "param", "method", ":", "HTTP", "method", "in", "string", "format", "e", ".", "g", ".", "GET", "POST", ":", "p...
train
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L104-L116
openpermissions/chub
chub/handlers.py
async_fetch
def async_fetch(request, method, default_headers=None, callback=None, httpclient=None, **kwargs): """ fetch resource using the asynchronous AsyncHTTPClient :param request: HTTPRequest object or a url :param method: HTTP method in string format, e.g. GET, POST :param callback: callbac...
python
def async_fetch(request, method, default_headers=None, callback=None, httpclient=None, **kwargs): """ fetch resource using the asynchronous AsyncHTTPClient :param request: HTTPRequest object or a url :param method: HTTP method in string format, e.g. GET, POST :param callback: callbac...
[ "def", "async_fetch", "(", "request", ",", "method", ",", "default_headers", "=", "None", ",", "callback", "=", "None", ",", "httpclient", "=", "None", ",", "*", "*", "kwargs", ")", ":", "updated_request", "=", "make_request", "(", "request", ",", "method"...
fetch resource using the asynchronous AsyncHTTPClient :param request: HTTPRequest object or a url :param method: HTTP method in string format, e.g. GET, POST :param callback: callback function on the result. it is used by the coroutine decorator. :param kwargs: query string entities or POST data
[ "fetch", "resource", "using", "the", "asynchronous", "AsyncHTTPClient", ":", "param", "request", ":", "HTTPRequest", "object", "or", "a", "url", ":", "param", "method", ":", "HTTP", "method", "in", "string", "format", "e", ".", "g", ".", "GET", "POST", ":"...
train
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L120-L134
openpermissions/chub
chub/handlers.py
make_fetch_func
def make_fetch_func(base_url, async, **kwargs): """ make a fetch function based on conditions of 1) async 2) ssl """ if async: client = AsyncHTTPClient(force_instance=True, defaults=kwargs) return partial(async_fetch, httpclient=client) else: client = HTTPClient(force...
python
def make_fetch_func(base_url, async, **kwargs): """ make a fetch function based on conditions of 1) async 2) ssl """ if async: client = AsyncHTTPClient(force_instance=True, defaults=kwargs) return partial(async_fetch, httpclient=client) else: client = HTTPClient(force...
[ "def", "make_fetch_func", "(", "base_url", ",", "async", ",", "*", "*", "kwargs", ")", ":", "if", "async", ":", "client", "=", "AsyncHTTPClient", "(", "force_instance", "=", "True", ",", "defaults", "=", "kwargs", ")", "return", "partial", "(", "async_fetc...
make a fetch function based on conditions of 1) async 2) ssl
[ "make", "a", "fetch", "function", "based", "on", "conditions", "of", "1", ")", "async", "2", ")", "ssl" ]
train
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L137-L148
dstufft/crust
crust/api.py
Api.http_resource
def http_resource(self, method, url, params=None, data=None): """ Makes an HTTP request. """ url = urllib_parse.urljoin(self.url, url) url = url if url.endswith("/") else url + "/" headers = None if method.lower() in self.unsupported_methods: header...
python
def http_resource(self, method, url, params=None, data=None): """ Makes an HTTP request. """ url = urllib_parse.urljoin(self.url, url) url = url if url.endswith("/") else url + "/" headers = None if method.lower() in self.unsupported_methods: header...
[ "def", "http_resource", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ")", ":", "url", "=", "urllib_parse", ".", "urljoin", "(", "self", ".", "url", ",", "url", ")", "url", "=", "url", "if", "url", ...
Makes an HTTP request.
[ "Makes", "an", "HTTP", "request", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/api.py#L69-L87
racker/python-twisted-keystone-agent
txKeystone/keystone.py
KeystoneAgent._getAuthHeaders
def _getAuthHeaders(self): """ Get authentication headers. If we have valid header data already, they immediately return it. If not, then get new authentication data. If we are currently in the process of getting the header data, put this request into a queue to be handle...
python
def _getAuthHeaders(self): """ Get authentication headers. If we have valid header data already, they immediately return it. If not, then get new authentication data. If we are currently in the process of getting the header data, put this request into a queue to be handle...
[ "def", "_getAuthHeaders", "(", "self", ")", ":", "def", "_handleAuthBody", "(", "body", ")", ":", "self", ".", "msg", "(", "\"_handleAuthBody: %(body)s\"", ",", "body", "=", "body", ")", "try", ":", "body_parsed", "=", "json", ".", "loads", "(", "body", ...
Get authentication headers. If we have valid header data already, they immediately return it. If not, then get new authentication data. If we are currently in the process of getting the header data, put this request into a queue to be handled when the data are received. ...
[ "Get", "authentication", "headers", ".", "If", "we", "have", "valid", "header", "data", "already", "they", "immediately", "return", "it", ".", "If", "not", "then", "get", "new", "authentication", "data", ".", "If", "we", "are", "currently", "in", "the", "p...
train
https://github.com/racker/python-twisted-keystone-agent/blob/8b245bc51cc4a4512550cd64e6f1007379ca1466/txKeystone/keystone.py#L166-L261
tagcubeio/tagcube-cli
tagcube_cli/main.py
main
def main(): """ Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit. """ cmd_args = TagCubeCLI.parse_args() try: tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args) except ValueError, ve: # We get here when there are no...
python
def main(): """ Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit. """ cmd_args = TagCubeCLI.parse_args() try: tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args) except ValueError, ve: # We get here when there are no...
[ "def", "main", "(", ")", ":", "cmd_args", "=", "TagCubeCLI", ".", "parse_args", "(", ")", "try", ":", "tagcube_cli", "=", "TagCubeCLI", ".", "from_cmd_args", "(", "cmd_args", ")", "except", "ValueError", ",", "ve", ":", "# We get here when there are no credentia...
Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit.
[ "Project", "s", "main", "method", "which", "will", "parse", "the", "command", "line", "arguments", "run", "a", "scan", "using", "the", "TagCubeClient", "and", "exit", "." ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/main.py#L6-L26
jenanwise/codequality
codequality/checkers.py
register
def register(filetypes): """ Decorator to register a class as a checker for extensions. """ def decorator(clazz): for ext in filetypes: checkers.setdefault(ext, []).append(clazz) return clazz return decorator
python
def register(filetypes): """ Decorator to register a class as a checker for extensions. """ def decorator(clazz): for ext in filetypes: checkers.setdefault(ext, []).append(clazz) return clazz return decorator
[ "def", "register", "(", "filetypes", ")", ":", "def", "decorator", "(", "clazz", ")", ":", "for", "ext", "in", "filetypes", ":", "checkers", ".", "setdefault", "(", "ext", ",", "[", "]", ")", ".", "append", "(", "clazz", ")", "return", "clazz", "retu...
Decorator to register a class as a checker for extensions.
[ "Decorator", "to", "register", "a", "class", "as", "a", "checker", "for", "extensions", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L11-L19
jenanwise/codequality
codequality/checkers.py
Checker.check
def check(self, paths): """ Return list of error dicts for all found errors in paths. The default implementation expects `tool`, and `tool_err_re` to be defined. tool: external binary to use for checking. tool_err_re: regexp that can match output of `tool` -- must provi...
python
def check(self, paths): """ Return list of error dicts for all found errors in paths. The default implementation expects `tool`, and `tool_err_re` to be defined. tool: external binary to use for checking. tool_err_re: regexp that can match output of `tool` -- must provi...
[ "def", "check", "(", "self", ",", "paths", ")", ":", "if", "not", "paths", ":", "return", "(", ")", "cmd_pieces", "=", "[", "self", ".", "tool", "]", "cmd_pieces", ".", "extend", "(", "self", ".", "tool_args", ")", "return", "self", ".", "_check_std"...
Return list of error dicts for all found errors in paths. The default implementation expects `tool`, and `tool_err_re` to be defined. tool: external binary to use for checking. tool_err_re: regexp that can match output of `tool` -- must provide a groupdict with at least "fi...
[ "Return", "list", "of", "error", "dicts", "for", "all", "found", "errors", "in", "paths", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L40-L57
jenanwise/codequality
codequality/checkers.py
Checker.get_version
def get_version(cls): """ Return the version number of the tool. """ cmd_pieces = [cls.tool, '--version'] process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() if err: return '' else: return out.spli...
python
def get_version(cls): """ Return the version number of the tool. """ cmd_pieces = [cls.tool, '--version'] process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() if err: return '' else: return out.spli...
[ "def", "get_version", "(", "cls", ")", ":", "cmd_pieces", "=", "[", "cls", ".", "tool", ",", "'--version'", "]", "process", "=", "Popen", "(", "cmd_pieces", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "out", ",", "err", "=", "process...
Return the version number of the tool.
[ "Return", "the", "version", "number", "of", "the", "tool", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L60-L70
jenanwise/codequality
codequality/checkers.py
Checker._check_std
def _check_std(self, paths, cmd_pieces): """ Run `cmd` as a check on `paths`. """ cmd_pieces.extend(paths) process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() lines = out.strip().splitlines() + err.strip().splitlines() re...
python
def _check_std(self, paths, cmd_pieces): """ Run `cmd` as a check on `paths`. """ cmd_pieces.extend(paths) process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() lines = out.strip().splitlines() + err.strip().splitlines() re...
[ "def", "_check_std", "(", "self", ",", "paths", ",", "cmd_pieces", ")", ":", "cmd_pieces", ".", "extend", "(", "paths", ")", "process", "=", "Popen", "(", "cmd_pieces", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "out", ",", "err", "...
Run `cmd` as a check on `paths`.
[ "Run", "cmd", "as", "a", "check", "on", "paths", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L74-L102
knagra/farnsworth
elections/models.py
PollRanks.create_ranking
def create_ranking(ranking_tuples): """ Create and return a string suitable for the rankings field when given tuples of choices and rankings. Parameters: ranking_tuples should be an iterable of tuples of form (choice, ranking) """ return ",...
python
def create_ranking(ranking_tuples): """ Create and return a string suitable for the rankings field when given tuples of choices and rankings. Parameters: ranking_tuples should be an iterable of tuples of form (choice, ranking) """ return ",...
[ "def", "create_ranking", "(", "ranking_tuples", ")", ":", "return", "\",\"", ".", "join", "(", "[", "str", "(", "r", ")", "for", "c", ",", "r", "in", "sorted", "(", "ranking_tuples", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "...
Create and return a string suitable for the rankings field when given tuples of choices and rankings. Parameters: ranking_tuples should be an iterable of tuples of form (choice, ranking)
[ "Create", "and", "return", "a", "string", "suitable", "for", "the", "rankings", "field", "when", "given", "tuples", "of", "choices", "and", "rankings", ".", "Parameters", ":", "ranking_tuples", "should", "be", "an", "iterable", "of", "tuples", "of", "form", ...
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/elections/models.py#L336-L346
knagra/farnsworth
elections/models.py
PollRanks.normalize_ranking
def normalize_ranking(ranking_tuples): """ Normalize rankings by reducing them to the simplest order. E.g.: If the rankings for 2 choices are -244 and 4, this function will normalize them to 0 and 1, respectively. Parameters: ranking_tuples should...
python
def normalize_ranking(ranking_tuples): """ Normalize rankings by reducing them to the simplest order. E.g.: If the rankings for 2 choices are -244 and 4, this function will normalize them to 0 and 1, respectively. Parameters: ranking_tuples should...
[ "def", "normalize_ranking", "(", "ranking_tuples", ")", ":", "ranking_tuples", "=", "sorted", "(", "ranking_tuples", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "normalized", "=", "[", "(", "ranking_tuples", ".", "pop", "(", "0", ")", ...
Normalize rankings by reducing them to the simplest order. E.g.: If the rankings for 2 choices are -244 and 4, this function will normalize them to 0 and 1, respectively. Parameters: ranking_tuples should be an iterable of tuples of fo...
[ "Normalize", "rankings", "by", "reducing", "them", "to", "the", "simplest", "order", ".", "E", ".", "g", ".", ":", "If", "the", "rankings", "for", "2", "choices", "are", "-", "244", "and", "4", "this", "function", "will", "normalize", "them", "to", "0"...
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/elections/models.py#L348-L369
AguaClara/aide_document-DEPRECATED
aide_document/translate.py
replace
def replace(dict,line): """ Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed. ...
python
def replace(dict,line): """ Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed. ...
[ "def", "replace", "(", "dict", ",", "line", ")", ":", "words", "=", "line", ".", "split", "(", ")", "new_line", "=", "\"\"", "for", "word", "in", "words", ":", "fst", "=", "word", "[", "0", "]", "last", "=", "word", "[", "-", "1", "]", "# Check...
Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed.
[ "Find", "and", "replace", "the", "special", "words", "according", "to", "the", "dictionary", "." ]
train
https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/translate.py#L6-L47
AguaClara/aide_document-DEPRECATED
aide_document/translate.py
translate
def translate(src_filename, dest_filename, dest_lang, src_lang='auto', specialwords_filename=''): """ Converts a source file to a destination file in the selected language. Parameters ========== src_filename : String Relative file path to the original MarkDown source file. dest_filename...
python
def translate(src_filename, dest_filename, dest_lang, src_lang='auto', specialwords_filename=''): """ Converts a source file to a destination file in the selected language. Parameters ========== src_filename : String Relative file path to the original MarkDown source file. dest_filename...
[ "def", "translate", "(", "src_filename", ",", "dest_filename", ",", "dest_lang", ",", "src_lang", "=", "'auto'", ",", "specialwords_filename", "=", "''", ")", ":", "translator", "=", "Translator", "(", ")", "# Initialize translator object", "with", "open", "(", ...
Converts a source file to a destination file in the selected language. Parameters ========== src_filename : String Relative file path to the original MarkDown source file. dest_filename : String Relative file path to where the translated MarkDown file should go. dest_lang : String ...
[ "Converts", "a", "source", "file", "to", "a", "destination", "file", "in", "the", "selected", "language", "." ]
train
https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/translate.py#L49-L128
dugan/coverage-reporter
coverage_reporter/config.py
get_config
def get_config(args): """ Method to get the correct configuration file for a set of command line arguments. Takes into account --config-file, --plugins, -- """ options, _ = defaults.DEFAULT_OPTIONS.parse(args, ignore_errors=True) read_config = not options.skip_default_config cfg = CoverageRe...
python
def get_config(args): """ Method to get the correct configuration file for a set of command line arguments. Takes into account --config-file, --plugins, -- """ options, _ = defaults.DEFAULT_OPTIONS.parse(args, ignore_errors=True) read_config = not options.skip_default_config cfg = CoverageRe...
[ "def", "get_config", "(", "args", ")", ":", "options", ",", "_", "=", "defaults", ".", "DEFAULT_OPTIONS", ".", "parse", "(", "args", ",", "ignore_errors", "=", "True", ")", "read_config", "=", "not", "options", ".", "skip_default_config", "cfg", "=", "Cove...
Method to get the correct configuration file for a set of command line arguments. Takes into account --config-file, --plugins, --
[ "Method", "to", "get", "the", "correct", "configuration", "file", "for", "a", "set", "of", "command", "line", "arguments", ".", "Takes", "into", "account", "--", "config", "-", "file", "--", "plugins", "--" ]
train
https://github.com/dugan/coverage-reporter/blob/18ecc9189de4f62b15366901b2451b8047f1ccfb/coverage_reporter/config.py#L16-L28
alexhayes/django-toolkit
django_toolkit/datetime_util.py
start_of_month
def start_of_month(dt, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://...
python
def start_of_month(dt, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://...
[ "def", "start_of_month", "(", "dt", ",", "d_years", "=", "0", ",", "d_months", "=", "0", ")", ":", "y", ",", "m", "=", "dt", ".", "year", "+", "d_years", ",", "dt", ".", "month", "+", "d_months", "a", ",", "m", "=", "divmod", "(", "m", "-", "...
Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://code.activestate.com/recipes/476197-first-last-day-of-the-m...
[ "Given", "a", "date", "return", "a", "date", "first", "day", "of", "the", "month", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/datetime_util.py#L6-L18
alexhayes/django-toolkit
django_toolkit/datetime_util.py
quarter
def quarter(dt): """ Return start/stop datetime for the quarter as defined by dt. """ quarters = rrule.rrule( rrule.MONTHLY, bymonth = (1, 4, 7, 10), bysetpos = -1, dtstart = datetime(dt.year, 1, 1), count = 8 ) first_day = quarters.before(dt, True) last_da...
python
def quarter(dt): """ Return start/stop datetime for the quarter as defined by dt. """ quarters = rrule.rrule( rrule.MONTHLY, bymonth = (1, 4, 7, 10), bysetpos = -1, dtstart = datetime(dt.year, 1, 1), count = 8 ) first_day = quarters.before(dt, True) last_da...
[ "def", "quarter", "(", "dt", ")", ":", "quarters", "=", "rrule", ".", "rrule", "(", "rrule", ".", "MONTHLY", ",", "bymonth", "=", "(", "1", ",", "4", ",", "7", ",", "10", ")", ",", "bysetpos", "=", "-", "1", ",", "dtstart", "=", "datetime", "("...
Return start/stop datetime for the quarter as defined by dt.
[ "Return", "start", "/", "stop", "datetime", "for", "the", "quarter", "as", "defined", "by", "dt", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/datetime_util.py#L40-L53
qzmfranklin/easyshell
easyshell/base.py
deprecated
def deprecated(f): """Decorate a function object as deprecated. Work nicely with the @command and @subshell decorators. Add a __deprecated__ field to the input object and set it to True. """ def inner_func(*args, **kwargs): print(textwrap.dedent("""\ This command is depreca...
python
def deprecated(f): """Decorate a function object as deprecated. Work nicely with the @command and @subshell decorators. Add a __deprecated__ field to the input object and set it to True. """ def inner_func(*args, **kwargs): print(textwrap.dedent("""\ This command is depreca...
[ "def", "deprecated", "(", "f", ")", ":", "def", "inner_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "(", "textwrap", ".", "dedent", "(", "\"\"\"\\\n This command is deprecated and is subject to complete\n removal at ...
Decorate a function object as deprecated. Work nicely with the @command and @subshell decorators. Add a __deprecated__ field to the input object and set it to True.
[ "Decorate", "a", "function", "object", "as", "deprecated", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L40-L58
qzmfranklin/easyshell
easyshell/base.py
command
def command(*commands, visible = True, internal = False, nargs = '*'): """Decorate a function to be the entry function of commands. Arguments: commands: Names of command that should trigger this function object. visible: This command is visible in tab completions. internal: The lexing r...
python
def command(*commands, visible = True, internal = False, nargs = '*'): """Decorate a function to be the entry function of commands. Arguments: commands: Names of command that should trigger this function object. visible: This command is visible in tab completions. internal: The lexing r...
[ "def", "command", "(", "*", "commands", ",", "visible", "=", "True", ",", "internal", "=", "False", ",", "nargs", "=", "'*'", ")", ":", "# Strict checking of the nargs argument.", "allowed_strs", "=", "{", "'*'", ",", "'?'", ",", "'+'", "}", "err_str", "="...
Decorate a function to be the entry function of commands. Arguments: commands: Names of command that should trigger this function object. visible: This command is visible in tab completions. internal: The lexing rule is unchanged even if the parse_line() method is overloaded in ...
[ "Decorate", "a", "function", "to", "be", "the", "entry", "function", "of", "commands", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L63-L157
qzmfranklin/easyshell
easyshell/base.py
helper
def helper(*commands): """Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ...
python
def helper(*commands): """Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ...
[ "def", "helper", "(", "*", "commands", ")", ":", "def", "decorated_func", "(", "f", ")", ":", "f", ".", "__help_targets__", "=", "list", "(", "commands", ")", "return", "f", "return", "decorated_func" ]
Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ''' Argumen...
[ "Decorate", "a", "function", "to", "be", "the", "helper", "function", "of", "commands", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L181-L204
qzmfranklin/easyshell
easyshell/base.py
completer
def completer(*commands): """Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def comple...
python
def completer(*commands): """Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def comple...
[ "def", "completer", "(", "*", "commands", ")", ":", "def", "decorated_func", "(", "f", ")", ":", "f", ".", "__complete_targets__", "=", "list", "(", "commands", ")", "return", "f", "return", "decorated_func" ]
Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def complete_foo(self, args, text): ...
[ "Decorate", "a", "function", "to", "be", "the", "completer", "function", "of", "commands", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L212-L253
qzmfranklin/easyshell
easyshell/base.py
subshell
def subshell(shell_cls, *commands, **kwargs): """Decorate a function to conditionally launch a _ShellBase subshell. Arguments: shell_cls: A subclass of _ShellBase to be launched. commands: Names of command that should trigger this function object. kwargs: The keyword arguments for the c...
python
def subshell(shell_cls, *commands, **kwargs): """Decorate a function to conditionally launch a _ShellBase subshell. Arguments: shell_cls: A subclass of _ShellBase to be launched. commands: Names of command that should trigger this function object. kwargs: The keyword arguments for the c...
[ "def", "subshell", "(", "shell_cls", ",", "*", "commands", ",", "*", "*", "kwargs", ")", ":", "def", "decorated_func", "(", "f", ")", ":", "def", "inner_func", "(", "self", ",", "cmd", ",", "args", ")", ":", "retval", "=", "f", "(", "self", ",", ...
Decorate a function to conditionally launch a _ShellBase subshell. Arguments: shell_cls: A subclass of _ShellBase to be launched. commands: Names of command that should trigger this function object. kwargs: The keyword arguments for the command decorator method. -----------------------...
[ "Decorate", "a", "function", "to", "conditionally", "launch", "a", "_ShellBase", "subshell", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L267-L325
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.doc_string
def doc_string(cls): """Get the doc string of this class. If this class does not have a doc string or the doc string is empty, try its base classes until the root base class, _ShellBase, is reached. CAVEAT: This method assumes that this class and all its super classes are ...
python
def doc_string(cls): """Get the doc string of this class. If this class does not have a doc string or the doc string is empty, try its base classes until the root base class, _ShellBase, is reached. CAVEAT: This method assumes that this class and all its super classes are ...
[ "def", "doc_string", "(", "cls", ")", ":", "clz", "=", "cls", "while", "not", "clz", ".", "__doc__", ":", "clz", "=", "clz", ".", "__bases__", "[", "0", "]", "return", "clz", ".", "__doc__" ]
Get the doc string of this class. If this class does not have a doc string or the doc string is empty, try its base classes until the root base class, _ShellBase, is reached. CAVEAT: This method assumes that this class and all its super classes are derived from _ShellBa...
[ "Get", "the", "doc", "string", "of", "this", "class", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L437-L450
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.launch_subshell
def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context = {}): """Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of sub...
python
def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context = {}): """Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of sub...
[ "def", "launch_subshell", "(", "self", ",", "shell_cls", ",", "cmd", ",", "args", ",", "*", ",", "prompt", "=", "None", ",", "context", "=", "{", "}", ")", ":", "# Save history of the current shell.", "readline", ".", "write_history_file", "(", "self", ".", ...
Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of subshells through the subshell() decorator function. Nonetheless, the user has the option o...
[ "Launch", "a", "subshell", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L480-L539
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.batch_string
def batch_string(self, content): """Process a string in batch mode. Arguments: content: A unicode string representing the content to be processed. """ pipe_send, pipe_recv = multiprocessing.Pipe() self._pipe_end = pipe_recv proc = multiprocessing.Process(targ...
python
def batch_string(self, content): """Process a string in batch mode. Arguments: content: A unicode string representing the content to be processed. """ pipe_send, pipe_recv = multiprocessing.Pipe() self._pipe_end = pipe_recv proc = multiprocessing.Process(targ...
[ "def", "batch_string", "(", "self", ",", "content", ")", ":", "pipe_send", ",", "pipe_recv", "=", "multiprocessing", ".", "Pipe", "(", ")", "self", ".", "_pipe_end", "=", "pipe_recv", "proc", "=", "multiprocessing", ".", "Process", "(", "target", "=", "sel...
Process a string in batch mode. Arguments: content: A unicode string representing the content to be processed.
[ "Process", "a", "string", "in", "batch", "mode", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L541-L554
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.cmdloop
def cmdloop(self): """Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectively. Returns: 'root': Inform the parent shell to to keep exiting until the root shell is reached....
python
def cmdloop(self): """Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectively. Returns: 'root': Inform the parent shell to to keep exiting until the root shell is reached....
[ "def", "cmdloop", "(", "self", ")", ":", "self", ".", "print_debug", "(", "\"Enter subshell '{}'\"", ".", "format", "(", "self", ".", "prompt", ")", ")", "# Save the completer function, the history buffer, and the", "# completer_delims.", "old_completer", "=", "readline...
Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectively. Returns: 'root': Inform the parent shell to to keep exiting until the root shell is reached. 'all': Exit all t...
[ "Start", "the", "main", "loop", "of", "the", "interactive", "shell", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L562-L665
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.parse_line
def parse_line(self, line): """Parse a line of input. The input line is tokenized using the same rules as the way bash shell tokenizes inputs. All quoting and escaping rules from the bash shell apply here too. The following cases are handled by __exec_line__(): 1. ...
python
def parse_line(self, line): """Parse a line of input. The input line is tokenized using the same rules as the way bash shell tokenizes inputs. All quoting and escaping rules from the bash shell apply here too. The following cases are handled by __exec_line__(): 1. ...
[ "def", "parse_line", "(", "self", ",", "line", ")", ":", "toks", "=", "shlex", ".", "split", "(", "line", ")", "# Safe to index the 0-th element because this line would have been", "# parsed by __exec_line__ if toks is an empty list.", "return", "(", "toks", "[", "0", "...
Parse a line of input. The input line is tokenized using the same rules as the way bash shell tokenizes inputs. All quoting and escaping rules from the bash shell apply here too. The following cases are handled by __exec_line__(): 1. Empty line. 2. The input l...
[ "Parse", "a", "line", "of", "input", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L714-L746
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__driver_stub
def __driver_stub(self, text, state): """Display help messages or invoke the proper completer. The interface of helper methods and completer methods are documented in the helper() decorator method and the completer() decorator method, respectively. Arguments: text: ...
python
def __driver_stub(self, text, state): """Display help messages or invoke the proper completer. The interface of helper methods and completer methods are documented in the helper() decorator method and the completer() decorator method, respectively. Arguments: text: ...
[ "def", "__driver_stub", "(", "self", ",", "text", ",", "state", ")", ":", "origline", "=", "readline", ".", "get_line_buffer", "(", ")", "line", "=", "origline", ".", "lstrip", "(", ")", "if", "line", "and", "line", "[", "-", "1", "]", "==", "'?'", ...
Display help messages or invoke the proper completer. The interface of helper methods and completer methods are documented in the helper() decorator method and the completer() decorator method, respectively. Arguments: text: A string, that is the current completion scope. ...
[ "Display", "help", "messages", "or", "invoke", "the", "proper", "completer", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L748-L776
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__driver_completer
def __driver_completer(self, toks, text, state): """Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A string, the text to be replaced if a completion candidate is chosen. state: An integer, the ...
python
def __driver_completer(self, toks, text, state): """Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A string, the text to be replaced if a completion candidate is chosen. state: An integer, the ...
[ "def", "__driver_completer", "(", "self", ",", "toks", ",", "text", ",", "state", ")", ":", "if", "state", "!=", "0", ":", "return", "self", ".", "__completion_candidates", "[", "state", "]", "# Update the cache when this method is first called, i.e., state == 0.", ...
Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A string, the text to be replaced if a completion candidate is chosen. state: An integer, the index of the candidate out of the list of ca...
[ "Driver", "level", "completer", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L778-L825
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__complete_cmds
def __complete_cmds(self, text): """Get the list of commands whose names start with a given text.""" return [ name for name in self._cmd_map_visible.keys() if name.startswith(text) ]
python
def __complete_cmds(self, text): """Get the list of commands whose names start with a given text.""" return [ name for name in self._cmd_map_visible.keys() if name.startswith(text) ]
[ "def", "__complete_cmds", "(", "self", ",", "text", ")", ":", "return", "[", "name", "for", "name", "in", "self", ".", "_cmd_map_visible", ".", "keys", "(", ")", "if", "name", ".", "startswith", "(", "text", ")", "]" ]
Get the list of commands whose names start with a given text.
[ "Get", "the", "list", "of", "commands", "whose", "names", "start", "with", "a", "given", "text", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L827-L829
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__driver_helper
def __driver_helper(self, line): """Driver level helper method. 1. Display help message for the given input. Internally calls self.__get_help_message() to obtain the help message. 2. Re-display the prompt and the input line. Arguments: line: The input line. ...
python
def __driver_helper(self, line): """Driver level helper method. 1. Display help message for the given input. Internally calls self.__get_help_message() to obtain the help message. 2. Re-display the prompt and the input line. Arguments: line: The input line. ...
[ "def", "__driver_helper", "(", "self", ",", "line", ")", ":", "if", "line", ".", "strip", "(", ")", "==", "'?'", ":", "self", ".", "stdout", ".", "write", "(", "'\\n'", ")", "self", ".", "stdout", ".", "write", "(", "self", ".", "doc_string", "(", ...
Driver level helper method. 1. Display help message for the given input. Internally calls self.__get_help_message() to obtain the help message. 2. Re-display the prompt and the input line. Arguments: line: The input line. Raises: Errors from helpe...
[ "Driver", "level", "helper", "method", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L831-L862
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__get_help_message
def __get_help_message(self, toks): """Write help message to file. Only called by the __driver_helper() method. Looks for the help message in the following order: 1. The helper method registered with this command via the @helper decorator. 2. The doc ...
python
def __get_help_message(self, toks): """Write help message to file. Only called by the __driver_helper() method. Looks for the help message in the following order: 1. The helper method registered with this command via the @helper decorator. 2. The doc ...
[ "def", "__get_help_message", "(", "self", ",", "toks", ")", ":", "cmd", "=", "toks", "[", "0", "]", "if", "cmd", "in", "self", ".", "_helper_map", ".", "keys", "(", ")", ":", "helper_name", "=", "self", ".", "_helper_map", "[", "cmd", "]", "helper_me...
Write help message to file. Only called by the __driver_helper() method. Looks for the help message in the following order: 1. The helper method registered with this command via the @helper decorator. 2. The doc string of the registered method. 3....
[ "Write", "help", "message", "to", "file", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L864-L903
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__build_cmd_maps
def __build_cmd_maps(cls): """Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns:...
python
def __build_cmd_maps(cls): """Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns:...
[ "def", "__build_cmd_maps", "(", "cls", ")", ":", "cmd_map_all", "=", "{", "}", "cmd_map_visible", "=", "{", "}", "cmd_map_internal", "=", "{", "}", "for", "name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "name", ")",...
Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns: A tuple (cmd_map, hidden_...
[ "Build", "the", "mapping", "from", "command", "names", "to", "method", "names", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L913-L942
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__build_helper_map
def __build_helper_map(cls): """Build a mapping from command names to helper names. One command name maps to at most one helper method. Multiple command names can map to the same helper method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. ...
python
def __build_helper_map(cls): """Build a mapping from command names to helper names. One command name maps to at most one helper method. Multiple command names can map to the same helper method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. ...
[ "def", "__build_helper_map", "(", "cls", ")", ":", "ret", "=", "{", "}", "for", "name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "name", ")", "if", "ishelper", "(", "obj", ")", ":", "for", "cmd", "in", "obj", "...
Build a mapping from command names to helper names. One command name maps to at most one helper method. Multiple command names can map to the same helper method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShellError: ...
[ "Build", "a", "mapping", "from", "command", "names", "to", "helper", "names", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L945-L968
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__build_completer_map
def __build_completer_map(cls): """Build a mapping from command names to completer names. One command name maps to at most one completer method. Multiple command names can map to the same completer method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used el...
python
def __build_completer_map(cls): """Build a mapping from command names to completer names. One command name maps to at most one completer method. Multiple command names can map to the same completer method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used el...
[ "def", "__build_completer_map", "(", "cls", ")", ":", "ret", "=", "{", "}", "for", "name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "name", ")", "if", "iscompleter", "(", "obj", ")", ":", "for", "cmd", "in", "obj...
Build a mapping from command names to completer names. One command name maps to at most one completer method. Multiple command names can map to the same completer method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShe...
[ "Build", "a", "mapping", "from", "command", "names", "to", "completer", "names", "." ]
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L971-L995
gebn/nibble
nibble/decorators.py
operator_same_class
def operator_same_class(method): """ Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with. """ def wrapper(self, other): ...
python
def operator_same_class(method): """ Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with. """ def wrapper(self, other): ...
[ "def", "operator_same_class", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "raise", "TypeError", "(", "'unsupported operand types: \\'{0}\\' an...
Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with.
[ "Intended", "to", "wrap", "operator", "methods", "this", "decorator", "ensures", "the", "other", "parameter", "is", "of", "the", "same", "type", "as", "the", "self", "parameter", ".", ":", "param", "method", ":", "The", "method", "being", "decorated", ".", ...
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/decorators.py#L9-L23
gebn/nibble
nibble/decorators.py
operator_numeric_type
def operator_numeric_type(method): """ Intended to wrap operator methods, this decorator ensures a numeric type was passed. :param method: The method being decorated. :return: The wrapper to replace the method with. """ def wrapper(self, other): if not isinstance(other, _NUMERIC...
python
def operator_numeric_type(method): """ Intended to wrap operator methods, this decorator ensures a numeric type was passed. :param method: The method being decorated. :return: The wrapper to replace the method with. """ def wrapper(self, other): if not isinstance(other, _NUMERIC...
[ "def", "operator_numeric_type", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "_NUMERIC_TYPES", ")", ":", "raise", "TypeError", "(", "'unsupported operand types: \\'{0}\\' and \\'{1}\\...
Intended to wrap operator methods, this decorator ensures a numeric type was passed. :param method: The method being decorated. :return: The wrapper to replace the method with.
[ "Intended", "to", "wrap", "operator", "methods", "this", "decorator", "ensures", "a", "numeric", "type", "was", "passed", ".", ":", "param", "method", ":", "The", "method", "being", "decorated", ".", ":", "return", ":", "The", "wrapper", "to", "replace", "...
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/decorators.py#L26-L40
gebn/nibble
nibble/decorators.py
python_2_format_compatible
def python_2_format_compatible(method): """ Handles bytestring and unicode inputs for the `__format__()` method in Python 2. This function has no effect in Python 3. :param method: The `__format__()` method to wrap. :return: The wrapped method. """ if six.PY3: return method def...
python
def python_2_format_compatible(method): """ Handles bytestring and unicode inputs for the `__format__()` method in Python 2. This function has no effect in Python 3. :param method: The `__format__()` method to wrap. :return: The wrapped method. """ if six.PY3: return method def...
[ "def", "python_2_format_compatible", "(", "method", ")", ":", "if", "six", ".", "PY3", ":", "return", "method", "def", "wrapper", "(", "self", ",", "format_spec", ")", ":", "formatted", "=", "method", "(", "self", ",", "format_spec", ")", "if", "isinstance...
Handles bytestring and unicode inputs for the `__format__()` method in Python 2. This function has no effect in Python 3. :param method: The `__format__()` method to wrap. :return: The wrapped method.
[ "Handles", "bytestring", "and", "unicode", "inputs", "for", "the", "__format__", "()", "method", "in", "Python", "2", ".", "This", "function", "has", "no", "effect", "in", "Python", "3", "." ]
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/decorators.py#L43-L62
gebn/nibble
nibble/decorators.py
python_2_nonzero_compatible
def python_2_nonzero_compatible(klass): """ Adds a `__nonzero__()` method to classes that define a `__bool__()` method, so boolean conversion works in Python 2. Has no effect in Python 3. :param klass: The class to modify. Must define `__bool__()`. :return: The possibly patched class. """ i...
python
def python_2_nonzero_compatible(klass): """ Adds a `__nonzero__()` method to classes that define a `__bool__()` method, so boolean conversion works in Python 2. Has no effect in Python 3. :param klass: The class to modify. Must define `__bool__()`. :return: The possibly patched class. """ i...
[ "def", "python_2_nonzero_compatible", "(", "klass", ")", ":", "if", "six", ".", "PY2", ":", "if", "'__bool__'", "not", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "'@python_2_nonzero_compatible cannot be applied to {0} because '", "'it doesn\\'t def...
Adds a `__nonzero__()` method to classes that define a `__bool__()` method, so boolean conversion works in Python 2. Has no effect in Python 3. :param klass: The class to modify. Must define `__bool__()`. :return: The possibly patched class.
[ "Adds", "a", "__nonzero__", "()", "method", "to", "classes", "that", "define", "a", "__bool__", "()", "method", "so", "boolean", "conversion", "works", "in", "Python", "2", ".", "Has", "no", "effect", "in", "Python", "3", "." ]
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/decorators.py#L65-L79
gebn/nibble
nibble/decorators.py
python_2_div_compatible
def python_2_div_compatible(klass): """ Adds a `__div__()` method to classes that define a `__floordiv__()` method, so division works in Python 2. Has no effect in Python 3. :param klass: The class to modify. Must define `__floordiv__()`. :return: The possibly patched class. """ if six.PY2:...
python
def python_2_div_compatible(klass): """ Adds a `__div__()` method to classes that define a `__floordiv__()` method, so division works in Python 2. Has no effect in Python 3. :param klass: The class to modify. Must define `__floordiv__()`. :return: The possibly patched class. """ if six.PY2:...
[ "def", "python_2_div_compatible", "(", "klass", ")", ":", "if", "six", ".", "PY2", ":", "if", "'__floordiv__'", "not", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "'@python_2_div_compatible cannot be applied to {0} because it '", "'doesn\\'t define ...
Adds a `__div__()` method to classes that define a `__floordiv__()` method, so division works in Python 2. Has no effect in Python 3. :param klass: The class to modify. Must define `__floordiv__()`. :return: The possibly patched class.
[ "Adds", "a", "__div__", "()", "method", "to", "classes", "that", "define", "a", "__floordiv__", "()", "method", "so", "division", "works", "in", "Python", "2", ".", "Has", "no", "effect", "in", "Python", "3", "." ]
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/decorators.py#L82-L96
rgmining/ria
ria/credibility.py
GraphBasedCredibility.review_score
def review_score(self, reviewer, product): """Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A revi...
python
def review_score(self, reviewer, product): """Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A revi...
[ "def", "review_score", "(", "self", ",", "reviewer", ",", "product", ")", ":", "return", "self", ".", "_g", ".", "retrieve_review", "(", "reviewer", ",", "product", ")", ".", "score" ]
Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A review object representing the review from the reviewer to...
[ "Find", "a", "review", "score", "from", "a", "given", "reviewer", "to", "a", "product", "." ]
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/credibility.py#L109-L119
tducret/precisionmapper-python
python-flask/swagger_server/models/base_model_.py
Model.from_dict
def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls)
python
def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls)
[ "def", "from_dict", "(", "cls", ":", "typing", ".", "Type", "[", "T", "]", ",", "dikt", ")", "->", "T", ":", "return", "util", ".", "deserialize_model", "(", "dikt", ",", "cls", ")" ]
Returns the dict as a model
[ "Returns", "the", "dict", "as", "a", "model" ]
train
https://github.com/tducret/precisionmapper-python/blob/462dcc5bccf6edec780b8b7bc42e8c1d717db942/python-flask/swagger_server/models/base_model_.py#L21-L23
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfBaseFactory.get_defs
def get_defs(self, cache=True): """ Gets the defitions args: cache: True will read from the file cache, False queries the triplestore """ log.debug(" *** Started") cache = self.__use_cache__(cache) if cache: log.info(" loading ...
python
def get_defs(self, cache=True): """ Gets the defitions args: cache: True will read from the file cache, False queries the triplestore """ log.debug(" *** Started") cache = self.__use_cache__(cache) if cache: log.info(" loading ...
[ "def", "get_defs", "(", "self", ",", "cache", "=", "True", ")", ":", "log", ".", "debug", "(", "\" *** Started\"", ")", "cache", "=", "self", ".", "__use_cache__", "(", "cache", ")", "if", "cache", ":", "log", ".", "info", "(", "\" loading json cache\"",...
Gets the defitions args: cache: True will read from the file cache, False queries the triplestore
[ "Gets", "the", "defitions" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L96-L127
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfBaseFactory.conv_defs
def conv_defs(self): """ Reads through the JSON object and converts them to Dataset """ log.setLevel(self.log_level) start = datetime.datetime.now() log.debug(" Converting to a Dataset: %s Triples", len(self.results)) self.defs = RdfDataset(self.results, ...
python
def conv_defs(self): """ Reads through the JSON object and converts them to Dataset """ log.setLevel(self.log_level) start = datetime.datetime.now() log.debug(" Converting to a Dataset: %s Triples", len(self.results)) self.defs = RdfDataset(self.results, ...
[ "def", "conv_defs", "(", "self", ")", ":", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "debug", "(", "\" Converting to a Dataset: %s Triples\"", ",", "len", "(", ...
Reads through the JSON object and converts them to Dataset
[ "Reads", "through", "the", "JSON", "object", "and", "converts", "them", "to", "Dataset" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L129-L140
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfPropertyFactory.make
def make(self): """ reads through the definitions and generates an python class for each definition """ log.setLevel(self.log_level) created = [] prop_list = [item for item in self.defs if item.type == 'uri'] log.debug(" creating properties ... ") for prop in prop...
python
def make(self): """ reads through the definitions and generates an python class for each definition """ log.setLevel(self.log_level) created = [] prop_list = [item for item in self.defs if item.type == 'uri'] log.debug(" creating properties ... ") for prop in prop...
[ "def", "make", "(", "self", ")", ":", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "created", "=", "[", "]", "prop_list", "=", "[", "item", "for", "item", "in", "self", ".", "defs", "if", "item", ".", "type", "==", "'uri'", "]", "l...
reads through the definitions and generates an python class for each definition
[ "reads", "through", "the", "definitions", "and", "generates", "an", "python", "class", "for", "each", "definition" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L151-L160
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfClassFactory.make
def make(self): """ reads through the definitions and generates an python class for each definition """ log.setLevel(self.log_level) created = [] self.set_class_dict() start = datetime.datetime.now() log.info(" # of classes to create: %s" % len(self.class_dict)) ...
python
def make(self): """ reads through the definitions and generates an python class for each definition """ log.setLevel(self.log_level) created = [] self.set_class_dict() start = datetime.datetime.now() log.info(" # of classes to create: %s" % len(self.class_dict)) ...
[ "def", "make", "(", "self", ")", ":", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "created", "=", "[", "]", "self", ".", "set_class_dict", "(", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "info"...
reads through the definitions and generates an python class for each definition
[ "reads", "through", "the", "definitions", "and", "generates", "an", "python", "class", "for", "each", "definition" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L178-L265
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfClassFactory.set_class_dict
def set_class_dict(self): """ Reads through the dataset and assigns self.class_dict the key value pairs for the classes in the dataset """ self.class_dict = {} for name, cls_defs in self.defs.items(): def_type = set(cls_defs.get(self.rdf_type, [])) if...
python
def set_class_dict(self): """ Reads through the dataset and assigns self.class_dict the key value pairs for the classes in the dataset """ self.class_dict = {} for name, cls_defs in self.defs.items(): def_type = set(cls_defs.get(self.rdf_type, [])) if...
[ "def", "set_class_dict", "(", "self", ")", ":", "self", ".", "class_dict", "=", "{", "}", "for", "name", ",", "cls_defs", "in", "self", ".", "defs", ".", "items", "(", ")", ":", "def_type", "=", "set", "(", "cls_defs", ".", "get", "(", "self", ".",...
Reads through the dataset and assigns self.class_dict the key value pairs for the classes in the dataset
[ "Reads", "through", "the", "dataset", "and", "assigns", "self", ".", "class_dict", "the", "key", "value", "pairs", "for", "the", "classes", "in", "the", "dataset" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L266-L281
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfClassFactory.tie_properties
def tie_properties(self, class_list): """ Runs through the classess and ties the properties to the class args: class_list: a list of class names to run """ log.setLevel(self.log_level) start = datetime.datetime.now() log.info(" Tieing properties to the class"...
python
def tie_properties(self, class_list): """ Runs through the classess and ties the properties to the class args: class_list: a list of class names to run """ log.setLevel(self.log_level) start = datetime.datetime.now() log.info(" Tieing properties to the class"...
[ "def", "tie_properties", "(", "self", ",", "class_list", ")", ":", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "info", "(", "\" Tieing properties to the class\"", ...
Runs through the classess and ties the properties to the class args: class_list: a list of class names to run
[ "Runs", "through", "the", "classess", "and", "ties", "the", "properties", "to", "the", "class" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L283-L298
ariebovenberg/valuable
valuable/xml.py
elemgetter
def elemgetter(path: str) -> t.Callable[[Element], Element]: """shortcut making an XML element getter""" return compose( partial(_raise_if_none, exc=LookupError(path)), methodcaller('find', path) )
python
def elemgetter(path: str) -> t.Callable[[Element], Element]: """shortcut making an XML element getter""" return compose( partial(_raise_if_none, exc=LookupError(path)), methodcaller('find', path) )
[ "def", "elemgetter", "(", "path", ":", "str", ")", "->", "t", ".", "Callable", "[", "[", "Element", "]", ",", "Element", "]", ":", "return", "compose", "(", "partial", "(", "_raise_if_none", ",", "exc", "=", "LookupError", "(", "path", ")", ")", ",",...
shortcut making an XML element getter
[ "shortcut", "making", "an", "XML", "element", "getter" ]
train
https://github.com/ariebovenberg/valuable/blob/72ac98b5a044233f13d14a9b9f273ce3a237d9ae/valuable/xml.py#L15-L20