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 |
|---|---|---|---|---|---|---|---|---|---|---|
cbrand/vpnchooser | src/vpnchooser/query/rules_query.py | RulesQuery.sync | def sync(self, rules: list):
"""
Synchronizes the given rules with the server
and ensures that there are no old rules active
which are not in the given list.
"""
self._reset()
old_rules = self.rules
to_delete_rules = [
rule for rule in old_rule... | python | def sync(self, rules: list):
"""
Synchronizes the given rules with the server
and ensures that there are no old rules active
which are not in the given list.
"""
self._reset()
old_rules = self.rules
to_delete_rules = [
rule for rule in old_rule... | [
"def",
"sync",
"(",
"self",
",",
"rules",
":",
"list",
")",
":",
"self",
".",
"_reset",
"(",
")",
"old_rules",
"=",
"self",
".",
"rules",
"to_delete_rules",
"=",
"[",
"rule",
"for",
"rule",
"in",
"old_rules",
"if",
"rule",
"not",
"in",
"rules",
"]",
... | Synchronizes the given rules with the server
and ensures that there are no old rules active
which are not in the given list. | [
"Synchronizes",
"the",
"given",
"rules",
"with",
"the",
"server",
"and",
"ensures",
"that",
"there",
"are",
"no",
"old",
"rules",
"active",
"which",
"are",
"not",
"in",
"the",
"given",
"list",
"."
] | train | https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L82-L107 |
cbrand/vpnchooser | src/vpnchooser/query/rules_query.py | RulesQuery._update | def _update(self, rules: list):
"""
Updates the given rules and stores
them on the router.
"""
self._rules = rules
to_store = '\n'.join(
rule.config_string
for rule in rules
)
sftp_connection = self._sftp_connection
with sft... | python | def _update(self, rules: list):
"""
Updates the given rules and stores
them on the router.
"""
self._rules = rules
to_store = '\n'.join(
rule.config_string
for rule in rules
)
sftp_connection = self._sftp_connection
with sft... | [
"def",
"_update",
"(",
"self",
",",
"rules",
":",
"list",
")",
":",
"self",
".",
"_rules",
"=",
"rules",
"to_store",
"=",
"'\\n'",
".",
"join",
"(",
"rule",
".",
"config_string",
"for",
"rule",
"in",
"rules",
")",
"sftp_connection",
"=",
"self",
".",
... | Updates the given rules and stores
them on the router. | [
"Updates",
"the",
"given",
"rules",
"and",
"stores",
"them",
"on",
"the",
"router",
"."
] | train | https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L109-L121 |
kynikos/lib.py.cmenu | cmenu.py | _Command.help | def help(self, *args):
"""
Can be overridden (and for example _Menu does).
"""
if args:
self.messages.error(
self.messages.command_does_not_accept_arguments)
else:
print(self.helpfull) | python | def help(self, *args):
"""
Can be overridden (and for example _Menu does).
"""
if args:
self.messages.error(
self.messages.command_does_not_accept_arguments)
else:
print(self.helpfull) | [
"def",
"help",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"self",
".",
"messages",
".",
"error",
"(",
"self",
".",
"messages",
".",
"command_does_not_accept_arguments",
")",
"else",
":",
"print",
"(",
"self",
".",
"helpfull",
")"
] | Can be overridden (and for example _Menu does). | [
"Can",
"be",
"overridden",
"(",
"and",
"for",
"example",
"_Menu",
"does",
")",
"."
] | train | https://github.com/kynikos/lib.py.cmenu/blob/eb1e806f0b674c4deb24730cbd7cf4604150c461/cmenu.py#L237-L245 |
kynikos/lib.py.cmenu | cmenu.py | _CommandWithFlags.complete | def complete(self, sp_args, line, rl_prefix, rl_begidx, rl_endidx):
"""
Override in order to have command or argument completion.
It is necessary to return a 'list', i.e. not a tuple or other
sequences.
"""
# TODO: Optionally check that flags are not repeated (i.e. exclu... | python | def complete(self, sp_args, line, rl_prefix, rl_begidx, rl_endidx):
"""
Override in order to have command or argument completion.
It is necessary to return a 'list', i.e. not a tuple or other
sequences.
"""
# TODO: Optionally check that flags are not repeated (i.e. exclu... | [
"def",
"complete",
"(",
"self",
",",
"sp_args",
",",
"line",
",",
"rl_prefix",
",",
"rl_begidx",
",",
"rl_endidx",
")",
":",
"# TODO: Optionally check that flags are not repeated (i.e. exclude",
"# them from the possible matches if they are already in the",
"# command... | Override in order to have command or argument completion.
It is necessary to return a 'list', i.e. not a tuple or other
sequences. | [
"Override",
"in",
"order",
"to",
"have",
"command",
"or",
"argument",
"completion",
"."
] | train | https://github.com/kynikos/lib.py.cmenu/blob/eb1e806f0b674c4deb24730cbd7cf4604150c461/cmenu.py#L264-L298 |
kynikos/lib.py.cmenu | cmenu.py | _Menu.iter_walk_menus | def iter_walk_menus(self):
"""
Useful for example to spread changes to the prompt, e.g. enabling or
disabling colors.
"""
yield self
for item in self.name_to_command.values():
if isinstance(item, _Menu):
# "Generator delegation" ;)
... | python | def iter_walk_menus(self):
"""
Useful for example to spread changes to the prompt, e.g. enabling or
disabling colors.
"""
yield self
for item in self.name_to_command.values():
if isinstance(item, _Menu):
# "Generator delegation" ;)
... | [
"def",
"iter_walk_menus",
"(",
"self",
")",
":",
"yield",
"self",
"for",
"item",
"in",
"self",
".",
"name_to_command",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"_Menu",
")",
":",
"# \"Generator delegation\" ;)",
"# https://docs.pytho... | Useful for example to spread changes to the prompt, e.g. enabling or
disabling colors. | [
"Useful",
"for",
"example",
"to",
"spread",
"changes",
"to",
"the",
"prompt",
"e",
".",
"g",
".",
"enabling",
"or",
"disabling",
"colors",
"."
] | train | https://github.com/kynikos/lib.py.cmenu/blob/eb1e806f0b674c4deb24730cbd7cf4604150c461/cmenu.py#L331-L341 |
troup-system/troup | troup/infrastructure.py | IncomingChannelWSAdapter.local_address | def local_address(self):
"""
Local endpoint address as a tuple
"""
if not self._local_address:
self._local_address = self.proto.reader._transport.get_extra_info('sockname')
if len(self._local_address) == 4:
self._local_address = self._local_address... | python | def local_address(self):
"""
Local endpoint address as a tuple
"""
if not self._local_address:
self._local_address = self.proto.reader._transport.get_extra_info('sockname')
if len(self._local_address) == 4:
self._local_address = self._local_address... | [
"def",
"local_address",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_local_address",
":",
"self",
".",
"_local_address",
"=",
"self",
".",
"proto",
".",
"reader",
".",
"_transport",
".",
"get_extra_info",
"(",
"'sockname'",
")",
"if",
"len",
"(",
"... | Local endpoint address as a tuple | [
"Local",
"endpoint",
"address",
"as",
"a",
"tuple"
] | train | https://github.com/troup-system/troup/blob/e3c74c363101243dfbfc3d2f0c7c8fce5d9ad1a8/troup/infrastructure.py#L198-L206 |
troup-system/troup | troup/infrastructure.py | IncomingChannelWSAdapter.peer_address | def peer_address(self):
"""
Peer endpoint address as a tuple
"""
if not self._peer_address:
self._peer_address = self.proto.reader._transport.get_extra_info('peername')
if len(self._peer_address) == 4:
self._peer_address = self._peer_address[:2]
... | python | def peer_address(self):
"""
Peer endpoint address as a tuple
"""
if not self._peer_address:
self._peer_address = self.proto.reader._transport.get_extra_info('peername')
if len(self._peer_address) == 4:
self._peer_address = self._peer_address[:2]
... | [
"def",
"peer_address",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_peer_address",
":",
"self",
".",
"_peer_address",
"=",
"self",
".",
"proto",
".",
"reader",
".",
"_transport",
".",
"get_extra_info",
"(",
"'peername'",
")",
"if",
"len",
"(",
"sel... | Peer endpoint address as a tuple | [
"Peer",
"endpoint",
"address",
"as",
"a",
"tuple"
] | train | https://github.com/troup-system/troup/blob/e3c74c363101243dfbfc3d2f0c7c8fce5d9ad1a8/troup/infrastructure.py#L209-L217 |
lambdalisue/tolerance | src/tolerance/utils.py | argument_switch_generator | def argument_switch_generator(argument_name=None,
default=True,
reverse=False,
keep=False):
"""
Create switch function which return the status from specified named
argument
Parameters
----------
argument_n... | python | def argument_switch_generator(argument_name=None,
default=True,
reverse=False,
keep=False):
"""
Create switch function which return the status from specified named
argument
Parameters
----------
argument_n... | [
"def",
"argument_switch_generator",
"(",
"argument_name",
"=",
"None",
",",
"default",
"=",
"True",
",",
"reverse",
"=",
"False",
",",
"keep",
"=",
"False",
")",
":",
"def",
"switch_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
... | Create switch function which return the status from specified named
argument
Parameters
----------
argument_name : string or None
An argument name which is used to judge the status.
If ``None`` is specified, the value of
``tolerance.utils.DEFAULT_ARGUMENT_NAME`` will be used ins... | [
"Create",
"switch",
"function",
"which",
"return",
"the",
"status",
"from",
"specified",
"named",
"argument"
] | train | https://github.com/lambdalisue/tolerance/blob/e332622d78b1f8066098cc768af4ed12ccb4153d/src/tolerance/utils.py#L10-L93 |
jmgilman/Neolib | neolib/neocodex/CodexAPI.py | CodexAPI.priceItems | def priceItems(items):
""" Takes a list of Item objects and returns a list of Item objects with respective prices modified
Uses the given list of item objects to formulate a query to the item database. Uses the returned
results to populate each item in the list with its respective price... | python | def priceItems(items):
""" Takes a list of Item objects and returns a list of Item objects with respective prices modified
Uses the given list of item objects to formulate a query to the item database. Uses the returned
results to populate each item in the list with its respective price... | [
"def",
"priceItems",
"(",
"items",
")",
":",
"retItems",
"=",
"[",
"]",
"sendItems",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"sendItems",
".",
"append",
"(",
"item",
".",
"name",
")",
"resp",
"=",
"CodexAPI",
".",
"searchMany",
"(",
"sendIt... | Takes a list of Item objects and returns a list of Item objects with respective prices modified
Uses the given list of item objects to formulate a query to the item database. Uses the returned
results to populate each item in the list with its respective price, then returns the modified list.
... | [
"Takes",
"a",
"list",
"of",
"Item",
"objects",
"and",
"returns",
"a",
"list",
"of",
"Item",
"objects",
"with",
"respective",
"prices",
"modified",
"Uses",
"the",
"given",
"list",
"of",
"item",
"objects",
"to",
"formulate",
"a",
"query",
"to",
"the",
"item"... | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/neocodex/CodexAPI.py#L49-L71 |
jjangsangy/kan | kan/__main__.py | command_line | def command_line():
'''
Parses users command line arguments and returns the namespace
containing parsed values.
'''
description = 'Kan helps you find the book'
version = ' '.join([__version__, __release__])
parser = ArgumentParser(prog='kan', description=description)
subparser ... | python | def command_line():
'''
Parses users command line arguments and returns the namespace
containing parsed values.
'''
description = 'Kan helps you find the book'
version = ' '.join([__version__, __release__])
parser = ArgumentParser(prog='kan', description=description)
subparser ... | [
"def",
"command_line",
"(",
")",
":",
"description",
"=",
"'Kan helps you find the book'",
"version",
"=",
"' '",
".",
"join",
"(",
"[",
"__version__",
",",
"__release__",
"]",
")",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"'kan'",
",",
"description"... | Parses users command line arguments and returns the namespace
containing parsed values. | [
"Parses",
"users",
"command",
"line",
"arguments",
"and",
"returns",
"the",
"namespace",
"containing",
"parsed",
"values",
"."
] | train | https://github.com/jjangsangy/kan/blob/7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6/kan/__main__.py#L18-L83 |
jjangsangy/kan | kan/__main__.py | main | def main():
"""
Main program entry point
"""
args = command_line()
# TODO: Decouple Book interface and implementation
query = Book(
title=args.title,
author=args.author,
max_results=args.max,
language_code=args.language,
fields=('title', 'authors', 'image... | python | def main():
"""
Main program entry point
"""
args = command_line()
# TODO: Decouple Book interface and implementation
query = Book(
title=args.title,
author=args.author,
max_results=args.max,
language_code=args.language,
fields=('title', 'authors', 'image... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"command_line",
"(",
")",
"# TODO: Decouple Book interface and implementation",
"query",
"=",
"Book",
"(",
"title",
"=",
"args",
".",
"title",
",",
"author",
"=",
"args",
".",
"author",
",",
"max_results",
"=",
"arg... | Main program entry point | [
"Main",
"program",
"entry",
"point"
] | train | https://github.com/jjangsangy/kan/blob/7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6/kan/__main__.py#L86-L135 |
edeposit/edeposit.amqp.calibre | src/edeposit/amqp/calibre/calibre.py | _wrap | def _wrap(text, columns=80):
"""
Own "dumb" reimplementation of textwrap.wrap().
This is because calling .wrap() on bigger strings can take a LOT of
processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of
text without spaces.
Args:
text (str): Text to wrap.
... | python | def _wrap(text, columns=80):
"""
Own "dumb" reimplementation of textwrap.wrap().
This is because calling .wrap() on bigger strings can take a LOT of
processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of
text without spaces.
Args:
text (str): Text to wrap.
... | [
"def",
"_wrap",
"(",
"text",
",",
"columns",
"=",
"80",
")",
":",
"out",
"=",
"[",
"]",
"for",
"cnt",
",",
"char",
"in",
"enumerate",
"(",
"text",
")",
":",
"out",
".",
"append",
"(",
"char",
")",
"if",
"(",
"cnt",
"+",
"1",
")",
"%",
"column... | Own "dumb" reimplementation of textwrap.wrap().
This is because calling .wrap() on bigger strings can take a LOT of
processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of
text without spaces.
Args:
text (str): Text to wrap.
columns (int): Wrap after `columns` chara... | [
"Own",
"dumb",
"reimplementation",
"of",
"textwrap",
".",
"wrap",
"()",
"."
] | train | https://github.com/edeposit/edeposit.amqp.calibre/blob/60ba5de0c30452d41f6e0da58d2ec6729ebdd7f1/src/edeposit/amqp/calibre/calibre.py#L21-L43 |
edeposit/edeposit.amqp.calibre | src/edeposit/amqp/calibre/calibre.py | convert | def convert(input_format, output_format, b64_data):
"""
Convert `b64_data` fron `input_format` to `output_format`.
Args:
input_format (str): Specification of input format (pdf/epub/whatever),
see :attr:`INPUT_FORMATS` for list.
output_format (str): Specificatio... | python | def convert(input_format, output_format, b64_data):
"""
Convert `b64_data` fron `input_format` to `output_format`.
Args:
input_format (str): Specification of input format (pdf/epub/whatever),
see :attr:`INPUT_FORMATS` for list.
output_format (str): Specificatio... | [
"def",
"convert",
"(",
"input_format",
",",
"output_format",
",",
"b64_data",
")",
":",
"# checks",
"assert",
"input_format",
"in",
"INPUT_FORMATS",
",",
"\"Unsupported input format!\"",
"assert",
"output_format",
"in",
"OUTPUT_FORMATS",
",",
"\"Unsupported output format!... | Convert `b64_data` fron `input_format` to `output_format`.
Args:
input_format (str): Specification of input format (pdf/epub/whatever),
see :attr:`INPUT_FORMATS` for list.
output_format (str): Specification of output format (pdf/epub/..),
s... | [
"Convert",
"b64_data",
"fron",
"input_format",
"to",
"output_format",
"."
] | train | https://github.com/edeposit/edeposit.amqp.calibre/blob/60ba5de0c30452d41f6e0da58d2ec6729ebdd7f1/src/edeposit/amqp/calibre/calibre.py#L46-L114 |
thibault/libnexmo | libnexmo/base.py | Nexmo.send_sms | def send_sms(self, frm, to, text):
"""Sends a simple text message.
Example usage::
>>> msg = "Cherie, n'oublie pas les gauffres !"
>>> nexmo.send_sms('+33123456780', '+33987654321', msg)
:arg frm: The `from` field, a phone number (international format with
... | python | def send_sms(self, frm, to, text):
"""Sends a simple text message.
Example usage::
>>> msg = "Cherie, n'oublie pas les gauffres !"
>>> nexmo.send_sms('+33123456780', '+33987654321', msg)
:arg frm: The `from` field, a phone number (international format with
... | [
"def",
"send_sms",
"(",
"self",
",",
"frm",
",",
"to",
",",
"text",
")",
":",
"frm",
"=",
"re",
".",
"sub",
"(",
"'[^\\d]'",
",",
"''",
",",
"frm",
")",
"to",
"=",
"re",
".",
"sub",
"(",
"'[^\\d]'",
",",
"''",
",",
"to",
")",
"api_url",
"=",
... | Sends a simple text message.
Example usage::
>>> msg = "Cherie, n'oublie pas les gauffres !"
>>> nexmo.send_sms('+33123456780', '+33987654321', msg)
:arg frm: The `from` field, a phone number (international format with
or without a leading "+" or alphanumerical).
... | [
"Sends",
"a",
"simple",
"text",
"message",
"."
] | train | https://github.com/thibault/libnexmo/blob/ed6cb6379bbcfd622f32d4e65f1a3f40f7910286/libnexmo/base.py#L32-L60 |
thibault/libnexmo | libnexmo/base.py | Nexmo.send_request | def send_request(self, url, params, method='GET'):
"""Sends a raw request to the given api endpoint.
:arg url: A Nexmpo api endpoint (json only)
:arg params: A parameter dictionnary
Returns a :class:`~libnexmo.NexmoResponse`.
Raises:
The library uses `Requests
... | python | def send_request(self, url, params, method='GET'):
"""Sends a raw request to the given api endpoint.
:arg url: A Nexmpo api endpoint (json only)
:arg params: A parameter dictionnary
Returns a :class:`~libnexmo.NexmoResponse`.
Raises:
The library uses `Requests
... | [
"def",
"send_request",
"(",
"self",
",",
"url",
",",
"params",
",",
"method",
"=",
"'GET'",
")",
":",
"method",
"=",
"method",
".",
"lower",
"(",
")",
"if",
"method",
"not",
"in",
"[",
"'get'",
",",
"'post'",
"]",
":",
"raise",
"ValueError",
"(",
"... | Sends a raw request to the given api endpoint.
:arg url: A Nexmpo api endpoint (json only)
:arg params: A parameter dictionnary
Returns a :class:`~libnexmo.NexmoResponse`.
Raises:
The library uses `Requests
<http://docs.python-requests.org/en/latest/>`_ to per... | [
"Sends",
"a",
"raw",
"request",
"to",
"the",
"given",
"api",
"endpoint",
"."
] | train | https://github.com/thibault/libnexmo/blob/ed6cb6379bbcfd622f32d4e65f1a3f40f7910286/libnexmo/base.py#L62-L95 |
knagra/farnsworth | managers/forms.py | ManagerForm.clean | def clean(self):
''' TinyMCE adds a placeholder <br> if no data is inserted. In this case, remove it. '''
cleaned_data = super(ManagerForm, self).clean()
compensation = cleaned_data.get("compensation")
duties = cleaned_data.get("duties")
if compensation == '<br data-mce-bogus="1... | python | def clean(self):
''' TinyMCE adds a placeholder <br> if no data is inserted. In this case, remove it. '''
cleaned_data = super(ManagerForm, self).clean()
compensation = cleaned_data.get("compensation")
duties = cleaned_data.get("duties")
if compensation == '<br data-mce-bogus="1... | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"ManagerForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"compensation",
"=",
"cleaned_data",
".",
"get",
"(",
"\"compensation\"",
")",
"duties",
"=",
"cleaned_data",
".",
"get",
"... | TinyMCE adds a placeholder <br> if no data is inserted. In this case, remove it. | [
"TinyMCE",
"adds",
"a",
"placeholder",
"<br",
">",
"if",
"no",
"data",
"is",
"inserted",
".",
"In",
"this",
"case",
"remove",
"it",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/managers/forms.py#L50-L59 |
pavelsof/ipatok | ipatok/tokens.py | normalise | def normalise(string):
"""
Convert each character of the string to the normal form in which it was
defined in the IPA spec. This would be normal form D, except for the
voiceless palatar fricative (ç) which should be in normal form C.
Helper for tokenise_word(string, ..).
"""
string = unicodedata.normalize('NFD'... | python | def normalise(string):
"""
Convert each character of the string to the normal form in which it was
defined in the IPA spec. This would be normal form D, except for the
voiceless palatar fricative (ç) which should be in normal form C.
Helper for tokenise_word(string, ..).
"""
string = unicodedata.normalize('NFD'... | [
"def",
"normalise",
"(",
"string",
")",
":",
"string",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
",",
"string",
")",
"for",
"char_c",
"in",
"ipa",
".",
"get_precomposed_chars",
"(",
")",
":",
"char_d",
"=",
"unicodedata",
".",
"normalize",
"(",
... | Convert each character of the string to the normal form in which it was
defined in the IPA spec. This would be normal form D, except for the
voiceless palatar fricative (ç) which should be in normal form C.
Helper for tokenise_word(string, ..). | [
"Convert",
"each",
"character",
"of",
"the",
"string",
"to",
"the",
"normal",
"form",
"in",
"which",
"it",
"was",
"defined",
"in",
"the",
"IPA",
"spec",
".",
"This",
"would",
"be",
"normal",
"form",
"D",
"except",
"for",
"the",
"voiceless",
"palatar",
"f... | train | https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/tokens.py#L7-L22 |
pavelsof/ipatok | ipatok/tokens.py | group | def group(merge_func, tokens):
"""
Group together those of the tokens for which the merge function returns
true. The merge function should accept two arguments/tokens and should
return a boolean indicating whether the strings should be merged or not.
Helper for tokenise(string, ..).
"""
output = []
if tokens:... | python | def group(merge_func, tokens):
"""
Group together those of the tokens for which the merge function returns
true. The merge function should accept two arguments/tokens and should
return a boolean indicating whether the strings should be merged or not.
Helper for tokenise(string, ..).
"""
output = []
if tokens:... | [
"def",
"group",
"(",
"merge_func",
",",
"tokens",
")",
":",
"output",
"=",
"[",
"]",
"if",
"tokens",
":",
"output",
".",
"append",
"(",
"tokens",
"[",
"0",
"]",
")",
"for",
"token",
"in",
"tokens",
"[",
"1",
":",
"]",
":",
"prev_token",
"=",
"out... | Group together those of the tokens for which the merge function returns
true. The merge function should accept two arguments/tokens and should
return a boolean indicating whether the strings should be merged or not.
Helper for tokenise(string, ..). | [
"Group",
"together",
"those",
"of",
"the",
"tokens",
"for",
"which",
"the",
"merge",
"function",
"returns",
"true",
".",
"The",
"merge",
"function",
"should",
"accept",
"two",
"arguments",
"/",
"tokens",
"and",
"should",
"return",
"a",
"boolean",
"indicating",... | train | https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/tokens.py#L25-L46 |
pavelsof/ipatok | ipatok/tokens.py | are_diphtong | def are_diphtong(tokenA, tokenB):
"""
Check (naively) whether the two tokens can form a diphtong. This would be a
sequence of vowels of which no more than one is syllabic. Vowel sequences
connected with a tie bar would already be handled in tokenise_word, so are
not checked for here.
Users who want more sophisti... | python | def are_diphtong(tokenA, tokenB):
"""
Check (naively) whether the two tokens can form a diphtong. This would be a
sequence of vowels of which no more than one is syllabic. Vowel sequences
connected with a tie bar would already be handled in tokenise_word, so are
not checked for here.
Users who want more sophisti... | [
"def",
"are_diphtong",
"(",
"tokenA",
",",
"tokenB",
")",
":",
"is_short",
"=",
"lambda",
"token",
":",
"'◌̯'[1]",
" ",
"i",
"n",
"to",
"en",
"subtokens",
"=",
"[",
"]",
"for",
"char",
"in",
"tokenA",
"+",
"tokenB",
":",
"if",
"ipa",
".",
"is_vowel",... | Check (naively) whether the two tokens can form a diphtong. This would be a
sequence of vowels of which no more than one is syllabic. Vowel sequences
connected with a tie bar would already be handled in tokenise_word, so are
not checked for here.
Users who want more sophisticated diphtong detection should instead ... | [
"Check",
"(",
"naively",
")",
"whether",
"the",
"two",
"tokens",
"can",
"form",
"a",
"diphtong",
".",
"This",
"would",
"be",
"a",
"sequence",
"of",
"vowels",
"of",
"which",
"no",
"more",
"than",
"one",
"is",
"syllabic",
".",
"Vowel",
"sequences",
"connec... | train | https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/tokens.py#L49-L80 |
pavelsof/ipatok | ipatok/tokens.py | tokenise_word | def tokenise_word(string,
strict=False, replace=False, tones=False, unknown=False):
"""
Tokenise the string into a list of tokens or raise ValueError if it cannot
be tokenised (relatively) unambiguously. The string should not include
whitespace, i.e. it is assumed to be a single word.
If strict=False, allow ... | python | def tokenise_word(string,
strict=False, replace=False, tones=False, unknown=False):
"""
Tokenise the string into a list of tokens or raise ValueError if it cannot
be tokenised (relatively) unambiguously. The string should not include
whitespace, i.e. it is assumed to be a single word.
If strict=False, allow ... | [
"def",
"tokenise_word",
"(",
"string",
",",
"strict",
"=",
"False",
",",
"replace",
"=",
"False",
",",
"tones",
"=",
"False",
",",
"unknown",
"=",
"False",
")",
":",
"string",
"=",
"normalise",
"(",
"string",
")",
"if",
"replace",
":",
"string",
"=",
... | Tokenise the string into a list of tokens or raise ValueError if it cannot
be tokenised (relatively) unambiguously. The string should not include
whitespace, i.e. it is assumed to be a single word.
If strict=False, allow non-standard letters and diacritics, as well as
initial diacritic-only tokens (e.g. pre-aspira... | [
"Tokenise",
"the",
"string",
"into",
"a",
"list",
"of",
"tokens",
"or",
"raise",
"ValueError",
"if",
"it",
"cannot",
"be",
"tokenised",
"(",
"relatively",
")",
"unambiguously",
".",
"The",
"string",
"should",
"not",
"include",
"whitespace",
"i",
".",
"e",
... | train | https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/tokens.py#L83-L147 |
pavelsof/ipatok | ipatok/tokens.py | tokenise | def tokenise(string, strict=False, replace=False,
diphtongs=False, tones=False, unknown=False, merge=None):
"""
Tokenise an IPA string into a list of tokens. Raise ValueError if there is
a problem; if strict=True, this includes the string not being compliant to
the IPA spec.
If replace=True, replace some co... | python | def tokenise(string, strict=False, replace=False,
diphtongs=False, tones=False, unknown=False, merge=None):
"""
Tokenise an IPA string into a list of tokens. Raise ValueError if there is
a problem; if strict=True, this includes the string not being compliant to
the IPA spec.
If replace=True, replace some co... | [
"def",
"tokenise",
"(",
"string",
",",
"strict",
"=",
"False",
",",
"replace",
"=",
"False",
",",
"diphtongs",
"=",
"False",
",",
"tones",
"=",
"False",
",",
"unknown",
"=",
"False",
",",
"merge",
"=",
"None",
")",
":",
"words",
"=",
"string",
".",
... | Tokenise an IPA string into a list of tokens. Raise ValueError if there is
a problem; if strict=True, this includes the string not being compliant to
the IPA spec.
If replace=True, replace some common non-IPA symbols with their IPA
counterparts. If diphtongs=True, try to group diphtongs into single tokens.
If ton... | [
"Tokenise",
"an",
"IPA",
"string",
"into",
"a",
"list",
"of",
"tokens",
".",
"Raise",
"ValueError",
"if",
"there",
"is",
"a",
"problem",
";",
"if",
"strict",
"=",
"True",
"this",
"includes",
"the",
"string",
"not",
"being",
"compliant",
"to",
"the",
"IPA... | train | https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/tokens.py#L150-L179 |
pavelsof/ipatok | ipatok/tokens.py | replace_digits_with_chao | def replace_digits_with_chao(string, inverse=False):
"""
Replace the digits 1-5 (also in superscript) with Chao tone letters. Equal
consecutive digits are collapsed into a single Chao letter.
If inverse=True, smaller digits are converted into higher tones; otherwise,
they are converted into lower tones (the defau... | python | def replace_digits_with_chao(string, inverse=False):
"""
Replace the digits 1-5 (also in superscript) with Chao tone letters. Equal
consecutive digits are collapsed into a single Chao letter.
If inverse=True, smaller digits are converted into higher tones; otherwise,
they are converted into lower tones (the defau... | [
"def",
"replace_digits_with_chao",
"(",
"string",
",",
"inverse",
"=",
"False",
")",
":",
"chao_letters",
"=",
"'˩˨˧˦˥'",
"if",
"inverse",
":",
"chao_letters",
"=",
"chao_letters",
"[",
":",
":",
"-",
"1",
"]",
"string",
"=",
"string",
".",
"translate",
"(... | Replace the digits 1-5 (also in superscript) with Chao tone letters. Equal
consecutive digits are collapsed into a single Chao letter.
If inverse=True, smaller digits are converted into higher tones; otherwise,
they are converted into lower tones (the default).
Part of ipatok's public API. | [
"Replace",
"the",
"digits",
"1",
"-",
"5",
"(",
"also",
"in",
"superscript",
")",
"with",
"Chao",
"tone",
"letters",
".",
"Equal",
"consecutive",
"digits",
"are",
"collapsed",
"into",
"a",
"single",
"Chao",
"letter",
"."
] | train | https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/tokens.py#L188-L210 |
KnowledgeLinks/rdfframework | rdfframework/framework.py | verify_server_core | def verify_server_core(timeout=120, start_delay=90):
''' checks to see if the server_core is running
args:
delay: will cycle till core is up.
timeout: number of seconds to wait
'''
timestamp = time.time()
last_check = time.time() + start_delay - 10
last_delay_notific... | python | def verify_server_core(timeout=120, start_delay=90):
''' checks to see if the server_core is running
args:
delay: will cycle till core is up.
timeout: number of seconds to wait
'''
timestamp = time.time()
last_check = time.time() + start_delay - 10
last_delay_notific... | [
"def",
"verify_server_core",
"(",
"timeout",
"=",
"120",
",",
"start_delay",
"=",
"90",
")",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"last_check",
"=",
"time",
".",
"time",
"(",
")",
"+",
"start_delay",
"-",
"10",
"last_delay_notification",
... | checks to see if the server_core is running
args:
delay: will cycle till core is up.
timeout: number of seconds to wait | [
"checks",
"to",
"see",
"if",
"the",
"server_core",
"is",
"running"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L221-L267 |
KnowledgeLinks/rdfframework | rdfframework/framework.py | RdfFramework.load_rml | def load_rml(self, rml_name):
""" loads an rml mapping into memory
args:
rml_name(str): the name of the rml file
"""
conn = CFG.rml_tstore
cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name)
if not os.path.exists(cache_path):
res... | python | def load_rml(self, rml_name):
""" loads an rml mapping into memory
args:
rml_name(str): the name of the rml file
"""
conn = CFG.rml_tstore
cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name)
if not os.path.exists(cache_path):
res... | [
"def",
"load_rml",
"(",
"self",
",",
"rml_name",
")",
":",
"conn",
"=",
"CFG",
".",
"rml_tstore",
"cache_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CFG",
".",
"CACHE_DATA_PATH",
",",
"'rml_files'",
",",
"rml_name",
")",
"if",
"not",
"os",
".",
... | loads an rml mapping into memory
args:
rml_name(str): the name of the rml file | [
"loads",
"an",
"rml",
"mapping",
"into",
"memory"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L87-L103 |
KnowledgeLinks/rdfframework | rdfframework/framework.py | RdfFramework.get_rml | def get_rml(self, rml_name):
""" returns the rml mapping RdfDataset
rml_name(str): Name of the rml mapping to retrieve
"""
try:
return getattr(self, rml_name)
except AttributeError:
return self.load_rml(rml_name) | python | def get_rml(self, rml_name):
""" returns the rml mapping RdfDataset
rml_name(str): Name of the rml mapping to retrieve
"""
try:
return getattr(self, rml_name)
except AttributeError:
return self.load_rml(rml_name) | [
"def",
"get_rml",
"(",
"self",
",",
"rml_name",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
",",
"rml_name",
")",
"except",
"AttributeError",
":",
"return",
"self",
".",
"load_rml",
"(",
"rml_name",
")"
] | returns the rml mapping RdfDataset
rml_name(str): Name of the rml mapping to retrieve | [
"returns",
"the",
"rml",
"mapping",
"RdfDataset"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L105-L114 |
KnowledgeLinks/rdfframework | rdfframework/framework.py | RdfFramework._load_data | def _load_data(self, reset=False):
''' loads the RDF/turtle application data to the triplestore
args:
reset(bool): True will delete the definition dataset and reload
all of the datafiles.
'''
log = logging.getLogger("%s.%s" % (self.log_name,
... | python | def _load_data(self, reset=False):
''' loads the RDF/turtle application data to the triplestore
args:
reset(bool): True will delete the definition dataset and reload
all of the datafiles.
'''
log = logging.getLogger("%s.%s" % (self.log_name,
... | [
"def",
"_load_data",
"(",
"self",
",",
"reset",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"log_name",
",",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
")",
")",
... | loads the RDF/turtle application data to the triplestore
args:
reset(bool): True will delete the definition dataset and reload
all of the datafiles. | [
"loads",
"the",
"RDF",
"/",
"turtle",
"application",
"data",
"to",
"the",
"triplestore"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L133-L169 |
KnowledgeLinks/rdfframework | rdfframework/framework.py | RdfFramework._set_data_filelist | def _set_data_filelist(self,
start_path,
attr_name,
conn,
file_exts=[],
dir_filter=set()):
''' does a directory search for data files '''
def filter_path(filter_terms, ... | python | def _set_data_filelist(self,
start_path,
attr_name,
conn,
file_exts=[],
dir_filter=set()):
''' does a directory search for data files '''
def filter_path(filter_terms, ... | [
"def",
"_set_data_filelist",
"(",
"self",
",",
"start_path",
",",
"attr_name",
",",
"conn",
",",
"file_exts",
"=",
"[",
"]",
",",
"dir_filter",
"=",
"set",
"(",
")",
")",
":",
"def",
"filter_path",
"(",
"filter_terms",
",",
"dir_path",
")",
":",
"\"\"\" ... | does a directory search for data files | [
"does",
"a",
"directory",
"search",
"for",
"data",
"files"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L171-L219 |
devricks/soft_drf | soft_drf/auth/authentication.py | BaseJSONWebTokenAuthentication.authenticate | def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.
"""
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
return None
... | python | def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.
"""
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
return None
... | [
"def",
"authenticate",
"(",
"self",
",",
"request",
")",
":",
"jwt_value",
"=",
"self",
".",
"get_jwt_value",
"(",
"request",
")",
"if",
"jwt_value",
"is",
"None",
":",
"return",
"None",
"try",
":",
"payload",
"=",
"jwt_decode_handler",
"(",
"jwt_value",
"... | Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`. | [
"Returns",
"a",
"two",
"-",
"tuple",
"of",
"User",
"and",
"token",
"if",
"a",
"valid",
"signature",
"has",
"been",
"supplied",
"using",
"JWT",
"-",
"based",
"authentication",
".",
"Otherwise",
"returns",
"None",
"."
] | train | https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/auth/authentication.py#L29-L51 |
devricks/soft_drf | soft_drf/auth/authentication.py | BaseJSONWebTokenAuthentication.authenticate_credentials | def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's user id and email.
"""
User = get_user_model() # noqa
username = jwt_get_username_from_payload_handler(payload)
if not username:
msg = _('Invalid payload.')
... | python | def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's user id and email.
"""
User = get_user_model() # noqa
username = jwt_get_username_from_payload_handler(payload)
if not username:
msg = _('Invalid payload.')
... | [
"def",
"authenticate_credentials",
"(",
"self",
",",
"payload",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"# noqa",
"username",
"=",
"jwt_get_username_from_payload_handler",
"(",
"payload",
")",
"if",
"not",
"username",
":",
"msg",
"=",
"_",
"(",
"'In... | Returns an active user that matches the payload's user id and email. | [
"Returns",
"an",
"active",
"user",
"that",
"matches",
"the",
"payload",
"s",
"user",
"id",
"and",
"email",
"."
] | train | https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/auth/authentication.py#L53-L70 |
rorr73/LifeSOSpy | lifesospy/util.py | to_ascii_hex | def to_ascii_hex(value: int, digits: int) -> str:
"""Converts an int value to ASCII hex, as used by LifeSOS.
Unlike regular hex, it uses the first 6 characters that follow
numerics on the ASCII table instead of A - F."""
if digits < 1:
return ''
text = ''
for _ in range(0, digits):... | python | def to_ascii_hex(value: int, digits: int) -> str:
"""Converts an int value to ASCII hex, as used by LifeSOS.
Unlike regular hex, it uses the first 6 characters that follow
numerics on the ASCII table instead of A - F."""
if digits < 1:
return ''
text = ''
for _ in range(0, digits):... | [
"def",
"to_ascii_hex",
"(",
"value",
":",
"int",
",",
"digits",
":",
"int",
")",
"->",
"str",
":",
"if",
"digits",
"<",
"1",
":",
"return",
"''",
"text",
"=",
"''",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"digits",
")",
":",
"text",
"=",
"chr... | Converts an int value to ASCII hex, as used by LifeSOS.
Unlike regular hex, it uses the first 6 characters that follow
numerics on the ASCII table instead of A - F. | [
"Converts",
"an",
"int",
"value",
"to",
"ASCII",
"hex",
"as",
"used",
"by",
"LifeSOS",
".",
"Unlike",
"regular",
"hex",
"it",
"uses",
"the",
"first",
"6",
"characters",
"that",
"follow",
"numerics",
"on",
"the",
"ASCII",
"table",
"instead",
"of",
"A",
"-... | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L17-L27 |
rorr73/LifeSOSpy | lifesospy/util.py | from_ascii_hex | def from_ascii_hex(text: str) -> int:
"""Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
Regular hex: 012... | python | def from_ascii_hex(text: str) -> int:
"""Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
Regular hex: 012... | [
"def",
"from_ascii_hex",
"(",
"text",
":",
"str",
")",
"->",
"int",
":",
"value",
"=",
"0",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"text",
")",
")",
":",
"char_ord",
"=",
"ord",
"(",
"text",
"[",
"index",
":",
"index",
"+",
"... | Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
Regular hex: 0123456789abcdef
ASCII hex: 0123456789:... | [
"Converts",
"to",
"an",
"int",
"value",
"from",
"both",
"ASCII",
"and",
"regular",
"hex",
".",
"The",
"format",
"used",
"appears",
"to",
"vary",
"based",
"on",
"whether",
"the",
"command",
"was",
"to",
"get",
"an",
"existing",
"value",
"(",
"regular",
"h... | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L30-L49 |
rorr73/LifeSOSpy | lifesospy/util.py | serializable | def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any:
"""
Ensures the specified object is serializable, converting if necessary.
:param obj: the object to use.
:param on_filter: optional function that can be used to filter which
properties on the object ... | python | def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any:
"""
Ensures the specified object is serializable, converting if necessary.
:param obj: the object to use.
:param on_filter: optional function that can be used to filter which
properties on the object ... | [
"def",
"serializable",
"(",
"obj",
":",
"Any",
",",
"on_filter",
":",
"Callable",
"[",
"[",
"Any",
",",
"str",
"]",
",",
"bool",
"]",
"=",
"None",
")",
"->",
"Any",
":",
"# Will be called recursively when object has children",
"def",
"_serializable",
"(",
"p... | Ensures the specified object is serializable, converting if necessary.
:param obj: the object to use.
:param on_filter: optional function that can be used to filter which
properties on the object will be included.
:return value representing the object, which is serializable. | [
"Ensures",
"the",
"specified",
"object",
"is",
"serializable",
"converting",
"if",
"necessary",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L61-L124 |
rorr73/LifeSOSpy | lifesospy/util.py | encode_value_using_ma | def encode_value_using_ma(message_attribute: int, value: Optional[Union[int, float]]) -> int:
"""Encode special sensor value using the message attribute."""
if message_attribute == MA_TX3AC_100A:
# TX-3AC in 100A mode; use value as-is, with 0xFE indicating null
if value is None:
retu... | python | def encode_value_using_ma(message_attribute: int, value: Optional[Union[int, float]]) -> int:
"""Encode special sensor value using the message attribute."""
if message_attribute == MA_TX3AC_100A:
# TX-3AC in 100A mode; use value as-is, with 0xFE indicating null
if value is None:
retu... | [
"def",
"encode_value_using_ma",
"(",
"message_attribute",
":",
"int",
",",
"value",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"float",
"]",
"]",
")",
"->",
"int",
":",
"if",
"message_attribute",
"==",
"MA_TX3AC_100A",
":",
"# TX-3AC in 100A mode; use value... | Encode special sensor value using the message attribute. | [
"Encode",
"special",
"sensor",
"value",
"using",
"the",
"message",
"attribute",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L149-L167 |
jmgilman/Neolib | neolib/pyamf/xml.py | set_default_interface | def set_default_interface(etree):
"""
Sets the default interface that PyAMF will use to deal with XML entities
(both objects and blobs).
"""
global types, ET, modules
t = _get_etree_type(etree)
_types = set(types or [])
_types.update([t])
types = tuple(_types)
modules[t] = et... | python | def set_default_interface(etree):
"""
Sets the default interface that PyAMF will use to deal with XML entities
(both objects and blobs).
"""
global types, ET, modules
t = _get_etree_type(etree)
_types = set(types or [])
_types.update([t])
types = tuple(_types)
modules[t] = et... | [
"def",
"set_default_interface",
"(",
"etree",
")",
":",
"global",
"types",
",",
"ET",
",",
"modules",
"t",
"=",
"_get_etree_type",
"(",
"etree",
")",
"_types",
"=",
"set",
"(",
"types",
"or",
"[",
"]",
")",
"_types",
".",
"update",
"(",
"[",
"t",
"]"... | Sets the default interface that PyAMF will use to deal with XML entities
(both objects and blobs). | [
"Sets",
"the",
"default",
"interface",
"that",
"PyAMF",
"will",
"use",
"to",
"deal",
"with",
"XML",
"entities",
"(",
"both",
"objects",
"and",
"blobs",
")",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/xml.py#L30-L48 |
jmgilman/Neolib | neolib/pyamf/xml.py | find_libs | def find_libs():
"""
Run through L{ETREE_MODULES} and find C{ElementTree} implementations so
that any type can be encoded.
We work through the C implementations first, then the pure Python versions.
The downside to this is that B{all} libraries will be imported but I{only}
one is ever used. The... | python | def find_libs():
"""
Run through L{ETREE_MODULES} and find C{ElementTree} implementations so
that any type can be encoded.
We work through the C implementations first, then the pure Python versions.
The downside to this is that B{all} libraries will be imported but I{only}
one is ever used. The... | [
"def",
"find_libs",
"(",
")",
":",
"from",
"pyamf",
".",
"util",
"import",
"get_module",
"types",
"=",
"[",
"]",
"mapping",
"=",
"{",
"}",
"for",
"mod",
"in",
"ETREE_MODULES",
":",
"try",
":",
"etree",
"=",
"get_module",
"(",
"mod",
")",
"except",
"I... | Run through L{ETREE_MODULES} and find C{ElementTree} implementations so
that any type can be encoded.
We work through the C implementations first, then the pure Python versions.
The downside to this is that B{all} libraries will be imported but I{only}
one is ever used. The libs are small (relatively) ... | [
"Run",
"through",
"L",
"{",
"ETREE_MODULES",
"}",
"and",
"find",
"C",
"{",
"ElementTree",
"}",
"implementations",
"so",
"that",
"any",
"type",
"can",
"be",
"encoded",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/xml.py#L51-L77 |
jmgilman/Neolib | neolib/pyamf/xml.py | tostring | def tostring(element, *args, **kwargs):
"""
Helper func to provide easy access to the (possibly) moving target that is
C{ET}.
"""
global modules
_bootstrap()
t = _get_type(element)
etree = modules.get(t, None)
if not etree:
raise RuntimeError('Unable to find the etree impl... | python | def tostring(element, *args, **kwargs):
"""
Helper func to provide easy access to the (possibly) moving target that is
C{ET}.
"""
global modules
_bootstrap()
t = _get_type(element)
etree = modules.get(t, None)
if not etree:
raise RuntimeError('Unable to find the etree impl... | [
"def",
"tostring",
"(",
"element",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"modules",
"_bootstrap",
"(",
")",
"t",
"=",
"_get_type",
"(",
"element",
")",
"etree",
"=",
"modules",
".",
"get",
"(",
"t",
",",
"None",
")",
"if",
... | Helper func to provide easy access to the (possibly) moving target that is
C{ET}. | [
"Helper",
"func",
"to",
"provide",
"easy",
"access",
"to",
"the",
"(",
"possibly",
")",
"moving",
"target",
"that",
"is",
"C",
"{",
"ET",
"}",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/xml.py#L137-L153 |
openpermissions/perch | perch/validators.py | partial_schema | def partial_schema(schema, filtered_fields):
"""
Validator for part of a schema, ignoring some fields
:param schema: the Schema
:param filtered_fields: fields to filter out
"""
return Schema({
k: v for k, v in schema.schema.items()
if getattr(k, 'schema', k) not in filtered_fiel... | python | def partial_schema(schema, filtered_fields):
"""
Validator for part of a schema, ignoring some fields
:param schema: the Schema
:param filtered_fields: fields to filter out
"""
return Schema({
k: v for k, v in schema.schema.items()
if getattr(k, 'schema', k) not in filtered_fiel... | [
"def",
"partial_schema",
"(",
"schema",
",",
"filtered_fields",
")",
":",
"return",
"Schema",
"(",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"schema",
".",
"schema",
".",
"items",
"(",
")",
"if",
"getattr",
"(",
"k",
",",
"'schema'",
",",
"k"... | Validator for part of a schema, ignoring some fields
:param schema: the Schema
:param filtered_fields: fields to filter out | [
"Validator",
"for",
"part",
"of",
"a",
"schema",
"ignoring",
"some",
"fields"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L53-L63 |
openpermissions/perch | perch/validators.py | validate_url | def validate_url(url):
"""Validate URL is valid
NOTE: only support http & https
"""
schemes = ['http', 'https']
netloc_re = re.compile(
r'^'
r'(?:\S+(?::\S*)?@)?' # user:pass auth
r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])'
r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]... | python | def validate_url(url):
"""Validate URL is valid
NOTE: only support http & https
"""
schemes = ['http', 'https']
netloc_re = re.compile(
r'^'
r'(?:\S+(?::\S*)?@)?' # user:pass auth
r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])'
r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]... | [
"def",
"validate_url",
"(",
"url",
")",
":",
"schemes",
"=",
"[",
"'http'",
",",
"'https'",
"]",
"netloc_re",
"=",
"re",
".",
"compile",
"(",
"r'^'",
"r'(?:\\S+(?::\\S*)?@)?'",
"# user:pass auth",
"r'(?:[a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])'",
"r'(?:\\.(?:[a-z0-9]... | Validate URL is valid
NOTE: only support http & https | [
"Validate",
"URL",
"is",
"valid"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L83-L109 |
openpermissions/perch | perch/validators.py | validate_reference_links | def validate_reference_links(reference_links):
"""
Vaidate reference links data structure
Expected data structure:
{
"links": {
id_type1: url1,
id_type2: url2
},
"redirect_id_type": id_type1 | id1_type2
}
where links i... | python | def validate_reference_links(reference_links):
"""
Vaidate reference links data structure
Expected data structure:
{
"links": {
id_type1: url1,
id_type2: url2
},
"redirect_id_type": id_type1 | id1_type2
}
where links i... | [
"def",
"validate_reference_links",
"(",
"reference_links",
")",
":",
"allowed_keys",
"=",
"[",
"'links'",
",",
"'redirect_id_type'",
"]",
"if",
"not",
"isinstance",
"(",
"reference_links",
",",
"dict",
")",
":",
"raise",
"Invalid",
"(",
"'Expected reference_links to... | Vaidate reference links data structure
Expected data structure:
{
"links": {
id_type1: url1,
id_type2: url2
},
"redirect_id_type": id_type1 | id1_type2
}
where links is an optional key but must be a dictionary with id types to... | [
"Vaidate",
"reference",
"links",
"data",
"structure"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L112-L150 |
openpermissions/perch | perch/validators.py | _validate_state | def _validate_state(state, valid_states):
"""Validate a state string"""
if state in State:
return state.name
elif state in valid_states:
return state
else:
raise Invalid('Invalid state') | python | def _validate_state(state, valid_states):
"""Validate a state string"""
if state in State:
return state.name
elif state in valid_states:
return state
else:
raise Invalid('Invalid state') | [
"def",
"_validate_state",
"(",
"state",
",",
"valid_states",
")",
":",
"if",
"state",
"in",
"State",
":",
"return",
"state",
".",
"name",
"elif",
"state",
"in",
"valid_states",
":",
"return",
"state",
"else",
":",
"raise",
"Invalid",
"(",
"'Invalid state'",
... | Validate a state string | [
"Validate",
"a",
"state",
"string"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L165-L172 |
blubberdiblub/eztemplate | eztemplate/__main__.py | is_filelike | def is_filelike(ob):
"""Check for filelikeness of an object.
Needed to distinguish it from file names.
Returns true if it has a read or a write method.
"""
if hasattr(ob, 'read') and callable(ob.read):
return True
if hasattr(ob, 'write') and callable(ob.write):
return True
... | python | def is_filelike(ob):
"""Check for filelikeness of an object.
Needed to distinguish it from file names.
Returns true if it has a read or a write method.
"""
if hasattr(ob, 'read') and callable(ob.read):
return True
if hasattr(ob, 'write') and callable(ob.write):
return True
... | [
"def",
"is_filelike",
"(",
"ob",
")",
":",
"if",
"hasattr",
"(",
"ob",
",",
"'read'",
")",
"and",
"callable",
"(",
"ob",
".",
"read",
")",
":",
"return",
"True",
"if",
"hasattr",
"(",
"ob",
",",
"'write'",
")",
"and",
"callable",
"(",
"ob",
".",
... | Check for filelikeness of an object.
Needed to distinguish it from file names.
Returns true if it has a read or a write method. | [
"Check",
"for",
"filelikeness",
"of",
"an",
"object",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L18-L30 |
blubberdiblub/eztemplate | eztemplate/__main__.py | parse_args | def parse_args(args=None):
"""Parse command line arguments."""
# The argparse module provides a nice abstraction for argument parsing.
# It automatically builds up the help text, too.
parser = argparse.ArgumentParser(
prog=__package__,
description='Make substitutions in text file... | python | def parse_args(args=None):
"""Parse command line arguments."""
# The argparse module provides a nice abstraction for argument parsing.
# It automatically builds up the help text, too.
parser = argparse.ArgumentParser(
prog=__package__,
description='Make substitutions in text file... | [
"def",
"parse_args",
"(",
"args",
"=",
"None",
")",
":",
"# The argparse module provides a nice abstraction for argument parsing.",
"# It automatically builds up the help text, too.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"__package__",
",",
"des... | Parse command line arguments. | [
"Parse",
"command",
"line",
"arguments",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L43-L217 |
blubberdiblub/eztemplate | eztemplate/__main__.py | dump_engines | def dump_engines(target=sys.stderr):
"""Print successfully imported templating engines."""
print("Available templating engines:", file=target)
width = max(len(engine) for engine in engines.engines)
for handle, engine in sorted(engines.engines.items()):
description = engine.__doc__.split('\n', 0... | python | def dump_engines(target=sys.stderr):
"""Print successfully imported templating engines."""
print("Available templating engines:", file=target)
width = max(len(engine) for engine in engines.engines)
for handle, engine in sorted(engines.engines.items()):
description = engine.__doc__.split('\n', 0... | [
"def",
"dump_engines",
"(",
"target",
"=",
"sys",
".",
"stderr",
")",
":",
"print",
"(",
"\"Available templating engines:\"",
",",
"file",
"=",
"target",
")",
"width",
"=",
"max",
"(",
"len",
"(",
"engine",
")",
"for",
"engine",
"in",
"engines",
".",
"en... | Print successfully imported templating engines. | [
"Print",
"successfully",
"imported",
"templating",
"engines",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L220-L227 |
blubberdiblub/eztemplate | eztemplate/__main__.py | check_engine | def check_engine(handle):
"""Check availability of requested template engine."""
if handle == 'help':
dump_engines()
sys.exit(0)
if handle not in engines.engines:
print('Engine "%s" is not available.' % (handle,), file=sys.stderr)
sys.exit(1) | python | def check_engine(handle):
"""Check availability of requested template engine."""
if handle == 'help':
dump_engines()
sys.exit(0)
if handle not in engines.engines:
print('Engine "%s" is not available.' % (handle,), file=sys.stderr)
sys.exit(1) | [
"def",
"check_engine",
"(",
"handle",
")",
":",
"if",
"handle",
"==",
"'help'",
":",
"dump_engines",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"if",
"handle",
"not",
"in",
"engines",
".",
"engines",
":",
"print",
"(",
"'Engine \"%s\" is not available.'"... | Check availability of requested template engine. | [
"Check",
"availability",
"of",
"requested",
"template",
"engine",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L230-L238 |
blubberdiblub/eztemplate | eztemplate/__main__.py | make_mapping | def make_mapping(args):
"""Make a mapping from the name=value pairs."""
mapping = {}
if args:
for arg in args:
name_value = arg.split('=', 1)
mapping[name_value[0]] = (name_value[1]
if len(name_value) > 1
... | python | def make_mapping(args):
"""Make a mapping from the name=value pairs."""
mapping = {}
if args:
for arg in args:
name_value = arg.split('=', 1)
mapping[name_value[0]] = (name_value[1]
if len(name_value) > 1
... | [
"def",
"make_mapping",
"(",
"args",
")",
":",
"mapping",
"=",
"{",
"}",
"if",
"args",
":",
"for",
"arg",
"in",
"args",
":",
"name_value",
"=",
"arg",
".",
"split",
"(",
"'='",
",",
"1",
")",
"mapping",
"[",
"name_value",
"[",
"0",
"]",
"]",
"=",
... | Make a mapping from the name=value pairs. | [
"Make",
"a",
"mapping",
"from",
"the",
"name",
"=",
"value",
"pairs",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L241-L252 |
blubberdiblub/eztemplate | eztemplate/__main__.py | make_path_properties | def make_path_properties(file_or_path, prefix=''):
"""Build useful properties from a file path."""
is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr)
if is_std:
path = '-'
elif is_filelike(file_or_path):
try:
path = str(file_or_path.name)
except AttributeEr... | python | def make_path_properties(file_or_path, prefix=''):
"""Build useful properties from a file path."""
is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr)
if is_std:
path = '-'
elif is_filelike(file_or_path):
try:
path = str(file_or_path.name)
except AttributeEr... | [
"def",
"make_path_properties",
"(",
"file_or_path",
",",
"prefix",
"=",
"''",
")",
":",
"is_std",
"=",
"file_or_path",
"in",
"(",
"sys",
".",
"stdin",
",",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
")",
"if",
"is_std",
":",
"path",
"=",
"'-'",
... | Build useful properties from a file path. | [
"Build",
"useful",
"properties",
"from",
"a",
"file",
"path",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L255-L305 |
blubberdiblub/eztemplate | eztemplate/__main__.py | constant_outfile_iterator | def constant_outfile_iterator(outfiles, infiles, arggroups):
"""Iterate over all output files."""
assert len(infiles) == 1
assert len(arggroups) == 1
return ((outfile, infiles[0], arggroups[0]) for outfile in outfiles) | python | def constant_outfile_iterator(outfiles, infiles, arggroups):
"""Iterate over all output files."""
assert len(infiles) == 1
assert len(arggroups) == 1
return ((outfile, infiles[0], arggroups[0]) for outfile in outfiles) | [
"def",
"constant_outfile_iterator",
"(",
"outfiles",
",",
"infiles",
",",
"arggroups",
")",
":",
"assert",
"len",
"(",
"infiles",
")",
"==",
"1",
"assert",
"len",
"(",
"arggroups",
")",
"==",
"1",
"return",
"(",
"(",
"outfile",
",",
"infiles",
"[",
"0",
... | Iterate over all output files. | [
"Iterate",
"over",
"all",
"output",
"files",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L308-L313 |
blubberdiblub/eztemplate | eztemplate/__main__.py | variable_outfile_iterator | def variable_outfile_iterator(outfiles, infiles, arggroups, engine):
"""Iterate over variable output file name template."""
assert len(outfiles) == 1
template = engine(outfiles[0], tolerant=False)
for infile in infiles:
properties = make_path_properties(infile, prefix='')
for arggroup... | python | def variable_outfile_iterator(outfiles, infiles, arggroups, engine):
"""Iterate over variable output file name template."""
assert len(outfiles) == 1
template = engine(outfiles[0], tolerant=False)
for infile in infiles:
properties = make_path_properties(infile, prefix='')
for arggroup... | [
"def",
"variable_outfile_iterator",
"(",
"outfiles",
",",
"infiles",
",",
"arggroups",
",",
"engine",
")",
":",
"assert",
"len",
"(",
"outfiles",
")",
"==",
"1",
"template",
"=",
"engine",
"(",
"outfiles",
"[",
"0",
"]",
",",
"tolerant",
"=",
"False",
")... | Iterate over variable output file name template. | [
"Iterate",
"over",
"variable",
"output",
"file",
"name",
"template",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L316-L327 |
blubberdiblub/eztemplate | eztemplate/__main__.py | process_combinations | def process_combinations(combinations, engine,
tolerant=False,
read_old=False,
delete_empty=False,
):
"""Process outfile-infile-arggroup combinations."""
outfiles = set()
templatereader = CachedTemplateReade... | python | def process_combinations(combinations, engine,
tolerant=False,
read_old=False,
delete_empty=False,
):
"""Process outfile-infile-arggroup combinations."""
outfiles = set()
templatereader = CachedTemplateReade... | [
"def",
"process_combinations",
"(",
"combinations",
",",
"engine",
",",
"tolerant",
"=",
"False",
",",
"read_old",
"=",
"False",
",",
"delete_empty",
"=",
"False",
",",
")",
":",
"outfiles",
"=",
"set",
"(",
")",
"templatereader",
"=",
"CachedTemplateReader",
... | Process outfile-infile-arggroup combinations. | [
"Process",
"outfile",
"-",
"infile",
"-",
"arggroup",
"combinations",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L361-L400 |
blubberdiblub/eztemplate | eztemplate/__main__.py | perform_templating | def perform_templating(args):
"""Perform templating according to the given arguments."""
engine = engines.engines[args.engine]
if args.vary:
it = variable_outfile_iterator(args.outfiles,
args.infiles,
args.args,
... | python | def perform_templating(args):
"""Perform templating according to the given arguments."""
engine = engines.engines[args.engine]
if args.vary:
it = variable_outfile_iterator(args.outfiles,
args.infiles,
args.args,
... | [
"def",
"perform_templating",
"(",
"args",
")",
":",
"engine",
"=",
"engines",
".",
"engines",
"[",
"args",
".",
"engine",
"]",
"if",
"args",
".",
"vary",
":",
"it",
"=",
"variable_outfile_iterator",
"(",
"args",
".",
"outfiles",
",",
"args",
".",
"infile... | Perform templating according to the given arguments. | [
"Perform",
"templating",
"according",
"to",
"the",
"given",
"arguments",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L403-L421 |
blubberdiblub/eztemplate | eztemplate/__main__.py | CachedTemplateReader.read | def read(self, file_or_path):
"""Read template from cache or file."""
if file_or_path in self._cached_templates:
return self._cached_templates[file_or_path]
if is_filelike(file_or_path):
template = file_or_path.read()
dirname = None
else:
... | python | def read(self, file_or_path):
"""Read template from cache or file."""
if file_or_path in self._cached_templates:
return self._cached_templates[file_or_path]
if is_filelike(file_or_path):
template = file_or_path.read()
dirname = None
else:
... | [
"def",
"read",
"(",
"self",
",",
"file_or_path",
")",
":",
"if",
"file_or_path",
"in",
"self",
".",
"_cached_templates",
":",
"return",
"self",
".",
"_cached_templates",
"[",
"file_or_path",
"]",
"if",
"is_filelike",
"(",
"file_or_path",
")",
":",
"template",
... | Read template from cache or file. | [
"Read",
"template",
"from",
"cache",
"or",
"file",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L340-L358 |
nws-cip/zenconf | examples/config.py | get_config | def get_config(cli_args=None, config_path=None):
"""
Perform standard setup - get the merged config
:param cli_args dict: A dictionary of CLI arguments
:param config_path string: Path to the config file to load
:return dict: A dictionary of config values drawn from different sources
"""
co... | python | def get_config(cli_args=None, config_path=None):
"""
Perform standard setup - get the merged config
:param cli_args dict: A dictionary of CLI arguments
:param config_path string: Path to the config file to load
:return dict: A dictionary of config values drawn from different sources
"""
co... | [
"def",
"get_config",
"(",
"cli_args",
"=",
"None",
",",
"config_path",
"=",
"None",
")",
":",
"config",
"=",
"Config",
"(",
"app_name",
"=",
"\"MYAPP\"",
",",
"cli_args",
"=",
"cli_args",
",",
"config_path",
"=",
"config_path",
")",
"config_dict",
"=",
"co... | Perform standard setup - get the merged config
:param cli_args dict: A dictionary of CLI arguments
:param config_path string: Path to the config file to load
:return dict: A dictionary of config values drawn from different sources | [
"Perform",
"standard",
"setup",
"-",
"get",
"the",
"merged",
"config"
] | train | https://github.com/nws-cip/zenconf/blob/fc96706468c0741fb1b54b2eeb9f9225737e3e36/examples/config.py#L101-L114 |
OldhamMade/PySO8601 | PySO8601/intervals.py | parse_interval | def parse_interval(interval):
"""
Attepmt to parse an ISO8601 formatted ``interval``.
Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta``
objects, order dependent on ``interval``.
"""
a, b = str(interval).upper().strip().split('/')
if a[0] is 'P' and b[0] is 'P':
ra... | python | def parse_interval(interval):
"""
Attepmt to parse an ISO8601 formatted ``interval``.
Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta``
objects, order dependent on ``interval``.
"""
a, b = str(interval).upper().strip().split('/')
if a[0] is 'P' and b[0] is 'P':
ra... | [
"def",
"parse_interval",
"(",
"interval",
")",
":",
"a",
",",
"b",
"=",
"str",
"(",
"interval",
")",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"a",
"[",
"0",
"]",
"is",
"'P'",
"and",
"b",
"[",
"0",
... | Attepmt to parse an ISO8601 formatted ``interval``.
Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta``
objects, order dependent on ``interval``. | [
"Attepmt",
"to",
"parse",
"an",
"ISO8601",
"formatted",
"interval",
"."
] | train | https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/intervals.py#L6-L31 |
hitchtest/hitchserve | hitchserve/hitch_service.py | Subcommand.run | def run(self, shell=False, ignore_errors=False, stdin=False, check_output=False):
"""Run subcommand.
Args:
shell (Optional[bool]): Run command using shell (default False)
ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default... | python | def run(self, shell=False, ignore_errors=False, stdin=False, check_output=False):
"""Run subcommand.
Args:
shell (Optional[bool]): Run command using shell (default False)
ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default... | [
"def",
"run",
"(",
"self",
",",
"shell",
"=",
"False",
",",
"ignore_errors",
"=",
"False",
",",
"stdin",
"=",
"False",
",",
"check_output",
"=",
"False",
")",
":",
"previous_directory",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"se... | Run subcommand.
Args:
shell (Optional[bool]): Run command using shell (default False)
ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default False)
stdin (Optional[bool]): Plug input from stdin when running command (defau... | [
"Run",
"subcommand",
"."
] | train | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/hitch_service.py#L52-L88 |
hitchtest/hitchserve | hitchserve/hitch_service.py | Service.env_vars | def env_vars(self):
"""dict: All environment variables fed to the service."""
if not self.no_libfaketime:
faketime_filename = self.service_group.hitch_dir.faketime()
env_vars = dict(os.environ)
env_vars.update(self._env_vars)
env_vars.update(faketime.get_... | python | def env_vars(self):
"""dict: All environment variables fed to the service."""
if not self.no_libfaketime:
faketime_filename = self.service_group.hitch_dir.faketime()
env_vars = dict(os.environ)
env_vars.update(self._env_vars)
env_vars.update(faketime.get_... | [
"def",
"env_vars",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"no_libfaketime",
":",
"faketime_filename",
"=",
"self",
".",
"service_group",
".",
"hitch_dir",
".",
"faketime",
"(",
")",
"env_vars",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"env_... | dict: All environment variables fed to the service. | [
"dict",
":",
"All",
"environment",
"variables",
"fed",
"to",
"the",
"service",
"."
] | train | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/hitch_service.py#L193-L204 |
hitchtest/hitchserve | hitchserve/hitch_service.py | Service.directory | def directory(self):
"""str: Directory that the service is run in."""
if self._directory is None:
return self.service_group.hitch_dir.hitch_dir
else:
return self._directory | python | def directory(self):
"""str: Directory that the service is run in."""
if self._directory is None:
return self.service_group.hitch_dir.hitch_dir
else:
return self._directory | [
"def",
"directory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_directory",
"is",
"None",
":",
"return",
"self",
".",
"service_group",
".",
"hitch_dir",
".",
"hitch_dir",
"else",
":",
"return",
"self",
".",
"_directory"
] | str: Directory that the service is run in. | [
"str",
":",
"Directory",
"that",
"the",
"service",
"is",
"run",
"in",
"."
] | train | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/hitch_service.py#L211-L216 |
hitchtest/hitchserve | hitchserve/hitch_service.py | Service.subcommand | def subcommand(self, *args):
"""Get subcommand acting on a service. Subcommand will run in service directory
and with the environment variables used to run the service itself.
Args:
*args: Arguments to run command (e.g. "redis-cli", "-n", "1")
Returns:
Subcom... | python | def subcommand(self, *args):
"""Get subcommand acting on a service. Subcommand will run in service directory
and with the environment variables used to run the service itself.
Args:
*args: Arguments to run command (e.g. "redis-cli", "-n", "1")
Returns:
Subcom... | [
"def",
"subcommand",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"Subcommand",
"(",
"*",
"args",
",",
"directory",
"=",
"self",
".",
"directory",
",",
"env_vars",
"=",
"self",
".",
"env_vars",
")"
] | Get subcommand acting on a service. Subcommand will run in service directory
and with the environment variables used to run the service itself.
Args:
*args: Arguments to run command (e.g. "redis-cli", "-n", "1")
Returns:
Subcommand object. | [
"Get",
"subcommand",
"acting",
"on",
"a",
"service",
".",
"Subcommand",
"will",
"run",
"in",
"service",
"directory",
"and",
"with",
"the",
"environment",
"variables",
"used",
"to",
"run",
"the",
"service",
"itself",
"."
] | train | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/hitch_service.py#L237-L247 |
pydsigner/taskit | taskit/resync.py | Mediator._wait | def _wait(self, timeout):
"""
Based upon an extract from threading.Condition().wait(). Immediately
tries to acquire the lock, and then sleeps for a period of time (going
1/2ms..1ms..2ms..4ms...50ms..50ms), repeating until the lock is
acquired or the timeout limit is reached.
... | python | def _wait(self, timeout):
"""
Based upon an extract from threading.Condition().wait(). Immediately
tries to acquire the lock, and then sleeps for a period of time (going
1/2ms..1ms..2ms..4ms...50ms..50ms), repeating until the lock is
acquired or the timeout limit is reached.
... | [
"def",
"_wait",
"(",
"self",
",",
"timeout",
")",
":",
"endtime",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"# Initial delay of .5ms",
"delay",
"=",
"0.0005",
"while",
"1",
":",
"if",
"self",
".",
"_lock",
".",
"acquire",
"(",
"0",
")",
":"... | Based upon an extract from threading.Condition().wait(). Immediately
tries to acquire the lock, and then sleeps for a period of time (going
1/2ms..1ms..2ms..4ms...50ms..50ms), repeating until the lock is
acquired or the timeout limit is reached. | [
"Based",
"upon",
"an",
"extract",
"from",
"threading",
".",
"Condition",
"()",
".",
"wait",
"()",
".",
"Immediately",
"tries",
"to",
"acquire",
"the",
"lock",
"and",
"then",
"sleeps",
"for",
"a",
"period",
"of",
"time",
"(",
"going",
"1",
"/",
"2ms",
"... | train | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/resync.py#L93-L115 |
pydsigner/taskit | taskit/resync.py | Mediator.set_result | def set_result(self, res):
"""
The worker thread should call this if it was successful. Unlike normal
functions, which will return None if execution is allowed to fall off
the end, either set_result() or self_error() must be called, or the
the get()ing side will hang.
... | python | def set_result(self, res):
"""
The worker thread should call this if it was successful. Unlike normal
functions, which will return None if execution is allowed to fall off
the end, either set_result() or self_error() must be called, or the
the get()ing side will hang.
... | [
"def",
"set_result",
"(",
"self",
",",
"res",
")",
":",
"self",
".",
"result",
"=",
"(",
"True",
",",
"res",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | The worker thread should call this if it was successful. Unlike normal
functions, which will return None if execution is allowed to fall off
the end, either set_result() or self_error() must be called, or the
the get()ing side will hang. | [
"The",
"worker",
"thread",
"should",
"call",
"this",
"if",
"it",
"was",
"successful",
".",
"Unlike",
"normal",
"functions",
"which",
"will",
"return",
"None",
"if",
"execution",
"is",
"allowed",
"to",
"fall",
"off",
"the",
"end",
"either",
"set_result",
"()"... | train | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/resync.py#L118-L126 |
pydsigner/taskit | taskit/resync.py | Mediator.set_error | def set_error(self, e):
"""
Rather than allowing unmanaged exceptions to explode, or raising errors
within thread, the worker thread should call this function with an
error class or instance.
"""
self.result = (False, e)
self._lock.release() | python | def set_error(self, e):
"""
Rather than allowing unmanaged exceptions to explode, or raising errors
within thread, the worker thread should call this function with an
error class or instance.
"""
self.result = (False, e)
self._lock.release() | [
"def",
"set_error",
"(",
"self",
",",
"e",
")",
":",
"self",
".",
"result",
"=",
"(",
"False",
",",
"e",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Rather than allowing unmanaged exceptions to explode, or raising errors
within thread, the worker thread should call this function with an
error class or instance. | [
"Rather",
"than",
"allowing",
"unmanaged",
"exceptions",
"to",
"explode",
"or",
"raising",
"errors",
"within",
"thread",
"the",
"worker",
"thread",
"should",
"call",
"this",
"function",
"with",
"an",
"error",
"class",
"or",
"instance",
"."
] | train | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/resync.py#L128-L135 |
pydsigner/taskit | taskit/resync.py | Mediator.get | def get(self, timeout=None):
"""
Get a result or raise an error. If `timeout` is not None, this function
will wait for only `timeout` seconds before raising ThreadTimeout().
"""
if timeout is None:
self._lock.acquire()
else:
self._wait(timeout)
... | python | def get(self, timeout=None):
"""
Get a result or raise an error. If `timeout` is not None, this function
will wait for only `timeout` seconds before raising ThreadTimeout().
"""
if timeout is None:
self._lock.acquire()
else:
self._wait(timeout)
... | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"else",
":",
"self",
".",
"_wait",
"(",
"timeout",
")",
"res",
"=",
"self",
".",
"result",
"if",... | Get a result or raise an error. If `timeout` is not None, this function
will wait for only `timeout` seconds before raising ThreadTimeout(). | [
"Get",
"a",
"result",
"or",
"raise",
"an",
"error",
".",
"If",
"timeout",
"is",
"not",
"None",
"this",
"function",
"will",
"wait",
"for",
"only",
"timeout",
"seconds",
"before",
"raising",
"ThreadTimeout",
"()",
"."
] | train | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/resync.py#L137-L151 |
pydsigner/taskit | taskit/resync.py | Resyncer._wrapper | def _wrapper(self):
"""
Wraps around a few calls which need to be made in the same thread.
"""
try:
res = self.func(*self.args, **self.kw)
except Exception as e:
self.mediator.set_error(e)
else:
self.mediator.set_result(res) | python | def _wrapper(self):
"""
Wraps around a few calls which need to be made in the same thread.
"""
try:
res = self.func(*self.args, **self.kw)
except Exception as e:
self.mediator.set_error(e)
else:
self.mediator.set_result(res) | [
"def",
"_wrapper",
"(",
"self",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"func",
"(",
"*",
"self",
".",
"args",
",",
"*",
"*",
"self",
".",
"kw",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"mediator",
".",
"set_error",
"(",
... | Wraps around a few calls which need to be made in the same thread. | [
"Wraps",
"around",
"a",
"few",
"calls",
"which",
"need",
"to",
"be",
"made",
"in",
"the",
"same",
"thread",
"."
] | train | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/resync.py#L170-L179 |
merryspankersltd/irenee | irenee/catfish.py | addinterval | def addinterval(instr, add, interval):
'''
adds string every n character. returns string
'''
if not isinstance(instr, str):
instr = str(instr)
return add.join(
instr[i:i+interval]
for i in xrange(0,len(instr),interval)) | python | def addinterval(instr, add, interval):
'''
adds string every n character. returns string
'''
if not isinstance(instr, str):
instr = str(instr)
return add.join(
instr[i:i+interval]
for i in xrange(0,len(instr),interval)) | [
"def",
"addinterval",
"(",
"instr",
",",
"add",
",",
"interval",
")",
":",
"if",
"not",
"isinstance",
"(",
"instr",
",",
"str",
")",
":",
"instr",
"=",
"str",
"(",
"instr",
")",
"return",
"add",
".",
"join",
"(",
"instr",
"[",
"i",
":",
"i",
"+",... | adds string every n character. returns string | [
"adds",
"string",
"every",
"n",
"character",
".",
"returns",
"string"
] | train | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L27-L36 |
merryspankersltd/irenee | irenee/catfish.py | get | def get(siren):
'''
renvoie un tuple (str, str, str, rs)
un siren
une categorie d'entreprise
une annee
une raison sociale
param: un siren (str)
:Example:
>>> get('444465736')
(u'2013', u'444465736', u'entreprise de taille inte... | python | def get(siren):
'''
renvoie un tuple (str, str, str, rs)
un siren
une categorie d'entreprise
une annee
une raison sociale
param: un siren (str)
:Example:
>>> get('444465736')
(u'2013', u'444465736', u'entreprise de taille inte... | [
"def",
"get",
"(",
"siren",
")",
":",
"# format siren",
"siren",
"=",
"addinterval",
"(",
"siren",
",",
"' '",
",",
"3",
")",
"# send request",
"res",
"=",
"requests",
".",
"get",
"(",
"api",
".",
"format",
"(",
"siren",
")",
")",
"try",
":",
"# if r... | renvoie un tuple (str, str, str, rs)
un siren
une categorie d'entreprise
une annee
une raison sociale
param: un siren (str)
:Example:
>>> get('444465736')
(u'2013', u'444465736', u'entreprise de taille interm\xe9diaire', u'NOVACAP')
... | [
"renvoie",
"un",
"tuple",
"(",
"str",
"str",
"str",
"rs",
")",
"un",
"siren",
"une",
"categorie",
"d",
"entreprise",
"une",
"annee",
"une",
"raison",
"sociale",
"param",
":",
"un",
"siren",
"(",
"str",
")"
] | train | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L38-L84 |
merryspankersltd/irenee | irenee/catfish.py | parse_ok | def parse_ok(l1, l3):
'''
parse html when siren is ok
'''
return {
'annee': l1.text.split(' : ')[1].split()[2],
'siren valide': ''.join(
l1.text.split(' : ')[1].split(u'\xab')[0].split()[-4:-1]),
'categorie': ' '.join(
l1.text.split(' : ')[1].split(u'\... | python | def parse_ok(l1, l3):
'''
parse html when siren is ok
'''
return {
'annee': l1.text.split(' : ')[1].split()[2],
'siren valide': ''.join(
l1.text.split(' : ')[1].split(u'\xab')[0].split()[-4:-1]),
'categorie': ' '.join(
l1.text.split(' : ')[1].split(u'\... | [
"def",
"parse_ok",
"(",
"l1",
",",
"l3",
")",
":",
"return",
"{",
"'annee'",
":",
"l1",
".",
"text",
".",
"split",
"(",
"' : '",
")",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"2",
"]",
",",
"'siren valide'",
":",
"''",
".",
"join",
"(",
"l... | parse html when siren is ok | [
"parse",
"html",
"when",
"siren",
"is",
"ok"
] | train | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L86-L97 |
merryspankersltd/irenee | irenee/catfish.py | parse_obsolete | def parse_obsolete(l1, l3):
'''
parse html when siren is obsolete
'''
return {
'annee': l1.text.split('.')[2].split()[2],
'siren valide': ''.join(
l1.text.split('.')[2].split(u'\xab')[0].split()[-4:-1]),
'categorie': ' '.join(
l1.text.split('.')[2].spl... | python | def parse_obsolete(l1, l3):
'''
parse html when siren is obsolete
'''
return {
'annee': l1.text.split('.')[2].split()[2],
'siren valide': ''.join(
l1.text.split('.')[2].split(u'\xab')[0].split()[-4:-1]),
'categorie': ' '.join(
l1.text.split('.')[2].spl... | [
"def",
"parse_obsolete",
"(",
"l1",
",",
"l3",
")",
":",
"return",
"{",
"'annee'",
":",
"l1",
".",
"text",
".",
"split",
"(",
"'.'",
")",
"[",
"2",
"]",
".",
"split",
"(",
")",
"[",
"2",
"]",
",",
"'siren valide'",
":",
"''",
".",
"join",
"(",
... | parse html when siren is obsolete | [
"parse",
"html",
"when",
"siren",
"is",
"obsolete"
] | train | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L99-L110 |
merryspankersltd/irenee | irenee/catfish.py | parse_new | def parse_new(l1, l2, l3):
'''
parse html when siren is obsolete
'''
return {
'annee': l1.text.split(' : ')[1].split()[2],
'siren valide': ''.join(l2.text.split(' : ')[1].split()),
'categorie': u'nouvellement cr\xe9\xe9e',
'raison sociale': l3.text.split(' : ')[1][:-1... | python | def parse_new(l1, l2, l3):
'''
parse html when siren is obsolete
'''
return {
'annee': l1.text.split(' : ')[1].split()[2],
'siren valide': ''.join(l2.text.split(' : ')[1].split()),
'categorie': u'nouvellement cr\xe9\xe9e',
'raison sociale': l3.text.split(' : ')[1][:-1... | [
"def",
"parse_new",
"(",
"l1",
",",
"l2",
",",
"l3",
")",
":",
"return",
"{",
"'annee'",
":",
"l1",
".",
"text",
".",
"split",
"(",
"' : '",
")",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"2",
"]",
",",
"'siren valide'",
":",
"''",
".",
"jo... | parse html when siren is obsolete | [
"parse",
"html",
"when",
"siren",
"is",
"obsolete"
] | train | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L112-L121 |
merryspankersltd/irenee | irenee/catfish.py | batch | def batch(in_xlsx, out_xlsx):
'''
retrieves siren list from input xlsx and batches get() to output xlsx
'''
import pandas as pd
import time
import openpyxl
pd.core.format.header_style = None
# load file
sirens_df = pd.read_excel(in_xlsx)
# extract and batch sirens
siren... | python | def batch(in_xlsx, out_xlsx):
'''
retrieves siren list from input xlsx and batches get() to output xlsx
'''
import pandas as pd
import time
import openpyxl
pd.core.format.header_style = None
# load file
sirens_df = pd.read_excel(in_xlsx)
# extract and batch sirens
siren... | [
"def",
"batch",
"(",
"in_xlsx",
",",
"out_xlsx",
")",
":",
"import",
"pandas",
"as",
"pd",
"import",
"time",
"import",
"openpyxl",
"pd",
".",
"core",
".",
"format",
".",
"header_style",
"=",
"None",
"# load file",
"sirens_df",
"=",
"pd",
".",
"read_excel",... | retrieves siren list from input xlsx and batches get() to output xlsx | [
"retrieves",
"siren",
"list",
"from",
"input",
"xlsx",
"and",
"batches",
"get",
"()",
"to",
"output",
"xlsx"
] | train | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L145-L170 |
edeposit/edeposit.amqp.calibre | src/edeposit/amqp/calibre/__init__.py | reactToAMQPMessage | def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is usually expected to be
:py:func:`collections.namedtuple` structure filled with all necessary data.
Args:
message (\*Request class): only :class:`.ConversionRequest` class is
... | python | def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is usually expected to be
:py:func:`collections.namedtuple` structure filled with all necessary data.
Args:
message (\*Request class): only :class:`.ConversionRequest` class is
... | [
"def",
"reactToAMQPMessage",
"(",
"message",
",",
"send_back",
")",
":",
"if",
"_instanceof",
"(",
"message",
",",
"ConversionRequest",
")",
":",
"return",
"convert",
"(",
"message",
".",
"input_format",
",",
"message",
".",
"output_format",
",",
"message",
".... | React to given (AMQP) message. `message` is usually expected to be
:py:func:`collections.namedtuple` structure filled with all necessary data.
Args:
message (\*Request class): only :class:`.ConversionRequest` class is
supported right now
send_back (fn referen... | [
"React",
"to",
"given",
"(",
"AMQP",
")",
"message",
".",
"message",
"is",
"usually",
"expected",
"to",
"be",
":",
"py",
":",
"func",
":",
"collections",
".",
"namedtuple",
"structure",
"filled",
"with",
"all",
"necessary",
"data",
"."
] | train | https://github.com/edeposit/edeposit.amqp.calibre/blob/60ba5de0c30452d41f6e0da58d2ec6729ebdd7f1/src/edeposit/amqp/calibre/__init__.py#L22-L52 |
pjanis/funtool | funtool/lib/general.py | sort_states | def sort_states(states, sort_list):
"""
Returns a list of sorted states, original states list remains unsorted
The sort list is a list of state field: field key pairs
For example (as YAML):
- data: position
- meta: created_at
The field_key part can be a list to simplify ... | python | def sort_states(states, sort_list):
"""
Returns a list of sorted states, original states list remains unsorted
The sort list is a list of state field: field key pairs
For example (as YAML):
- data: position
- meta: created_at
The field_key part can be a list to simplify ... | [
"def",
"sort_states",
"(",
"states",
",",
"sort_list",
")",
":",
"sorted_states",
"=",
"states",
".",
"copy",
"(",
")",
"for",
"sort_pair",
"in",
"reversed",
"(",
"_convert_list_of_dict_to_tuple",
"(",
"sort_list",
")",
")",
":",
"if",
"sort_pair",
"[",
"0",... | Returns a list of sorted states, original states list remains unsorted
The sort list is a list of state field: field key pairs
For example (as YAML):
- data: position
- meta: created_at
The field_key part can be a list to simplify input
- meta: created_at
- meta:... | [
"Returns",
"a",
"list",
"of",
"sorted",
"states",
"original",
"states",
"list",
"remains",
"unsorted"
] | train | https://github.com/pjanis/funtool/blob/231851238f0a62bc3682d8fa937db9053378c53d/funtool/lib/general.py#L27-L75 |
jmgilman/Neolib | neolib/pyamf/__init__.py | register_class | def register_class(klass, alias=None):
"""
Registers a class to be used in the data streaming. This is the equivalent
to the C{[RemoteClass(alias="foobar")]} AS3 metatag.
@return: The registered L{ClassAlias} instance.
@see: L{unregister_class}
"""
meta = util.get_class_meta(klass)
if ... | python | def register_class(klass, alias=None):
"""
Registers a class to be used in the data streaming. This is the equivalent
to the C{[RemoteClass(alias="foobar")]} AS3 metatag.
@return: The registered L{ClassAlias} instance.
@see: L{unregister_class}
"""
meta = util.get_class_meta(klass)
if ... | [
"def",
"register_class",
"(",
"klass",
",",
"alias",
"=",
"None",
")",
":",
"meta",
"=",
"util",
".",
"get_class_meta",
"(",
"klass",
")",
"if",
"alias",
"is",
"not",
"None",
":",
"meta",
"[",
"'alias'",
"]",
"=",
"alias",
"alias_klass",
"=",
"util",
... | Registers a class to be used in the data streaming. This is the equivalent
to the C{[RemoteClass(alias="foobar")]} AS3 metatag.
@return: The registered L{ClassAlias} instance.
@see: L{unregister_class} | [
"Registers",
"a",
"class",
"to",
"be",
"used",
"in",
"the",
"data",
"streaming",
".",
"This",
"is",
"the",
"equivalent",
"to",
"the",
"C",
"{",
"[",
"RemoteClass",
"(",
"alias",
"=",
"foobar",
")",
"]",
"}",
"AS3",
"metatag",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L224-L246 |
jmgilman/Neolib | neolib/pyamf/__init__.py | unregister_class | def unregister_class(alias):
"""
Opposite of L{register_class}.
@raise UnknownClassAlias: Unknown alias.
"""
try:
x = CLASS_CACHE[alias]
except KeyError:
raise UnknownClassAlias('Unknown alias %r' % (alias,))
if not x.anonymous:
del CLASS_CACHE[x.alias]
del CLA... | python | def unregister_class(alias):
"""
Opposite of L{register_class}.
@raise UnknownClassAlias: Unknown alias.
"""
try:
x = CLASS_CACHE[alias]
except KeyError:
raise UnknownClassAlias('Unknown alias %r' % (alias,))
if not x.anonymous:
del CLASS_CACHE[x.alias]
del CLA... | [
"def",
"unregister_class",
"(",
"alias",
")",
":",
"try",
":",
"x",
"=",
"CLASS_CACHE",
"[",
"alias",
"]",
"except",
"KeyError",
":",
"raise",
"UnknownClassAlias",
"(",
"'Unknown alias %r'",
"%",
"(",
"alias",
",",
")",
")",
"if",
"not",
"x",
".",
"anony... | Opposite of L{register_class}.
@raise UnknownClassAlias: Unknown alias. | [
"Opposite",
"of",
"L",
"{",
"register_class",
"}",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L249-L265 |
jmgilman/Neolib | neolib/pyamf/__init__.py | get_class_alias | def get_class_alias(klass_or_alias):
"""
Finds the L{ClassAlias} that is registered to C{klass_or_alias}.
If a string is supplied and no related L{ClassAlias} is found, the alias is
loaded via L{load_class}.
@raise UnknownClassAlias: Unknown alias
"""
if isinstance(klass_or_alias, python.s... | python | def get_class_alias(klass_or_alias):
"""
Finds the L{ClassAlias} that is registered to C{klass_or_alias}.
If a string is supplied and no related L{ClassAlias} is found, the alias is
loaded via L{load_class}.
@raise UnknownClassAlias: Unknown alias
"""
if isinstance(klass_or_alias, python.s... | [
"def",
"get_class_alias",
"(",
"klass_or_alias",
")",
":",
"if",
"isinstance",
"(",
"klass_or_alias",
",",
"python",
".",
"str_types",
")",
":",
"try",
":",
"return",
"CLASS_CACHE",
"[",
"klass_or_alias",
"]",
"except",
"KeyError",
":",
"return",
"load_class",
... | Finds the L{ClassAlias} that is registered to C{klass_or_alias}.
If a string is supplied and no related L{ClassAlias} is found, the alias is
loaded via L{load_class}.
@raise UnknownClassAlias: Unknown alias | [
"Finds",
"the",
"L",
"{",
"ClassAlias",
"}",
"that",
"is",
"registered",
"to",
"C",
"{",
"klass_or_alias",
"}",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L268-L286 |
jmgilman/Neolib | neolib/pyamf/__init__.py | load_class | def load_class(alias):
"""
Finds the class registered to the alias.
The search is done in order:
1. Checks if the class name has been registered via L{register_class}
or L{register_package}.
2. Checks all functions registered via L{register_class_loader}.
3. Attempts to load the ... | python | def load_class(alias):
"""
Finds the class registered to the alias.
The search is done in order:
1. Checks if the class name has been registered via L{register_class}
or L{register_package}.
2. Checks all functions registered via L{register_class_loader}.
3. Attempts to load the ... | [
"def",
"load_class",
"(",
"alias",
")",
":",
"# Try the CLASS_CACHE first",
"try",
":",
"return",
"CLASS_CACHE",
"[",
"alias",
"]",
"except",
"KeyError",
":",
"pass",
"for",
"loader",
"in",
"CLASS_LOADERS",
":",
"klass",
"=",
"loader",
"(",
"alias",
")",
"if... | Finds the class registered to the alias.
The search is done in order:
1. Checks if the class name has been registered via L{register_class}
or L{register_package}.
2. Checks all functions registered via L{register_class_loader}.
3. Attempts to load the class via standard module loading t... | [
"Finds",
"the",
"class",
"registered",
"to",
"the",
"alias",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L336-L399 |
jmgilman/Neolib | neolib/pyamf/__init__.py | decode | def decode(stream, *args, **kwargs):
"""
A generator function to decode a datastream.
@param stream: AMF data to be decoded.
@type stream: byte data.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A generator that will decode each element in the stream.
"""
encod... | python | def decode(stream, *args, **kwargs):
"""
A generator function to decode a datastream.
@param stream: AMF data to be decoded.
@type stream: byte data.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A generator that will decode each element in the stream.
"""
encod... | [
"def",
"decode",
"(",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"DEFAULT_ENCODING",
")",
"decoder",
"=",
"get_decoder",
"(",
"encoding",
",",
"stream",
",",
"*",
"args"... | A generator function to decode a datastream.
@param stream: AMF data to be decoded.
@type stream: byte data.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A generator that will decode each element in the stream. | [
"A",
"generator",
"function",
"to",
"decode",
"a",
"datastream",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L402-L414 |
jmgilman/Neolib | neolib/pyamf/__init__.py | encode | def encode(*args, **kwargs):
"""
A helper function to encode an element.
@param args: The python data to be encoded.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A L{util.BufferedByteStream} object that contains the data.
"""
encoding = kwargs.pop('encoding', DEFAU... | python | def encode(*args, **kwargs):
"""
A helper function to encode an element.
@param args: The python data to be encoded.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A L{util.BufferedByteStream} object that contains the data.
"""
encoding = kwargs.pop('encoding', DEFAU... | [
"def",
"encode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"DEFAULT_ENCODING",
")",
"encoder",
"=",
"get_encoder",
"(",
"encoding",
",",
"*",
"*",
"kwargs",
")",
"[",
"encoder",
... | A helper function to encode an element.
@param args: The python data to be encoded.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A L{util.BufferedByteStream} object that contains the data. | [
"A",
"helper",
"function",
"to",
"encode",
"an",
"element",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L417-L433 |
jmgilman/Neolib | neolib/pyamf/__init__.py | get_decoder | def get_decoder(encoding, *args, **kwargs):
"""
Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}.
"""
def _get_decoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except Imp... | python | def get_decoder(encoding, *args, **kwargs):
"""
Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}.
"""
def _get_decoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except Imp... | [
"def",
"get_decoder",
"(",
"encoding",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_get_decoder_class",
"(",
")",
":",
"if",
"encoding",
"==",
"AMF0",
":",
"try",
":",
"from",
"cpyamf",
"import",
"amf0",
"except",
"ImportError",
":",
"... | Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}. | [
"Returns",
"a",
"L",
"{",
"codec",
".",
"Decoder",
"}",
"capable",
"of",
"decoding",
"AMF",
"[",
"C",
"{",
"encoding",
"}",
"]",
"streams",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L436-L460 |
jmgilman/Neolib | neolib/pyamf/__init__.py | get_encoder | def get_encoder(encoding, *args, **kwargs):
"""
Returns a L{codec.Encoder} capable of encoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}.
"""
def _get_encoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except Imp... | python | def get_encoder(encoding, *args, **kwargs):
"""
Returns a L{codec.Encoder} capable of encoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}.
"""
def _get_encoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except Imp... | [
"def",
"get_encoder",
"(",
"encoding",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_get_encoder_class",
"(",
")",
":",
"if",
"encoding",
"==",
"AMF0",
":",
"try",
":",
"from",
"cpyamf",
"import",
"amf0",
"except",
"ImportError",
":",
"... | Returns a L{codec.Encoder} capable of encoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}. | [
"Returns",
"a",
"L",
"{",
"codec",
".",
"Encoder",
"}",
"capable",
"of",
"encoding",
"AMF",
"[",
"C",
"{",
"encoding",
"}",
"]",
"streams",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L463-L487 |
jmgilman/Neolib | neolib/pyamf/__init__.py | flex_loader | def flex_loader(alias):
"""
Loader for L{Flex<pyamf.flex>} framework compatibility classes.
@raise UnknownClassAlias: Trying to load an unknown Flex compatibility class.
"""
if not alias.startswith('flex.'):
return
try:
if alias.startswith('flex.messaging.messages'):
... | python | def flex_loader(alias):
"""
Loader for L{Flex<pyamf.flex>} framework compatibility classes.
@raise UnknownClassAlias: Trying to load an unknown Flex compatibility class.
"""
if not alias.startswith('flex.'):
return
try:
if alias.startswith('flex.messaging.messages'):
... | [
"def",
"flex_loader",
"(",
"alias",
")",
":",
"if",
"not",
"alias",
".",
"startswith",
"(",
"'flex.'",
")",
":",
"return",
"try",
":",
"if",
"alias",
".",
"startswith",
"(",
"'flex.messaging.messages'",
")",
":",
"import",
"pyamf",
".",
"flex",
".",
"mes... | Loader for L{Flex<pyamf.flex>} framework compatibility classes.
@raise UnknownClassAlias: Trying to load an unknown Flex compatibility class. | [
"Loader",
"for",
"L",
"{",
"Flex<pyamf",
".",
"flex",
">",
"}",
"framework",
"compatibility",
"classes",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L506-L525 |
jmgilman/Neolib | neolib/pyamf/__init__.py | add_type | def add_type(type_, func=None):
"""
Adds a custom type to L{TYPE_MAP}. A custom type allows fine grain control
of what to encode to an AMF data stream.
@raise TypeError: Unable to add as a custom type (expected a class or callable).
@raise KeyError: Type already exists.
@see: L{get_type} and L{... | python | def add_type(type_, func=None):
"""
Adds a custom type to L{TYPE_MAP}. A custom type allows fine grain control
of what to encode to an AMF data stream.
@raise TypeError: Unable to add as a custom type (expected a class or callable).
@raise KeyError: Type already exists.
@see: L{get_type} and L{... | [
"def",
"add_type",
"(",
"type_",
",",
"func",
"=",
"None",
")",
":",
"def",
"_check_type",
"(",
"type_",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"type_",
",",
"python",
".",
"class_types",
")",
"or",
"hasattr",
"(",
"type_",
",",
"'__call__'",
... | Adds a custom type to L{TYPE_MAP}. A custom type allows fine grain control
of what to encode to an AMF data stream.
@raise TypeError: Unable to add as a custom type (expected a class or callable).
@raise KeyError: Type already exists.
@see: L{get_type} and L{remove_type} | [
"Adds",
"a",
"custom",
"type",
"to",
"L",
"{",
"TYPE_MAP",
"}",
".",
"A",
"custom",
"type",
"allows",
"fine",
"grain",
"control",
"of",
"what",
"to",
"encode",
"to",
"an",
"AMF",
"data",
"stream",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L528-L555 |
jmgilman/Neolib | neolib/pyamf/__init__.py | get_type | def get_type(type_):
"""
Gets the declaration for the corresponding custom type.
@raise KeyError: Unknown type.
@see: L{add_type} and L{remove_type}
"""
if isinstance(type_, list):
type_ = tuple(type_)
for k, v in TYPE_MAP.iteritems():
if k == type_:
return v
... | python | def get_type(type_):
"""
Gets the declaration for the corresponding custom type.
@raise KeyError: Unknown type.
@see: L{add_type} and L{remove_type}
"""
if isinstance(type_, list):
type_ = tuple(type_)
for k, v in TYPE_MAP.iteritems():
if k == type_:
return v
... | [
"def",
"get_type",
"(",
"type_",
")",
":",
"if",
"isinstance",
"(",
"type_",
",",
"list",
")",
":",
"type_",
"=",
"tuple",
"(",
"type_",
")",
"for",
"k",
",",
"v",
"in",
"TYPE_MAP",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"==",
"type_",
":",
... | Gets the declaration for the corresponding custom type.
@raise KeyError: Unknown type.
@see: L{add_type} and L{remove_type} | [
"Gets",
"the",
"declaration",
"for",
"the",
"corresponding",
"custom",
"type",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L558-L572 |
jmgilman/Neolib | neolib/pyamf/__init__.py | add_error_class | def add_error_class(klass, code):
"""
Maps an exception class to a string code. Used to map remoting C{onStatus}
objects to an exception class so that an exception can be built to
represent that error.
An example::
>>> class AuthenticationError(Exception):
... pass
...
... | python | def add_error_class(klass, code):
"""
Maps an exception class to a string code. Used to map remoting C{onStatus}
objects to an exception class so that an exception can be built to
represent that error.
An example::
>>> class AuthenticationError(Exception):
... pass
...
... | [
"def",
"add_error_class",
"(",
"klass",
",",
"code",
")",
":",
"if",
"not",
"isinstance",
"(",
"code",
",",
"python",
".",
"str_types",
")",
":",
"code",
"=",
"code",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"not",
"isinstance",
"(",
"klass",
",",
"... | Maps an exception class to a string code. Used to map remoting C{onStatus}
objects to an exception class so that an exception can be built to
represent that error.
An example::
>>> class AuthenticationError(Exception):
... pass
...
>>> pyamf.add_error_class(Authenticati... | [
"Maps",
"an",
"exception",
"class",
"to",
"a",
"string",
"code",
".",
"Used",
"to",
"map",
"remoting",
"C",
"{",
"onStatus",
"}",
"objects",
"to",
"an",
"exception",
"class",
"so",
"that",
"an",
"exception",
"can",
"be",
"built",
"to",
"represent",
"that... | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L589-L626 |
jmgilman/Neolib | neolib/pyamf/__init__.py | remove_error_class | def remove_error_class(klass):
"""
Removes a class from the L{ERROR_CLASS_MAP}.
An example::
>>> class AuthenticationError(Exception):
... pass
...
>>> pyamf.add_error_class(AuthenticationError, 'Auth.Failed')
>>> pyamf.remove_error_class(AuthenticationError)
@s... | python | def remove_error_class(klass):
"""
Removes a class from the L{ERROR_CLASS_MAP}.
An example::
>>> class AuthenticationError(Exception):
... pass
...
>>> pyamf.add_error_class(AuthenticationError, 'Auth.Failed')
>>> pyamf.remove_error_class(AuthenticationError)
@s... | [
"def",
"remove_error_class",
"(",
"klass",
")",
":",
"if",
"isinstance",
"(",
"klass",
",",
"python",
".",
"str_types",
")",
":",
"if",
"klass",
"not",
"in",
"ERROR_CLASS_MAP",
":",
"raise",
"ValueError",
"(",
"'Code %s is not registered'",
"%",
"(",
"klass",
... | Removes a class from the L{ERROR_CLASS_MAP}.
An example::
>>> class AuthenticationError(Exception):
... pass
...
>>> pyamf.add_error_class(AuthenticationError, 'Auth.Failed')
>>> pyamf.remove_error_class(AuthenticationError)
@see: L{add_error_class} | [
"Removes",
"a",
"class",
"from",
"the",
"L",
"{",
"ERROR_CLASS_MAP",
"}",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L629-L655 |
jmgilman/Neolib | neolib/pyamf/__init__.py | register_alias_type | def register_alias_type(klass, *args):
"""
This function allows you to map subclasses of L{ClassAlias} to classes
listed in C{args}.
When an object is read/written from/to the AMF stream, a paired L{ClassAlias}
instance is created (or reused), based on the Python class of that object.
L{ClassAl... | python | def register_alias_type(klass, *args):
"""
This function allows you to map subclasses of L{ClassAlias} to classes
listed in C{args}.
When an object is read/written from/to the AMF stream, a paired L{ClassAlias}
instance is created (or reused), based on the Python class of that object.
L{ClassAl... | [
"def",
"register_alias_type",
"(",
"klass",
",",
"*",
"args",
")",
":",
"def",
"check_type_registered",
"(",
"arg",
")",
":",
"for",
"k",
",",
"v",
"in",
"ALIAS_TYPES",
".",
"iteritems",
"(",
")",
":",
"for",
"kl",
"in",
"v",
":",
"if",
"arg",
"is",
... | This function allows you to map subclasses of L{ClassAlias} to classes
listed in C{args}.
When an object is read/written from/to the AMF stream, a paired L{ClassAlias}
instance is created (or reused), based on the Python class of that object.
L{ClassAlias} provides important metadata for the class and ... | [
"This",
"function",
"allows",
"you",
"to",
"map",
"subclasses",
"of",
"L",
"{",
"ClassAlias",
"}",
"to",
"classes",
"listed",
"in",
"C",
"{",
"args",
"}",
"."
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L658-L721 |
jmgilman/Neolib | neolib/pyamf/__init__.py | register_package | def register_package(module=None, package=None, separator='.', ignore=[],
strict=True):
"""
This is a helper function that takes the concept of Actionscript packages
and registers all the classes in the supplied Python module under that
package. It auto-aliased all classes in C{modu... | python | def register_package(module=None, package=None, separator='.', ignore=[],
strict=True):
"""
This is a helper function that takes the concept of Actionscript packages
and registers all the classes in the supplied Python module under that
package. It auto-aliased all classes in C{modu... | [
"def",
"register_package",
"(",
"module",
"=",
"None",
",",
"package",
"=",
"None",
",",
"separator",
"=",
"'.'",
",",
"ignore",
"=",
"[",
"]",
",",
"strict",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"python",
".",
"str_types",
... | This is a helper function that takes the concept of Actionscript packages
and registers all the classes in the supplied Python module under that
package. It auto-aliased all classes in C{module} based on the parent
C{package}.
@param module: The Python module that will contain all the classes to
... | [
"This",
"is",
"a",
"helper",
"function",
"that",
"takes",
"the",
"concept",
"of",
"Actionscript",
"packages",
"and",
"registers",
"all",
"the",
"classes",
"in",
"the",
"supplied",
"Python",
"module",
"under",
"that",
"package",
".",
"It",
"auto",
"-",
"alias... | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L733-L826 |
madisona/apysigner | apysigner.py | Signer.create_signature | def create_signature(self, base_url, payload=None):
"""
Creates unique signature for request.
Make sure ALL 'GET' and 'POST' data is already included before
creating the signature or receiver won't be able to re-create it.
:param base_url:
The url you'll using for yo... | python | def create_signature(self, base_url, payload=None):
"""
Creates unique signature for request.
Make sure ALL 'GET' and 'POST' data is already included before
creating the signature or receiver won't be able to re-create it.
:param base_url:
The url you'll using for yo... | [
"def",
"create_signature",
"(",
"self",
",",
"base_url",
",",
"payload",
"=",
"None",
")",
":",
"url",
"=",
"urlparse",
"(",
"base_url",
")",
"url_to_sign",
"=",
"\"{path}?{query}\"",
".",
"format",
"(",
"path",
"=",
"url",
".",
"path",
",",
"query",
"="... | Creates unique signature for request.
Make sure ALL 'GET' and 'POST' data is already included before
creating the signature or receiver won't be able to re-create it.
:param base_url:
The url you'll using for your request.
:param payload:
The POST data that you'l... | [
"Creates",
"unique",
"signature",
"for",
"request",
".",
"Make",
"sure",
"ALL",
"GET",
"and",
"POST",
"data",
"is",
"already",
"included",
"before",
"creating",
"the",
"signature",
"or",
"receiver",
"won",
"t",
"be",
"able",
"to",
"re",
"-",
"create",
"it"... | train | https://github.com/madisona/apysigner/blob/3666b478d228a38aca66a1b73d0aaf4aa67e765d/apysigner.py#L66-L85 |
madisona/apysigner | apysigner.py | Signer._convert | def _convert(self, payload):
"""
Converts payload to a string. Complex objects are dumped to json
"""
if not isinstance(payload, six.string_types):
payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True)
return str(payload) | python | def _convert(self, payload):
"""
Converts payload to a string. Complex objects are dumped to json
"""
if not isinstance(payload, six.string_types):
payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True)
return str(payload) | [
"def",
"_convert",
"(",
"self",
",",
"payload",
")",
":",
"if",
"not",
"isinstance",
"(",
"payload",
",",
"six",
".",
"string_types",
")",
":",
"payload",
"=",
"json",
".",
"dumps",
"(",
"payload",
",",
"cls",
"=",
"DefaultJSONEncoder",
",",
"sort_keys",... | Converts payload to a string. Complex objects are dumped to json | [
"Converts",
"payload",
"to",
"a",
"string",
".",
"Complex",
"objects",
"are",
"dumped",
"to",
"json"
] | train | https://github.com/madisona/apysigner/blob/3666b478d228a38aca66a1b73d0aaf4aa67e765d/apysigner.py#L87-L93 |
heikomuller/sco-datastore | scodata/funcdata.py | DefaultFunctionalDataManager.create_object | def create_object(self, filename, read_only=False):
"""Create a functional data object for the given file. Expects the file
to be a valid functional data file. Expects exactly one file that has
suffix mgh/mgz or nii/nii.gz.
Parameters
----------
filename : string
... | python | def create_object(self, filename, read_only=False):
"""Create a functional data object for the given file. Expects the file
to be a valid functional data file. Expects exactly one file that has
suffix mgh/mgz or nii/nii.gz.
Parameters
----------
filename : string
... | [
"def",
"create_object",
"(",
"self",
",",
"filename",
",",
"read_only",
"=",
"False",
")",
":",
"# Get the file name, i.e., last component of the given absolute path",
"prop_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"normpath",
"... | Create a functional data object for the given file. Expects the file
to be a valid functional data file. Expects exactly one file that has
suffix mgh/mgz or nii/nii.gz.
Parameters
----------
filename : string
Name of the (uploaded) file
read_only : boolean, o... | [
"Create",
"a",
"functional",
"data",
"object",
"for",
"the",
"given",
"file",
".",
"Expects",
"the",
"file",
"to",
"be",
"a",
"valid",
"functional",
"data",
"file",
".",
"Expects",
"exactly",
"one",
"file",
"that",
"has",
"suffix",
"mgh",
"/",
"mgz",
"or... | train | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/funcdata.py#L178-L236 |
heikomuller/sco-datastore | scodata/funcdata.py | DefaultFunctionalDataManager.from_dict | def from_dict(self, document):
"""Create functional data object from JSON document retrieved from
database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
FunctionalDataHandle
Handle for functional... | python | def from_dict(self, document):
"""Create functional data object from JSON document retrieved from
database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
FunctionalDataHandle
Handle for functional... | [
"def",
"from_dict",
"(",
"self",
",",
"document",
")",
":",
"identifier",
"=",
"str",
"(",
"document",
"[",
"'_id'",
"]",
")",
"active",
"=",
"document",
"[",
"'active'",
"]",
"# The directory is not materilaized in database to allow moving the",
"# base directory wit... | Create functional data object from JSON document retrieved from
database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
FunctionalDataHandle
Handle for functional data object | [
"Create",
"functional",
"data",
"object",
"from",
"JSON",
"document",
"retrieved",
"from",
"database",
"."
] | train | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/funcdata.py#L238-L259 |
cmheisel/better-project-forecast | better/lib.py | Forecaster.forecast | def forecast(self, throughputs, backlog_size, num_simulations=10000, max_periods=10000, seed=None):
"""Forecasts how long a backlog will take to complete given the historical values provided.
Arguments:
throughputs(List[int]): Number of units completed per unit of time (stories per week, sto... | python | def forecast(self, throughputs, backlog_size, num_simulations=10000, max_periods=10000, seed=None):
"""Forecasts how long a backlog will take to complete given the historical values provided.
Arguments:
throughputs(List[int]): Number of units completed per unit of time (stories per week, sto... | [
"def",
"forecast",
"(",
"self",
",",
"throughputs",
",",
"backlog_size",
",",
"num_simulations",
"=",
"10000",
",",
"max_periods",
"=",
"10000",
",",
"seed",
"=",
"None",
")",
":",
"self",
".",
"_check_throughputs",
"(",
"throughputs",
")",
"results",
"=",
... | Forecasts how long a backlog will take to complete given the historical values provided.
Arguments:
throughputs(List[int]): Number of units completed per unit of time (stories per week, story points per month, etc.)
backlog_size(int): Units in the backlog (stories, points, etc.)
... | [
"Forecasts",
"how",
"long",
"a",
"backlog",
"will",
"take",
"to",
"complete",
"given",
"the",
"historical",
"values",
"provided",
".",
"Arguments",
":",
"throughputs",
"(",
"List",
"[",
"int",
"]",
")",
":",
"Number",
"of",
"units",
"completed",
"per",
"un... | train | https://github.com/cmheisel/better-project-forecast/blob/9bcba88d70c174ecedec09a020b02ac530bc4734/better/lib.py#L30-L56 |
kennydo/nyaalib | nyaalib/__init__.py | extract_url_query_parameter | def extract_url_query_parameter(url, parameter):
"""Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for the given query name in the gi... | python | def extract_url_query_parameter(url, parameter):
"""Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for the given query name in the gi... | [
"def",
"extract_url_query_parameter",
"(",
"url",
",",
"parameter",
")",
":",
"query_string",
"=",
"urlparse",
"(",
"url",
")",
".",
"query",
"return",
"parse_qs",
"(",
"query_string",
")",
".",
"get",
"(",
"parameter",
",",
"[",
"]",
")"
] | Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for the given query name in the given URL or
an empty string if the query is not i... | [
"Given",
"a",
"URL",
"(",
"ex",
":",
"http",
":",
"//",
"www",
".",
"test",
".",
"com",
"/",
"path?query",
"=",
"3",
")",
"and",
"a",
"parameter",
"(",
"ex",
":",
"query",
")",
"return",
"the",
"value",
"as",
"a",
"list",
":",
"param",
"url",
"... | train | https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L207-L216 |
kennydo/nyaalib | nyaalib/__init__.py | NyaaClient._get_page_content | def _get_page_content(self, response):
"""Given a :class:`requests.Response`, return the
:class:`xml.etree.Element` of the content `div`.
:param response: a :class:`requests.Response` to parse
:returns: the :class:`Element` of the first content `div` or `None`
"""
docume... | python | def _get_page_content(self, response):
"""Given a :class:`requests.Response`, return the
:class:`xml.etree.Element` of the content `div`.
:param response: a :class:`requests.Response` to parse
:returns: the :class:`Element` of the first content `div` or `None`
"""
docume... | [
"def",
"_get_page_content",
"(",
"self",
",",
"response",
")",
":",
"document",
"=",
"html5lib",
".",
"parse",
"(",
"response",
".",
"content",
",",
"encoding",
"=",
"response",
".",
"encoding",
",",
"treebuilder",
"=",
"'etree'",
",",
"namespaceHTMLElements",... | Given a :class:`requests.Response`, return the
:class:`xml.etree.Element` of the content `div`.
:param response: a :class:`requests.Response` to parse
:returns: the :class:`Element` of the first content `div` or `None` | [
"Given",
"a",
":",
"class",
":",
"requests",
".",
"Response",
"return",
"the",
":",
"class",
":",
"xml",
".",
"etree",
".",
"Element",
"of",
"the",
"content",
"div",
"."
] | train | https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L38-L65 |
kennydo/nyaalib | nyaalib/__init__.py | NyaaClient.view_torrent | def view_torrent(self, torrent_id):
"""Retrieves and parses the torrent page for a given `torrent_id`.
:param torrent_id: the ID of the torrent to view
:raises TorrentNotFoundError: if the torrent does not exist
:returns: a :class:`TorrentPage` with a snapshot view of the torrent
... | python | def view_torrent(self, torrent_id):
"""Retrieves and parses the torrent page for a given `torrent_id`.
:param torrent_id: the ID of the torrent to view
:raises TorrentNotFoundError: if the torrent does not exist
:returns: a :class:`TorrentPage` with a snapshot view of the torrent
... | [
"def",
"view_torrent",
"(",
"self",
",",
"torrent_id",
")",
":",
"params",
"=",
"{",
"'page'",
":",
"'view'",
",",
"'tid'",
":",
"torrent_id",
",",
"}",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base_url",
",",
"params",
"=",
"params",
")"... | Retrieves and parses the torrent page for a given `torrent_id`.
:param torrent_id: the ID of the torrent to view
:raises TorrentNotFoundError: if the torrent does not exist
:returns: a :class:`TorrentPage` with a snapshot view of the torrent
detail page | [
"Retrieves",
"and",
"parses",
"the",
"torrent",
"page",
"for",
"a",
"given",
"torrent_id",
"."
] | train | https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L67-L122 |
kennydo/nyaalib | nyaalib/__init__.py | NyaaClient.get_torrent | def get_torrent(self, torrent_id):
"""Gets the `.torrent` data for the given `torrent_id`.
:param torrent_id: the ID of the torrent to download
:raises TorrentNotFoundError: if the torrent does not exist
:returns: :class:`Torrent` of the associated torrent
"""
params = {... | python | def get_torrent(self, torrent_id):
"""Gets the `.torrent` data for the given `torrent_id`.
:param torrent_id: the ID of the torrent to download
:raises TorrentNotFoundError: if the torrent does not exist
:returns: :class:`Torrent` of the associated torrent
"""
params = {... | [
"def",
"get_torrent",
"(",
"self",
",",
"torrent_id",
")",
":",
"params",
"=",
"{",
"'page'",
":",
"'download'",
",",
"'tid'",
":",
"torrent_id",
",",
"}",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base_url",
",",
"params",
"=",
"params",
... | Gets the `.torrent` data for the given `torrent_id`.
:param torrent_id: the ID of the torrent to download
:raises TorrentNotFoundError: if the torrent does not exist
:returns: :class:`Torrent` of the associated torrent | [
"Gets",
"the",
".",
"torrent",
"data",
"for",
"the",
"given",
"torrent_id",
"."
] | train | https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L124-L139 |
kennydo/nyaalib | nyaalib/__init__.py | NyaaClient.search | def search(self, terms, category=Category.all_categories, page=1,
sort_key=SearchSortKey.date,
order_key=SearchOrderKey.descending):
"""Get a list of torrents that match the given search term
:param terms: the `str` needle
:param category: the desired :class:`Categ... | python | def search(self, terms, category=Category.all_categories, page=1,
sort_key=SearchSortKey.date,
order_key=SearchOrderKey.descending):
"""Get a list of torrents that match the given search term
:param terms: the `str` needle
:param category: the desired :class:`Categ... | [
"def",
"search",
"(",
"self",
",",
"terms",
",",
"category",
"=",
"Category",
".",
"all_categories",
",",
"page",
"=",
"1",
",",
"sort_key",
"=",
"SearchSortKey",
".",
"date",
",",
"order_key",
"=",
"SearchOrderKey",
".",
"descending",
")",
":",
"params",
... | Get a list of torrents that match the given search term
:param terms: the `str` needle
:param category: the desired :class:`Category` of the results
:param page: the 1-based page to return the result
:param sort_key: the :class:`SearchSortKey` of the results list
:param order_ke... | [
"Get",
"a",
"list",
"of",
"torrents",
"that",
"match",
"the",
"given",
"search",
"term"
] | train | https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L141-L204 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/grada_cz.py | _parse_alt_title | def _parse_alt_title(html_chunk):
"""
Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
"""
title = html_chunk.find(
"input",
{"src": ... | python | def _parse_alt_title(html_chunk):
"""
Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
"""
title = html_chunk.find(
"input",
{"src": ... | [
"def",
"_parse_alt_title",
"(",
"html_chunk",
")",
":",
"title",
"=",
"html_chunk",
".",
"find",
"(",
"\"input\"",
",",
"{",
"\"src\"",
":",
"\"../images_buttons/objednat_off.gif\"",
"}",
")",
"assert",
"title",
",",
"\"Can't find alternative title!\"",
"title",
"="... | Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title. | [
"Parse",
"title",
"from",
"alternative",
"location",
"if",
"not",
"found",
"where",
"it",
"should",
"be",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L27-L51 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/grada_cz.py | _parse_title_url | def _parse_title_url(html_chunk):
"""
Parse title/name of the book and URL of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (title, url), both as strings.
"""
title = html_chunk.find("div", {"class": "comment"})
if... | python | def _parse_title_url(html_chunk):
"""
Parse title/name of the book and URL of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (title, url), both as strings.
"""
title = html_chunk.find("div", {"class": "comment"})
if... | [
"def",
"_parse_title_url",
"(",
"html_chunk",
")",
":",
"title",
"=",
"html_chunk",
".",
"find",
"(",
"\"div\"",
",",
"{",
"\"class\"",
":",
"\"comment\"",
"}",
")",
"if",
"not",
"title",
":",
"return",
"_parse_alt_title",
"(",
"html_chunk",
")",
",",
"Non... | Parse title/name of the book and URL of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (title, url), both as strings. | [
"Parse",
"title",
"/",
"name",
"of",
"the",
"book",
"and",
"URL",
"of",
"the",
"book",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L54-L80 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/grada_cz.py | _parse_authors | def _parse_authors(html_chunk):
"""
Parse authors of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found.
"""
authors = html_chunk.match(
... | python | def _parse_authors(html_chunk):
"""
Parse authors of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found.
"""
authors = html_chunk.match(
... | [
"def",
"_parse_authors",
"(",
"html_chunk",
")",
":",
"authors",
"=",
"html_chunk",
".",
"match",
"(",
"[",
"\"div\"",
",",
"{",
"\"class\"",
":",
"\"comment\"",
"}",
"]",
",",
"\"h3\"",
",",
"\"a\"",
",",
")",
"if",
"not",
"authors",
":",
"return",
"[... | Parse authors of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found. | [
"Parse",
"authors",
"of",
"the",
"book",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L102-L130 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/grada_cz.py | _parse_format_pages_isbn | def _parse_format_pages_isbn(html_chunk):
"""
Parse format, number of pages and ISBN.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (format, pages, isbn), all as string.
"""
ppi = get_first_content(
html_chunk.find("div",... | python | def _parse_format_pages_isbn(html_chunk):
"""
Parse format, number of pages and ISBN.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (format, pages, isbn), all as string.
"""
ppi = get_first_content(
html_chunk.find("div",... | [
"def",
"_parse_format_pages_isbn",
"(",
"html_chunk",
")",
":",
"ppi",
"=",
"get_first_content",
"(",
"html_chunk",
".",
"find",
"(",
"\"div\"",
",",
"{",
"\"class\"",
":",
"\"price-overflow\"",
"}",
")",
")",
"if",
"not",
"ppi",
":",
"return",
"None",
",",
... | Parse format, number of pages and ISBN.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (format, pages, isbn), all as string. | [
"Parse",
"format",
"number",
"of",
"pages",
"and",
"ISBN",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L148-L182 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/grada_cz.py | _parse_price | def _parse_price(html_chunk):
"""
Parse price of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Price as string with currency or None if not found.
"""
price = get_first_content(
html_chunk.find("div", {"class... | python | def _parse_price(html_chunk):
"""
Parse price of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Price as string with currency or None if not found.
"""
price = get_first_content(
html_chunk.find("div", {"class... | [
"def",
"_parse_price",
"(",
"html_chunk",
")",
":",
"price",
"=",
"get_first_content",
"(",
"html_chunk",
".",
"find",
"(",
"\"div\"",
",",
"{",
"\"class\"",
":",
"\"prices\"",
"}",
")",
")",
"if",
"not",
"price",
":",
"return",
"None",
"# it is always in fo... | Parse price of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Price as string with currency or None if not found. | [
"Parse",
"price",
"of",
"the",
"book",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L185-L206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.