repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
GaretJax/lancet
lancet/timer.py
credentials_checker
def credentials_checker(url, username, password): """Check the provided credentials using the Harvest API.""" api = HarvestAPI(url, (username, password)) try: api.whoami() except HarvestError: return False else: return True
python
def credentials_checker(url, username, password): """Check the provided credentials using the Harvest API.""" api = HarvestAPI(url, (username, password)) try: api.whoami() except HarvestError: return False else: return True
[ "def", "credentials_checker", "(", "url", ",", "username", ",", "password", ")", ":", "api", "=", "HarvestAPI", "(", "url", ",", "(", "username", ",", "password", ")", ")", "try", ":", "api", ".", "whoami", "(", ")", "except", "HarvestError", ":", "ret...
Check the provided credentials using the Harvest API.
[ "Check", "the", "provided", "credentials", "using", "the", "Harvest", "API", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/timer.py#L219-L227
train
GaretJax/lancet
lancet/timer.py
harvest
def harvest(lancet, config_section): """Construct a new Harvest client.""" url, username, password = lancet.get_credentials( config_section, credentials_checker ) project_id_getter = lancet.get_instance_from_config( "timer", "project_id_getter", lancet ) task_id_getter = lancet....
python
def harvest(lancet, config_section): """Construct a new Harvest client.""" url, username, password = lancet.get_credentials( config_section, credentials_checker ) project_id_getter = lancet.get_instance_from_config( "timer", "project_id_getter", lancet ) task_id_getter = lancet....
[ "def", "harvest", "(", "lancet", ",", "config_section", ")", ":", "url", ",", "username", ",", "password", "=", "lancet", ".", "get_credentials", "(", "config_section", ",", "credentials_checker", ")", "project_id_getter", "=", "lancet", ".", "get_instance_from_co...
Construct a new Harvest client.
[ "Construct", "a", "new", "Harvest", "client", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/timer.py#L230-L250
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/path.py
temp_dir
def temp_dir(folder=None, delete=True): # type: (Optional[str], bool) -> str """Get a temporary directory optionally with folder appended (and created if it doesn't exist) Args: folder (Optional[str]): Folder to create in temporary folder. Defaults to None. delete (bool): Whether to delete ...
python
def temp_dir(folder=None, delete=True): # type: (Optional[str], bool) -> str """Get a temporary directory optionally with folder appended (and created if it doesn't exist) Args: folder (Optional[str]): Folder to create in temporary folder. Defaults to None. delete (bool): Whether to delete ...
[ "def", "temp_dir", "(", "folder", "=", "None", ",", "delete", "=", "True", ")", ":", "# type: (Optional[str], bool) -> str", "tempdir", "=", "get_temp_dir", "(", ")", "if", "folder", ":", "tempdir", "=", "join", "(", "tempdir", ",", "folder", ")", "if", "n...
Get a temporary directory optionally with folder appended (and created if it doesn't exist) Args: folder (Optional[str]): Folder to create in temporary folder. Defaults to None. delete (bool): Whether to delete folder on exiting with statement Returns: str: A temporary directory
[ "Get", "a", "temporary", "directory", "optionally", "with", "folder", "appended", "(", "and", "created", "if", "it", "doesn", "t", "exist", ")" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/path.py#L60-L80
train
martinkou/applepushnotification
applepushnotification/service.py
NotificationService.send
def send(self, obj): """Send a push notification""" if not isinstance(obj, NotificationMessage): raise ValueError, u"You can only send NotificationMessage objects." self._send_queue.put(obj)
python
def send(self, obj): """Send a push notification""" if not isinstance(obj, NotificationMessage): raise ValueError, u"You can only send NotificationMessage objects." self._send_queue.put(obj)
[ "def", "send", "(", "self", ",", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "NotificationMessage", ")", ":", "raise", "ValueError", ",", "u\"You can only send NotificationMessage objects.\"", "self", ".", "_send_queue", ".", "put", "(", "obj", ...
Send a push notification
[ "Send", "a", "push", "notification" ]
43ebe5963fa9c48990dd57f6aaba6056a1e7470f
https://github.com/martinkou/applepushnotification/blob/43ebe5963fa9c48990dd57f6aaba6056a1e7470f/applepushnotification/service.py#L156-L160
train
martinkou/applepushnotification
applepushnotification/service.py
NotificationService.get_error
def get_error(self, block = True, timeout = None): """ Gets the next error message. Each error message is a 2-tuple of (status, identifier).""" return self._error_queue.get(block = block, timeout = timeout)
python
def get_error(self, block = True, timeout = None): """ Gets the next error message. Each error message is a 2-tuple of (status, identifier).""" return self._error_queue.get(block = block, timeout = timeout)
[ "def", "get_error", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_error_queue", ".", "get", "(", "block", "=", "block", ",", "timeout", "=", "timeout", ")" ]
Gets the next error message. Each error message is a 2-tuple of (status, identifier).
[ "Gets", "the", "next", "error", "message", ".", "Each", "error", "message", "is", "a", "2", "-", "tuple", "of", "(", "status", "identifier", ")", "." ]
43ebe5963fa9c48990dd57f6aaba6056a1e7470f
https://github.com/martinkou/applepushnotification/blob/43ebe5963fa9c48990dd57f6aaba6056a1e7470f/applepushnotification/service.py#L162-L167
train
martinkou/applepushnotification
applepushnotification/service.py
NotificationService.get_feedback
def get_feedback(self, block = True, timeout = None): """ Gets the next feedback message. Each feedback message is a 2-tuple of (timestamp, device_token).""" if self._feedback_greenlet is None: self._feedback_greenlet = gevent.spawn(self._feedback_loop) return self._feedback_queue.get(block = block, timeo...
python
def get_feedback(self, block = True, timeout = None): """ Gets the next feedback message. Each feedback message is a 2-tuple of (timestamp, device_token).""" if self._feedback_greenlet is None: self._feedback_greenlet = gevent.spawn(self._feedback_loop) return self._feedback_queue.get(block = block, timeo...
[ "def", "get_feedback", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_feedback_greenlet", "is", "None", ":", "self", ".", "_feedback_greenlet", "=", "gevent", ".", "spawn", "(", "self", ".", "_feedback...
Gets the next feedback message. Each feedback message is a 2-tuple of (timestamp, device_token).
[ "Gets", "the", "next", "feedback", "message", "." ]
43ebe5963fa9c48990dd57f6aaba6056a1e7470f
https://github.com/martinkou/applepushnotification/blob/43ebe5963fa9c48990dd57f6aaba6056a1e7470f/applepushnotification/service.py#L169-L176
train
martinkou/applepushnotification
applepushnotification/service.py
NotificationService.wait_send
def wait_send(self, timeout = None): """Wait until all queued messages are sent.""" self._send_queue_cleared.clear() self._send_queue_cleared.wait(timeout = timeout)
python
def wait_send(self, timeout = None): """Wait until all queued messages are sent.""" self._send_queue_cleared.clear() self._send_queue_cleared.wait(timeout = timeout)
[ "def", "wait_send", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_send_queue_cleared", ".", "clear", "(", ")", "self", ".", "_send_queue_cleared", ".", "wait", "(", "timeout", "=", "timeout", ")" ]
Wait until all queued messages are sent.
[ "Wait", "until", "all", "queued", "messages", "are", "sent", "." ]
43ebe5963fa9c48990dd57f6aaba6056a1e7470f
https://github.com/martinkou/applepushnotification/blob/43ebe5963fa9c48990dd57f6aaba6056a1e7470f/applepushnotification/service.py#L178-L181
train
martinkou/applepushnotification
applepushnotification/service.py
NotificationService.start
def start(self): """Start the message sending loop.""" if self._send_greenlet is None: self._send_greenlet = gevent.spawn(self._send_loop)
python
def start(self): """Start the message sending loop.""" if self._send_greenlet is None: self._send_greenlet = gevent.spawn(self._send_loop)
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "_send_greenlet", "is", "None", ":", "self", ".", "_send_greenlet", "=", "gevent", ".", "spawn", "(", "self", ".", "_send_loop", ")" ]
Start the message sending loop.
[ "Start", "the", "message", "sending", "loop", "." ]
43ebe5963fa9c48990dd57f6aaba6056a1e7470f
https://github.com/martinkou/applepushnotification/blob/43ebe5963fa9c48990dd57f6aaba6056a1e7470f/applepushnotification/service.py#L183-L186
train
martinkou/applepushnotification
applepushnotification/service.py
NotificationService.stop
def stop(self, timeout = 10.0): """ Send all pending messages, close connection. Returns True if no message left to sent. False if dirty. - timeout: seconds to wait for sending remaining messages. disconnect immedately if None. """ if (self._send_greenlet is not None) and \ (self._send_queue.qsiz...
python
def stop(self, timeout = 10.0): """ Send all pending messages, close connection. Returns True if no message left to sent. False if dirty. - timeout: seconds to wait for sending remaining messages. disconnect immedately if None. """ if (self._send_greenlet is not None) and \ (self._send_queue.qsiz...
[ "def", "stop", "(", "self", ",", "timeout", "=", "10.0", ")", ":", "if", "(", "self", ".", "_send_greenlet", "is", "not", "None", ")", "and", "(", "self", ".", "_send_queue", ".", "qsize", "(", ")", ">", "0", ")", ":", "self", ".", "wait_send", "...
Send all pending messages, close connection. Returns True if no message left to sent. False if dirty. - timeout: seconds to wait for sending remaining messages. disconnect immedately if None.
[ "Send", "all", "pending", "messages", "close", "connection", ".", "Returns", "True", "if", "no", "message", "left", "to", "sent", ".", "False", "if", "dirty", ".", "-", "timeout", ":", "seconds", "to", "wait", "for", "sending", "remaining", "messages", "."...
43ebe5963fa9c48990dd57f6aaba6056a1e7470f
https://github.com/martinkou/applepushnotification/blob/43ebe5963fa9c48990dd57f6aaba6056a1e7470f/applepushnotification/service.py#L188-L210
train
nbedi/typecaster
typecaster/ssml.py
convert_to_ssml
def convert_to_ssml(text, text_format): """ Convert text to SSML based on the text's current format. NOTE: This module is extremely limited at the moment and will be expanded. :param text: The text to convert. :param text_format: The text format of the text. Currently supports 'plai...
python
def convert_to_ssml(text, text_format): """ Convert text to SSML based on the text's current format. NOTE: This module is extremely limited at the moment and will be expanded. :param text: The text to convert. :param text_format: The text format of the text. Currently supports 'plai...
[ "def", "convert_to_ssml", "(", "text", ",", "text_format", ")", ":", "if", "text_format", "is", "None", ":", "return", "text", "elif", "text_format", "==", "'plain'", ":", "return", "plain_to_ssml", "(", "text", ")", "elif", "text_format", "==", "'html'", ":...
Convert text to SSML based on the text's current format. NOTE: This module is extremely limited at the moment and will be expanded. :param text: The text to convert. :param text_format: The text format of the text. Currently supports 'plain', 'html' or None for skipping SSML convers...
[ "Convert", "text", "to", "SSML", "based", "on", "the", "text", "s", "current", "format", ".", "NOTE", ":", "This", "module", "is", "extremely", "limited", "at", "the", "moment", "and", "will", "be", "expanded", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/ssml.py#L19-L37
train
nbedi/typecaster
typecaster/ssml.py
html_to_ssml
def html_to_ssml(text): """ Replaces specific html tags with probable SSML counterparts. """ ssml_text = reduce(lambda x, y: x.replace(y, html_to_ssml_maps[y]), html_to_ssml_maps, text) return ssml_text
python
def html_to_ssml(text): """ Replaces specific html tags with probable SSML counterparts. """ ssml_text = reduce(lambda x, y: x.replace(y, html_to_ssml_maps[y]), html_to_ssml_maps, text) return ssml_text
[ "def", "html_to_ssml", "(", "text", ")", ":", "ssml_text", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", ".", "replace", "(", "y", ",", "html_to_ssml_maps", "[", "y", "]", ")", ",", "html_to_ssml_maps", ",", "text", ")", "return", "ssml_text" ...
Replaces specific html tags with probable SSML counterparts.
[ "Replaces", "specific", "html", "tags", "with", "probable", "SSML", "counterparts", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/ssml.py#L48-L53
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/text.py
multiple_replace
def multiple_replace(string, replacements): # type: (str, Dict[str,str]) -> str """Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements """ patt...
python
def multiple_replace(string, replacements): # type: (str, Dict[str,str]) -> str """Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements """ patt...
[ "def", "multiple_replace", "(", "string", ",", "replacements", ")", ":", "# type: (str, Dict[str,str]) -> str", "pattern", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "[", "re", ".", "escape", "(", "k", ")", "for", "k", "in", "sorted", "(", ...
Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements
[ "Simultaneously", "replace", "multiple", "strigns", "in", "a", "string" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/text.py#L9-L22
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/text.py
get_matching_text_in_strs
def get_matching_text_in_strs(a, b, match_min_size=30, ignore='', end_characters=''): # type: (str, str, int, str, str) -> List[str] """Returns a list of matching blocks of text in a and b Args: a (str): First string to match b (str): Second string to match match_min_size (int): Min...
python
def get_matching_text_in_strs(a, b, match_min_size=30, ignore='', end_characters=''): # type: (str, str, int, str, str) -> List[str] """Returns a list of matching blocks of text in a and b Args: a (str): First string to match b (str): Second string to match match_min_size (int): Min...
[ "def", "get_matching_text_in_strs", "(", "a", ",", "b", ",", "match_min_size", "=", "30", ",", "ignore", "=", "''", ",", "end_characters", "=", "''", ")", ":", "# type: (str, str, int, str, str) -> List[str]", "compare", "=", "difflib", ".", "SequenceMatcher", "("...
Returns a list of matching blocks of text in a and b Args: a (str): First string to match b (str): Second string to match match_min_size (int): Minimum block size to match on. Defaults to 30. ignore (str): Any characters to ignore in matching. Defaults to ''. end_characters ...
[ "Returns", "a", "list", "of", "matching", "blocks", "of", "text", "in", "a", "and", "b" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/text.py#L39-L71
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/text.py
get_matching_text
def get_matching_text(string_list, match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match ...
python
def get_matching_text(string_list, match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match ...
[ "def", "get_matching_text", "(", "string_list", ",", "match_min_size", "=", "30", ",", "ignore", "=", "''", ",", "end_characters", "=", "'.!\\r\\n'", ")", ":", "# type: (List[str], int, str, str) -> str", "a", "=", "string_list", "[", "0", "]", "for", "i", "in",...
Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match match_min_size (int): Minimum block size to match on. Defaults to 30. ignore (str): Any characters to ignore in matching. Defaults to ''...
[ "Returns", "a", "string", "containing", "matching", "blocks", "of", "text", "in", "a", "list", "of", "strings", "followed", "by", "non", "-", "matching", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/text.py#L74-L94
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/text.py
get_matching_then_nonmatching_text
def get_matching_then_nonmatching_text(string_list, separator='', match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], str, int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. ...
python
def get_matching_then_nonmatching_text(string_list, separator='', match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], str, int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. ...
[ "def", "get_matching_then_nonmatching_text", "(", "string_list", ",", "separator", "=", "''", ",", "match_min_size", "=", "30", ",", "ignore", "=", "''", ",", "end_characters", "=", "'.!\\r\\n'", ")", ":", "# type: (List[str], str, int, str, str) -> str", "def", "add_...
Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match separator (str): Separator to add between blocks of text. Defaults to ''. match_min_size (int): Minimum block size to match on. Defaults...
[ "Returns", "a", "string", "containing", "matching", "blocks", "of", "text", "in", "a", "list", "of", "strings", "followed", "by", "non", "-", "matching", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/text.py#L97-L168
train
facelessuser/bracex
bracex/__init__.py
iexpand
def iexpand(string, keep_escapes=False): """Expand braces and return an iterator.""" if isinstance(string, bytes): is_bytes = True string = string.decode('latin-1') else: is_bytes = False if is_bytes: return (entry.encode('latin-1') for entry in ExpandBrace(keep_escape...
python
def iexpand(string, keep_escapes=False): """Expand braces and return an iterator.""" if isinstance(string, bytes): is_bytes = True string = string.decode('latin-1') else: is_bytes = False if is_bytes: return (entry.encode('latin-1') for entry in ExpandBrace(keep_escape...
[ "def", "iexpand", "(", "string", ",", "keep_escapes", "=", "False", ")", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "is_bytes", "=", "True", "string", "=", "string", ".", "decode", "(", "'latin-1'", ")", "else", ":", "is_bytes", "=...
Expand braces and return an iterator.
[ "Expand", "braces", "and", "return", "an", "iterator", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L50-L64
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.set_expanding
def set_expanding(self): """Set that we are expanding a sequence, and return whether a release is required by the caller.""" status = not self.expanding if status: self.expanding = True return status
python
def set_expanding(self): """Set that we are expanding a sequence, and return whether a release is required by the caller.""" status = not self.expanding if status: self.expanding = True return status
[ "def", "set_expanding", "(", "self", ")", ":", "status", "=", "not", "self", ".", "expanding", "if", "status", ":", "self", ".", "expanding", "=", "True", "return", "status" ]
Set that we are expanding a sequence, and return whether a release is required by the caller.
[ "Set", "that", "we", "are", "expanding", "a", "sequence", "and", "return", "whether", "a", "release", "is", "required", "by", "the", "caller", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L140-L146
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.get_escape
def get_escape(self, c, i): """Get an escape.""" try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
python
def get_escape(self, c, i): """Get an escape.""" try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
[ "def", "get_escape", "(", "self", ",", "c", ",", "i", ")", ":", "try", ":", "escaped", "=", "next", "(", "i", ")", "except", "StopIteration", ":", "escaped", "=", "''", "return", "c", "+", "escaped", "if", "self", ".", "keep_escapes", "else", "escape...
Get an escape.
[ "Get", "an", "escape", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L159-L166
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.squash
def squash(self, a, b): """ Returns a generator that squashes two iterables into one. ``` ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or'] ``` """ return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product...
python
def squash(self, a, b): """ Returns a generator that squashes two iterables into one. ``` ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or'] ``` """ return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product...
[ "def", "squash", "(", "self", ",", "a", ",", "b", ")", ":", "return", "(", "(", "''", ".", "join", "(", "x", ")", "if", "isinstance", "(", "x", ",", "tuple", ")", "else", "x", ")", "for", "x", "in", "itertools", ".", "product", "(", "a", ",",...
Returns a generator that squashes two iterables into one. ``` ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or'] ```
[ "Returns", "a", "generator", "that", "squashes", "two", "iterables", "into", "one", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L168-L177
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.get_literals
def get_literals(self, c, i, depth): """ Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). """ result = [''] is_dollar = False try: ...
python
def get_literals(self, c, i, depth): """ Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). """ result = [''] is_dollar = False try: ...
[ "def", "get_literals", "(", "self", ",", "c", ",", "i", ",", "depth", ")", ":", "result", "=", "[", "''", "]", "is_dollar", "=", "False", "try", ":", "while", "c", ":", "ignore_brace", "=", "is_dollar", "is_dollar", "=", "False", "if", "c", "==", "...
Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding).
[ "Get", "a", "string", "literal", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L179-L227
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.combine
def combine(self, a, b): """A generator that combines two iterables.""" for l in (a, b): for x in l: yield x
python
def combine(self, a, b): """A generator that combines two iterables.""" for l in (a, b): for x in l: yield x
[ "def", "combine", "(", "self", ",", "a", ",", "b", ")", ":", "for", "l", "in", "(", "a", ",", "b", ")", ":", "for", "x", "in", "l", ":", "yield", "x" ]
A generator that combines two iterables.
[ "A", "generator", "that", "combines", "two", "iterables", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L229-L234
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.get_sequence
def get_sequence(self, c, i, depth): """ Get the sequence. Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc. It will basically crawl to the end or find a valid series. """ result = [] release = self.set_expanding() has_comma = False # U...
python
def get_sequence(self, c, i, depth): """ Get the sequence. Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc. It will basically crawl to the end or find a valid series. """ result = [] release = self.set_expanding() has_comma = False # U...
[ "def", "get_sequence", "(", "self", ",", "c", ",", "i", ",", "depth", ")", ":", "result", "=", "[", "]", "release", "=", "self", ".", "set_expanding", "(", ")", "has_comma", "=", "False", "# Used to indicate validity of group (`{1..2}` are an exception).", "is_e...
Get the sequence. Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc. It will basically crawl to the end or find a valid series.
[ "Get", "the", "sequence", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L236-L303
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.get_range
def get_range(self, i): """ Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine). """ try: m = i.match(RE_INT_ITER) ...
python
def get_range(self, i): """ Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine). """ try: m = i.match(RE_INT_ITER) ...
[ "def", "get_range", "(", "self", ",", "i", ")", ":", "try", ":", "m", "=", "i", ".", "match", "(", "RE_INT_ITER", ")", "if", "m", ":", "return", "self", ".", "get_int_range", "(", "*", "m", ".", "groups", "(", ")", ")", "m", "=", "i", ".", "m...
Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine).
[ "Check", "and", "retrieve", "range", "if", "value", "is", "a", "valid", "range", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L305-L328
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.format_value
def format_value(self, value, padding): """Get padding adjusting for negative values.""" # padding = padding - 1 if value < 0 and padding > 0 else padding # prefix = '-' if value < 0 else '' if padding: return "{:0{pad}d}".format(value, pad=padding) else: ...
python
def format_value(self, value, padding): """Get padding adjusting for negative values.""" # padding = padding - 1 if value < 0 and padding > 0 else padding # prefix = '-' if value < 0 else '' if padding: return "{:0{pad}d}".format(value, pad=padding) else: ...
[ "def", "format_value", "(", "self", ",", "value", ",", "padding", ")", ":", "# padding = padding - 1 if value < 0 and padding > 0 else padding", "# prefix = '-' if value < 0 else ''", "if", "padding", ":", "return", "\"{:0{pad}d}\"", ".", "format", "(", "value", ",", "pad...
Get padding adjusting for negative values.
[ "Get", "padding", "adjusting", "for", "negative", "values", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L330-L340
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.get_int_range
def get_int_range(self, start, end, increment=None): """Get an integer range between start and end and increments of increment.""" first, last = int(start), int(end) increment = int(increment) if increment is not None else 1 max_length = max(len(start), len(end)) # Zero doesn't...
python
def get_int_range(self, start, end, increment=None): """Get an integer range between start and end and increments of increment.""" first, last = int(start), int(end) increment = int(increment) if increment is not None else 1 max_length = max(len(start), len(end)) # Zero doesn't...
[ "def", "get_int_range", "(", "self", ",", "start", ",", "end", ",", "increment", "=", "None", ")", ":", "first", ",", "last", "=", "int", "(", "start", ")", ",", "int", "(", "end", ")", "increment", "=", "int", "(", "increment", ")", "if", "increme...
Get an integer range between start and end and increments of increment.
[ "Get", "an", "integer", "range", "between", "start", "and", "end", "and", "increments", "of", "increment", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L342-L372
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.get_char_range
def get_char_range(self, start, end, increment=None): """Get a range of alphabetic characters.""" increment = int(increment) if increment else 1 if increment < 0: increment = -increment # Zero doesn't make sense as an incrementer # but like bash, just assume one ...
python
def get_char_range(self, start, end, increment=None): """Get a range of alphabetic characters.""" increment = int(increment) if increment else 1 if increment < 0: increment = -increment # Zero doesn't make sense as an incrementer # but like bash, just assume one ...
[ "def", "get_char_range", "(", "self", ",", "start", ",", "end", ",", "increment", "=", "None", ")", ":", "increment", "=", "int", "(", "increment", ")", "if", "increment", "else", "1", "if", "increment", "<", "0", ":", "increment", "=", "-", "increment...
Get a range of alphabetic characters.
[ "Get", "a", "range", "of", "alphabetic", "characters", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L374-L396
train
facelessuser/bracex
bracex/__init__.py
ExpandBrace.expand
def expand(self, string): """Expand.""" self.expanding = False empties = [] found_literal = False if string: i = iter(StringIter(string)) for x in self.get_literals(next(i), i, 0): # We don't want to return trailing empty strings. ...
python
def expand(self, string): """Expand.""" self.expanding = False empties = [] found_literal = False if string: i = iter(StringIter(string)) for x in self.get_literals(next(i), i, 0): # We don't want to return trailing empty strings. ...
[ "def", "expand", "(", "self", ",", "string", ")", ":", "self", ".", "expanding", "=", "False", "empties", "=", "[", "]", "found_literal", "=", "False", "if", "string", ":", "i", "=", "iter", "(", "StringIter", "(", "string", ")", ")", "for", "x", "...
Expand.
[ "Expand", "." ]
1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L398-L420
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
merge_two_dictionaries
def merge_two_dictionaries(a, b, merge_lists=False): # type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound """Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictiona...
python
def merge_two_dictionaries(a, b, merge_lists=False): # type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound """Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictiona...
[ "def", "merge_two_dictionaries", "(", "a", ",", "b", ",", "merge_lists", "=", "False", ")", ":", "# type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound", "key", "=", "None", "# ## debug output", "# sys.stderr.write('DEBUG: %s to %s\\n' %(b,a))", "try", ":", "if", ...
Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictionary to merge into b (DictUpperBound): dictionary to merge from merge_lists (bool): Whether to merge lists (True) o...
[ "Merges", "b", "into", "a", "and", "returns", "merged", "result" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L16-L63
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
merge_dictionaries
def merge_dictionaries(dicts, merge_lists=False): # type: (List[DictUpperBound], bool) -> DictUpperBound """Merges all dictionaries in dicts into a single dictionary and returns result Args: dicts (List[DictUpperBound]): Dictionaries to merge into the first one in the list merge_lists (bool...
python
def merge_dictionaries(dicts, merge_lists=False): # type: (List[DictUpperBound], bool) -> DictUpperBound """Merges all dictionaries in dicts into a single dictionary and returns result Args: dicts (List[DictUpperBound]): Dictionaries to merge into the first one in the list merge_lists (bool...
[ "def", "merge_dictionaries", "(", "dicts", ",", "merge_lists", "=", "False", ")", ":", "# type: (List[DictUpperBound], bool) -> DictUpperBound", "dict1", "=", "dicts", "[", "0", "]", "for", "other_dict", "in", "dicts", "[", "1", ":", "]", ":", "merge_two_dictionar...
Merges all dictionaries in dicts into a single dictionary and returns result Args: dicts (List[DictUpperBound]): Dictionaries to merge into the first one in the list merge_lists (bool): Whether to merge lists (True) or replace lists (False). Default is False. Returns: DictUpperBound: M...
[ "Merges", "all", "dictionaries", "in", "dicts", "into", "a", "single", "dictionary", "and", "returns", "result" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L66-L81
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
dict_diff
def dict_diff(d1, d2, no_key='<KEYNOTFOUND>'): # type: (DictUpperBound, DictUpperBound, str) -> Dict """Compares two dictionaries Args: d1 (DictUpperBound): First dictionary to compare d2 (DictUpperBound): Second dictionary to compare no_key (str): What value to use if key is not fo...
python
def dict_diff(d1, d2, no_key='<KEYNOTFOUND>'): # type: (DictUpperBound, DictUpperBound, str) -> Dict """Compares two dictionaries Args: d1 (DictUpperBound): First dictionary to compare d2 (DictUpperBound): Second dictionary to compare no_key (str): What value to use if key is not fo...
[ "def", "dict_diff", "(", "d1", ",", "d2", ",", "no_key", "=", "'<KEYNOTFOUND>'", ")", ":", "# type: (DictUpperBound, DictUpperBound, str) -> Dict", "d1keys", "=", "set", "(", "d1", ".", "keys", "(", ")", ")", "d2keys", "=", "set", "(", "d2", ".", "keys", "...
Compares two dictionaries Args: d1 (DictUpperBound): First dictionary to compare d2 (DictUpperBound): Second dictionary to compare no_key (str): What value to use if key is not found Defaults to '<KEYNOTFOUND>'. Returns: Dict: Comparison dictionary
[ "Compares", "two", "dictionaries" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L84-L103
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
dict_of_lists_add
def dict_of_lists_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictiona...
python
def dict_of_lists_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictiona...
[ "def", "dict_of_lists_add", "(", "dictionary", ",", "key", ",", "value", ")", ":", "# type: (DictUpperBound, Any, Any) -> None", "list_objs", "=", "dictionary", ".", "get", "(", "key", ",", "list", "(", ")", ")", "list_objs", ".", "append", "(", "value", ")", ...
Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictionary Returns: None
[ "Add", "value", "to", "a", "list", "in", "a", "dictionary", "by", "key" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L106-L121
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
dict_of_sets_add
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary ...
python
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary ...
[ "def", "dict_of_sets_add", "(", "dictionary", ",", "key", ",", "value", ")", ":", "# type: (DictUpperBound, Any, Any) -> None", "set_objs", "=", "dictionary", ".", "get", "(", "key", ",", "set", "(", ")", ")", "set_objs", ".", "add", "(", "value", ")", "dict...
Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None
[ "Add", "value", "to", "a", "set", "in", "a", "dictionary", "by", "key" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L124-L139
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
list_distribute_contents_simple
def list_distribute_contents_simple(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case the function can return the appropriate value ...
python
def list_distribute_contents_simple(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case the function can return the appropriate value ...
[ "def", "list_distribute_contents_simple", "(", "input_list", ",", "function", "=", "lambda", "x", ":", "x", ")", ":", "# type: (List, Callable[[Any], Any]) -> List", "dictionary", "=", "dict", "(", ")", "for", "obj", "in", "input_list", ":", "dict_of_lists_add", "("...
Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. lambda x: x[KEY] Args: input_list (List): List to distribute values function (Callable[[Any], Any]): ...
[ "Distribute", "the", "contents", "of", "a", "list", "eg", ".", "[", "1", "1", "1", "2", "2", "3", "]", "-", ">", "[", "1", "2", "3", "1", "2", "1", "]", ".", "List", "can", "contain", "complex", "types", "like", "dictionaries", "in", "which", "...
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L142-L171
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
list_distribute_contents
def list_distribute_contents(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 1, 2, 1, 3]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. la...
python
def list_distribute_contents(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 1, 2, 1, 3]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. la...
[ "def", "list_distribute_contents", "(", "input_list", ",", "function", "=", "lambda", "x", ":", "x", ")", ":", "# type: (List, Callable[[Any], Any]) -> List", "def", "riffle_shuffle", "(", "piles_list", ")", ":", "def", "grouper", "(", "n", ",", "iterable", ",", ...
Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 1, 2, 1, 3]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. lambda x: x[KEY] Args: input_list (List): List to distribute values function (Callable[[Any], Any]): ...
[ "Distribute", "the", "contents", "of", "a", "list", "eg", ".", "[", "1", "1", "1", "2", "2", "3", "]", "-", ">", "[", "1", "2", "1", "2", "1", "3", "]", ".", "List", "can", "contain", "complex", "types", "like", "dictionaries", "in", "which", "...
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L174-L211
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
extract_list_from_list_of_dict
def extract_list_from_list_of_dict(list_of_dict, key): # type: (List[DictUpperBound], Any) -> List """Extract a list by looking up key in each member of a list of dictionaries Args: list_of_dict (List[DictUpperBound]): List of dictionaries key (Any): Key to find in each dictionary Retu...
python
def extract_list_from_list_of_dict(list_of_dict, key): # type: (List[DictUpperBound], Any) -> List """Extract a list by looking up key in each member of a list of dictionaries Args: list_of_dict (List[DictUpperBound]): List of dictionaries key (Any): Key to find in each dictionary Retu...
[ "def", "extract_list_from_list_of_dict", "(", "list_of_dict", ",", "key", ")", ":", "# type: (List[DictUpperBound], Any) -> List", "result", "=", "list", "(", ")", "for", "dictionary", "in", "list_of_dict", ":", "result", ".", "append", "(", "dictionary", "[", "key"...
Extract a list by looking up key in each member of a list of dictionaries Args: list_of_dict (List[DictUpperBound]): List of dictionaries key (Any): Key to find in each dictionary Returns: List: List containing values returned from each dictionary
[ "Extract", "a", "list", "by", "looking", "up", "key", "in", "each", "member", "of", "a", "list", "of", "dictionaries" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L214-L229
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
key_value_convert
def key_value_convert(dictin, keyfn=lambda x: x, valuefn=lambda x: x, dropfailedkeys=False, dropfailedvalues=False, exception=ValueError): # type: (DictUpperBound, Callable[[Any], Any], Callable[[Any], Any], bool, bool, ExceptionUpperBound) -> Dict """Convert keys and/or values of dictiona...
python
def key_value_convert(dictin, keyfn=lambda x: x, valuefn=lambda x: x, dropfailedkeys=False, dropfailedvalues=False, exception=ValueError): # type: (DictUpperBound, Callable[[Any], Any], Callable[[Any], Any], bool, bool, ExceptionUpperBound) -> Dict """Convert keys and/or values of dictiona...
[ "def", "key_value_convert", "(", "dictin", ",", "keyfn", "=", "lambda", "x", ":", "x", ",", "valuefn", "=", "lambda", "x", ":", "x", ",", "dropfailedkeys", "=", "False", ",", "dropfailedvalues", "=", "False", ",", "exception", "=", "ValueError", ")", ":"...
Convert keys and/or values of dictionary using functions passed in as parameters Args: dictin (DictUpperBound): Input dictionary keyfn (Callable[[Any], Any]): Function to convert keys. Defaults to lambda x: x valuefn (Callable[[Any], Any]): Function to convert values. Defaults to lambda x: ...
[ "Convert", "keys", "and", "/", "or", "values", "of", "dictionary", "using", "functions", "passed", "in", "as", "parameters" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L232-L265
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
integer_key_convert
def integer_key_convert(dictin, dropfailedkeys=False): # type: (DictUpperBound, bool) -> Dict """Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. ...
python
def integer_key_convert(dictin, dropfailedkeys=False): # type: (DictUpperBound, bool) -> Dict """Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. ...
[ "def", "integer_key_convert", "(", "dictin", ",", "dropfailedkeys", "=", "False", ")", ":", "# type: (DictUpperBound, bool) -> Dict", "return", "key_value_convert", "(", "dictin", ",", "keyfn", "=", "int", ",", "dropfailedkeys", "=", "dropfailedkeys", ")" ]
Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with keys converted to integers
[ "Convert", "keys", "of", "dictionary", "to", "integers" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L268-L280
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
integer_value_convert
def integer_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to F...
python
def integer_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to F...
[ "def", "integer_value_convert", "(", "dictin", ",", "dropfailedvalues", "=", "False", ")", ":", "# type: (DictUpperBound, bool) -> Dict", "return", "key_value_convert", "(", "dictin", ",", "valuefn", "=", "int", ",", "dropfailedvalues", "=", "dropfailedvalues", ")" ]
Convert values of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with values converted to integers
[ "Convert", "values", "of", "dictionary", "to", "integers" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L283-L295
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
float_value_convert
def float_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to floats Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False...
python
def float_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to floats Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False...
[ "def", "float_value_convert", "(", "dictin", ",", "dropfailedvalues", "=", "False", ")", ":", "# type: (DictUpperBound, bool) -> Dict", "return", "key_value_convert", "(", "dictin", ",", "valuefn", "=", "float", ",", "dropfailedvalues", "=", "dropfailedvalues", ")" ]
Convert values of dictionary to floats Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with values converted to floats
[ "Convert", "values", "of", "dictionary", "to", "floats" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L298-L310
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
avg_dicts
def avg_dicts(dictin1, dictin2, dropmissing=True): # type: (DictUpperBound, DictUpperBound, bool) -> Dict """Create a new dictionary from two dictionaries by averaging values Args: dictin1 (DictUpperBound): First input dictionary dictin2 (DictUpperBound): Second input dictionary dro...
python
def avg_dicts(dictin1, dictin2, dropmissing=True): # type: (DictUpperBound, DictUpperBound, bool) -> Dict """Create a new dictionary from two dictionaries by averaging values Args: dictin1 (DictUpperBound): First input dictionary dictin2 (DictUpperBound): Second input dictionary dro...
[ "def", "avg_dicts", "(", "dictin1", ",", "dictin2", ",", "dropmissing", "=", "True", ")", ":", "# type: (DictUpperBound, DictUpperBound, bool) -> Dict", "dictout", "=", "dict", "(", ")", "for", "key", "in", "dictin1", ":", "if", "key", "in", "dictin2", ":", "d...
Create a new dictionary from two dictionaries by averaging values Args: dictin1 (DictUpperBound): First input dictionary dictin2 (DictUpperBound): Second input dictionary dropmissing (bool): Whether to drop keys missing in one dictionary. Defaults to True. Returns: Dict: Dictio...
[ "Create", "a", "new", "dictionary", "from", "two", "dictionaries", "by", "averaging", "values" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L313-L336
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
read_list_from_csv
def read_list_from_csv(filepath, dict_form=False, headers=None, **kwargs): # type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]] """Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of mu...
python
def read_list_from_csv(filepath, dict_form=False, headers=None, **kwargs): # type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]] """Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of mu...
[ "def", "read_list_from_csv", "(", "filepath", ",", "dict_form", "=", "False", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]]", "stream", "=", "Stream", "(", "fi...
Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line headers) to be considered as headers (rows start counting at 1), or the actual headers defined a list of strings. If not set, all rows will be treated as c...
[ "Read", "a", "list", "of", "rows", "in", "dict", "or", "list", "form", "from", "a", "csv", ".", "(", "The", "headers", "argument", "is", "either", "a", "row", "number", "or", "list", "of", "row", "numbers", "(", "in", "case", "of", "multi", "-", "l...
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L339-L360
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
write_list_to_csv
def write_list_to_csv(list_of_rows, filepath, headers=None): # type: (List[Union[DictUpperBound, List]], str, Union[int, List[int], List[str], None]) -> None """Write a list of rows in dict or list form to a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line h...
python
def write_list_to_csv(list_of_rows, filepath, headers=None): # type: (List[Union[DictUpperBound, List]], str, Union[int, List[int], List[str], None]) -> None """Write a list of rows in dict or list form to a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line h...
[ "def", "write_list_to_csv", "(", "list_of_rows", ",", "filepath", ",", "headers", "=", "None", ")", ":", "# type: (List[Union[DictUpperBound, List]], str, Union[int, List[int], List[str], None]) -> None", "stream", "=", "Stream", "(", "list_of_rows", ",", "headers", "=", "h...
Write a list of rows in dict or list form to a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line headers) to be considered as headers (rows start counting at 1), or the actual headers defined a list of strings. If not set, all rows will be treated as co...
[ "Write", "a", "list", "of", "rows", "in", "dict", "or", "list", "form", "to", "a", "csv", ".", "(", "The", "headers", "argument", "is", "either", "a", "row", "number", "or", "list", "of", "row", "numbers", "(", "in", "case", "of", "multi", "-", "li...
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L363-L382
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/dictandlist.py
args_to_dict
def args_to_dict(args): # type: (str) -> DictUpperBound[str,str] """Convert command line arguments in a comma separated string to a dictionary Args: args (str): Command line arguments Returns: DictUpperBound[str,str]: Dictionary of arguments """ arguments = dict() for arg ...
python
def args_to_dict(args): # type: (str) -> DictUpperBound[str,str] """Convert command line arguments in a comma separated string to a dictionary Args: args (str): Command line arguments Returns: DictUpperBound[str,str]: Dictionary of arguments """ arguments = dict() for arg ...
[ "def", "args_to_dict", "(", "args", ")", ":", "# type: (str) -> DictUpperBound[str,str]", "arguments", "=", "dict", "(", ")", "for", "arg", "in", "args", ".", "split", "(", "','", ")", ":", "key", ",", "value", "=", "arg", ".", "split", "(", "'='", ")", ...
Convert command line arguments in a comma separated string to a dictionary Args: args (str): Command line arguments Returns: DictUpperBound[str,str]: Dictionary of arguments
[ "Convert", "command", "line", "arguments", "in", "a", "comma", "separated", "string", "to", "a", "dictionary" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L385-L400
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/compare.py
compare_files
def compare_files(path1, path2): # type: (str, str) -> List[str] """Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two fi...
python
def compare_files(path1, path2): # type: (str, str) -> List[str] """Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two fi...
[ "def", "compare_files", "(", "path1", ",", "path2", ")", ":", "# type: (str, str) -> List[str]", "diff", "=", "difflib", ".", "ndiff", "(", "open", "(", "path1", ")", ".", "readlines", "(", ")", ",", "open", "(", "path2", ")", ".", "readlines", "(", ")",...
Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two files
[ "Returns", "the", "delta", "between", "two", "files", "using", "-", "?", "+", "format", "excluding", "lines", "that", "are", "the", "same" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/compare.py#L7-L21
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/compare.py
assert_files_same
def assert_files_same(path1, path2): # type: (str, str) -> None """Asserts that two files are the same and returns delta using -, ?, + format if not Args: path1 (str): Path to first file path2 (str): Path to second file Returns: None """ difflines = compare_files(p...
python
def assert_files_same(path1, path2): # type: (str, str) -> None """Asserts that two files are the same and returns delta using -, ?, + format if not Args: path1 (str): Path to first file path2 (str): Path to second file Returns: None """ difflines = compare_files(p...
[ "def", "assert_files_same", "(", "path1", ",", "path2", ")", ":", "# type: (str, str) -> None", "difflines", "=", "compare_files", "(", "path1", ",", "path2", ")", "assert", "len", "(", "difflines", ")", "==", "0", ",", "''", ".", "join", "(", "[", "'\\n'"...
Asserts that two files are the same and returns delta using -, ?, + format if not Args: path1 (str): Path to first file path2 (str): Path to second file Returns: None
[ "Asserts", "that", "two", "files", "are", "the", "same", "and", "returns", "delta", "using", "-", "?", "+", "format", "if", "not" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/compare.py#L24-L38
train
VisTrails/tej
tej/main.py
main
def main(): """Entry point when called on the command-line. """ # Locale locale.setlocale(locale.LC_ALL, '') # Encoding for output streams if str == bytes: # PY2 writer = codecs.getwriter(locale.getpreferredencoding()) o_stdout, o_stderr = sys.stdout, sys.stderr sys.std...
python
def main(): """Entry point when called on the command-line. """ # Locale locale.setlocale(locale.LC_ALL, '') # Encoding for output streams if str == bytes: # PY2 writer = codecs.getwriter(locale.getpreferredencoding()) o_stdout, o_stderr = sys.stdout, sys.stderr sys.std...
[ "def", "main", "(", ")", ":", "# Locale", "locale", ".", "setlocale", "(", "locale", ".", "LC_ALL", ",", "''", ")", "# Encoding for output streams", "if", "str", "==", "bytes", ":", "# PY2", "writer", "=", "codecs", ".", "getwriter", "(", "locale", ".", ...
Entry point when called on the command-line.
[ "Entry", "point", "when", "called", "on", "the", "command", "-", "line", "." ]
b8dedaeb6bdeb650b46cfe6d85e5aa9284fc7f0b
https://github.com/VisTrails/tej/blob/b8dedaeb6bdeb650b46cfe6d85e5aa9284fc7f0b/tej/main.py#L103-L231
train
agile4you/bottle-neck
bottle_neck/plugins.py
WrapErrorPlugin.apply
def apply(self, callback, context): # pragma: no cover """Apply the HTTPError wrapper to the callback. """ def wrapper(*args, **kwargs): try: return callback(*args, **kwargs) except bottle.HTTPError as error: return self.error_wrapper.fro...
python
def apply(self, callback, context): # pragma: no cover """Apply the HTTPError wrapper to the callback. """ def wrapper(*args, **kwargs): try: return callback(*args, **kwargs) except bottle.HTTPError as error: return self.error_wrapper.fro...
[ "def", "apply", "(", "self", ",", "callback", ",", "context", ")", ":", "# pragma: no cover", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "...
Apply the HTTPError wrapper to the callback.
[ "Apply", "the", "HTTPError", "wrapper", "to", "the", "callback", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/plugins.py#L61-L74
train
nbedi/typecaster
typecaster/models.py
Podcast.add_episode
def add_episode(self, text, text_format, title, author, summary=None, publish_date=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add a new episode to the podcast. :param text: See :meth:`Episode`. :param text_format: S...
python
def add_episode(self, text, text_format, title, author, summary=None, publish_date=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add a new episode to the podcast. :param text: See :meth:`Episode`. :param text_format: S...
[ "def", "add_episode", "(", "self", ",", "text", ",", "text_format", ",", "title", ",", "author", ",", "summary", "=", "None", ",", "publish_date", "=", "None", ",", "synthesizer", "=", "'watson'", ",", "synth_args", "=", "None", ",", "sentence_break", "=",...
Add a new episode to the podcast. :param text: See :meth:`Episode`. :param text_format: See :meth:`Episode`. :param title: See :meth:`Episode`. :param author: See :meth:`Episode`. :param summary: See :meth:`Episode`. ...
[ "Add", "a", "new", "episode", "to", "the", "podcast", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/models.py#L70-L101
train
nbedi/typecaster
typecaster/models.py
Podcast.add_scheduled_job
def add_scheduled_job(self, text_source, cron_args, text_format, title, author, summary=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add and start a new scheduled job to dynamically generate podcasts. Note: scheduling will end when the process...
python
def add_scheduled_job(self, text_source, cron_args, text_format, title, author, summary=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add and start a new scheduled job to dynamically generate podcasts. Note: scheduling will end when the process...
[ "def", "add_scheduled_job", "(", "self", ",", "text_source", ",", "cron_args", ",", "text_format", ",", "title", ",", "author", ",", "summary", "=", "None", ",", "synthesizer", "=", "'watson'", ",", "synth_args", "=", "None", ",", "sentence_break", "=", "'. ...
Add and start a new scheduled job to dynamically generate podcasts. Note: scheduling will end when the process ends. This works best when run inside an existing application. :param text_source: A function that generates podcast text. Examples: a function that opens a fi...
[ "Add", "and", "start", "a", "new", "scheduled", "job", "to", "dynamically", "generate", "podcasts", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/models.py#L103-L150
train
nbedi/typecaster
typecaster/models.py
Podcast.publish
def publish(self, titles): """ Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish. """ if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): ...
python
def publish(self, titles): """ Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish. """ if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): ...
[ "def", "publish", "(", "self", ",", "titles", ")", ":", "if", "isinstance", "(", "titles", ",", "Sequence", ")", "and", "not", "isinstance", "(", "titles", ",", "six", ".", "string_types", ")", ":", "for", "title", "in", "titles", ":", "self", ".", "...
Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish.
[ "Publish", "a", "set", "of", "episodes", "to", "the", "Podcast", "s", "RSS", "feed", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/models.py#L152-L168
train
nbedi/typecaster
typecaster/models.py
Episode.render_audio
def render_audio(self): """ Synthesize audio from the episode's text. """ segment = text_to_speech(self._text, self.synthesizer, self.synth_args, self.sentence_break) milli = len(segment) seconds = '{0:.1f}'.format(float(milli) / 1000 % 60).zfill(2) minutes = '{0...
python
def render_audio(self): """ Synthesize audio from the episode's text. """ segment = text_to_speech(self._text, self.synthesizer, self.synth_args, self.sentence_break) milli = len(segment) seconds = '{0:.1f}'.format(float(milli) / 1000 % 60).zfill(2) minutes = '{0...
[ "def", "render_audio", "(", "self", ")", ":", "segment", "=", "text_to_speech", "(", "self", ".", "_text", ",", "self", ".", "synthesizer", ",", "self", ".", "synth_args", ",", "self", ".", "sentence_break", ")", "milli", "=", "len", "(", "segment", ")",...
Synthesize audio from the episode's text.
[ "Synthesize", "audio", "from", "the", "episode", "s", "text", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/models.py#L261-L274
train
nbedi/typecaster
typecaster/models.py
Episode.publish
def publish(self): """ Mark an episode as published. """ if self.published is False: self.published = True else: raise Warning(self.title + ' is already published.')
python
def publish(self): """ Mark an episode as published. """ if self.published is False: self.published = True else: raise Warning(self.title + ' is already published.')
[ "def", "publish", "(", "self", ")", ":", "if", "self", ".", "published", "is", "False", ":", "self", ".", "published", "=", "True", "else", ":", "raise", "Warning", "(", "self", ".", "title", "+", "' is already published.'", ")" ]
Mark an episode as published.
[ "Mark", "an", "episode", "as", "published", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/models.py#L276-L283
train
nbedi/typecaster
typecaster/models.py
Episode.unpublish
def unpublish(self): """ Mark an episode as not published. """ if self.published is True: self.published = False else: raise Warning(self.title + ' is already not published.')
python
def unpublish(self): """ Mark an episode as not published. """ if self.published is True: self.published = False else: raise Warning(self.title + ' is already not published.')
[ "def", "unpublish", "(", "self", ")", ":", "if", "self", ".", "published", "is", "True", ":", "self", ".", "published", "=", "False", "else", ":", "raise", "Warning", "(", "self", ".", "title", "+", "' is already not published.'", ")" ]
Mark an episode as not published.
[ "Mark", "an", "episode", "as", "not", "published", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/models.py#L285-L292
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/useragent.py
UserAgent._environment_variables
def _environment_variables(**kwargs): # type: (Any) -> Any """ Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments """ ...
python
def _environment_variables(**kwargs): # type: (Any) -> Any """ Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments """ ...
[ "def", "_environment_variables", "(", "*", "*", "kwargs", ")", ":", "# type: (Any) -> Any", "user_agent", "=", "os", ".", "getenv", "(", "'USER_AGENT'", ")", "if", "user_agent", "is", "not", "None", ":", "kwargs", "[", "'user_agent'", "]", "=", "user_agent", ...
Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments
[ "Overwrite", "keyword", "arguments", "with", "environment", "variables" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/useragent.py#L23-L42
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/useragent.py
UserAgent._construct
def _construct(configdict, prefix, ua): # type: (Dict, str, str) -> str """ Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at start of user agent ua (str): Custom user agent text ...
python
def _construct(configdict, prefix, ua): # type: (Dict, str, str) -> str """ Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at start of user agent ua (str): Custom user agent text ...
[ "def", "_construct", "(", "configdict", ",", "prefix", ",", "ua", ")", ":", "# type: (Dict, str, str) -> str", "if", "not", "ua", ":", "raise", "UserAgentError", "(", "\"User_agent parameter missing. It can be your project's name for example.\"", ")", "preprefix", "=", "c...
Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at start of user agent ua (str): Custom user agent text Returns: str: Full user agent string
[ "Construct", "user", "agent" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/useragent.py#L45-L69
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/useragent.py
UserAgent._load
def _load(cls, prefix, user_agent_config_yaml, user_agent_lookup=None): # type: (str, str, Optional[str]) -> str """ Load user agent YAML file Args: prefix (str): Text to put at start of user agent user_agent_config_yaml (str): Path to user agent YAML file ...
python
def _load(cls, prefix, user_agent_config_yaml, user_agent_lookup=None): # type: (str, str, Optional[str]) -> str """ Load user agent YAML file Args: prefix (str): Text to put at start of user agent user_agent_config_yaml (str): Path to user agent YAML file ...
[ "def", "_load", "(", "cls", ",", "prefix", ",", "user_agent_config_yaml", ",", "user_agent_lookup", "=", "None", ")", ":", "# type: (str, str, Optional[str]) -> str", "if", "not", "user_agent_config_yaml", ":", "user_agent_config_yaml", "=", "cls", ".", "default_user_ag...
Load user agent YAML file Args: prefix (str): Text to put at start of user agent user_agent_config_yaml (str): Path to user agent YAML file user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied. Returns: str: user agent
[ "Load", "user", "agent", "YAML", "file" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/useragent.py#L72-L100
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/useragent.py
UserAgent._create
def _create(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLi...
python
def _create(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLi...
[ "def", "_create", "(", "cls", ",", "user_agent", "=", "None", ",", "user_agent_config_yaml", "=", "None", ",", "user_agent_lookup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (Optional[str], Optional[str], Optional[str], Any) -> str", "kwargs", "=", "U...
Get full user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_lookup...
[ "Get", "full", "user", "agent", "string" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/useragent.py#L103-L131
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/useragent.py
UserAgent.set_global
def set_global(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> None """ Set global user agent string Args: user_agent (Optional[str]): User agent string. HD...
python
def set_global(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> None """ Set global user agent string Args: user_agent (Optional[str]): User agent string. HD...
[ "def", "set_global", "(", "cls", ",", "user_agent", "=", "None", ",", "user_agent_config_yaml", "=", "None", ",", "user_agent_lookup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (Optional[str], Optional[str], Optional[str], Any) -> None", "cls", ".", "...
Set global user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_look...
[ "Set", "global", "user", "agent", "string" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/useragent.py#L146-L160
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/useragent.py
UserAgent.get
def get(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string from parameters if supplied falling back on global user agent if set. Args: user_age...
python
def get(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string from parameters if supplied falling back on global user agent if set. Args: user_age...
[ "def", "get", "(", "cls", ",", "user_agent", "=", "None", ",", "user_agent_config_yaml", "=", "None", ",", "user_agent_lookup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (Optional[str], Optional[str], Optional[str], Any) -> str", "if", "user_agent", "...
Get full user agent string from parameters if supplied falling back on global user agent if set. Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent...
[ "Get", "full", "user", "agent", "string", "from", "parameters", "if", "supplied", "falling", "back", "on", "global", "user", "agent", "if", "set", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/useragent.py#L163-L183
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/saver.py
save_yaml
def save_yaml(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to YAML file pretty (bool): Whether to ...
python
def save_yaml(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to YAML file pretty (bool): Whether to ...
[ "def", "save_yaml", "(", "dictionary", ",", "path", ",", "pretty", "=", "False", ",", "sortkeys", "=", "False", ")", ":", "# type: (Dict, str, bool, bool) -> None", "if", "sortkeys", ":", "dictionary", "=", "dict", "(", "dictionary", ")", "with", "open", "(", ...
Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to YAML file pretty (bool): Whether to pretty print. Defaults to False. sortkeys (bool): Whether to sort dictionary keys. Defaults to False. ...
[ "Save", "dictionary", "to", "YAML", "file", "preserving", "order", "if", "it", "is", "an", "OrderedDict" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/saver.py#L15-L34
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/saver.py
save_json
def save_json(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to JSON file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to JSON file pretty (bool): Whether to ...
python
def save_json(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to JSON file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to JSON file pretty (bool): Whether to ...
[ "def", "save_json", "(", "dictionary", ",", "path", ",", "pretty", "=", "False", ",", "sortkeys", "=", "False", ")", ":", "# type: (Dict, str, bool, bool) -> None", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "if", "pretty", ":", "indent"...
Save dictionary to JSON file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to JSON file pretty (bool): Whether to pretty print. Defaults to False. sortkeys (bool): Whether to sort dictionary keys. Defaults to False. ...
[ "Save", "dictionary", "to", "JSON", "file", "preserving", "order", "if", "it", "is", "an", "OrderedDict" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/saver.py#L37-L57
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/loader.py
load_yaml
def load_yaml(path): # type: (str) -> OrderedDict """Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered dictionary containing loaded YAML file """ with open(path, 'rt') as f: yamldict = yaml.load(f.read(), Loader=...
python
def load_yaml(path): # type: (str) -> OrderedDict """Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered dictionary containing loaded YAML file """ with open(path, 'rt') as f: yamldict = yaml.load(f.read(), Loader=...
[ "def", "load_yaml", "(", "path", ")", ":", "# type: (str) -> OrderedDict", "with", "open", "(", "path", ",", "'rt'", ")", "as", "f", ":", "yamldict", "=", "yaml", ".", "load", "(", "f", ".", "read", "(", ")", ",", "Loader", "=", "yamlloader", ".", "o...
Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered dictionary containing loaded YAML file
[ "Load", "YAML", "file", "into", "an", "ordered", "dictionary" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/loader.py#L79-L93
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/loader.py
load_json
def load_json(path): # type: (str) -> OrderedDict """Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered dictionary containing loaded JSON file """ with open(path, 'rt') as f: jsondict = json.loads(f.read(), object...
python
def load_json(path): # type: (str) -> OrderedDict """Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered dictionary containing loaded JSON file """ with open(path, 'rt') as f: jsondict = json.loads(f.read(), object...
[ "def", "load_json", "(", "path", ")", ":", "# type: (str) -> OrderedDict", "with", "open", "(", "path", ",", "'rt'", ")", "as", "f", ":", "jsondict", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ",", "object_pairs_hook", "=", "OrderedDict"...
Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered dictionary containing loaded JSON file
[ "Load", "JSON", "file", "into", "an", "ordered", "dictionary" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/loader.py#L96-L110
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/loader.py
load_file_to_str
def load_file_to_str(path): # type: (str) -> str """ Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file """ with open(path, 'rt') as f: string = f.read().replace(linesep, '') if not string: rai...
python
def load_file_to_str(path): # type: (str) -> str """ Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file """ with open(path, 'rt') as f: string = f.read().replace(linesep, '') if not string: rai...
[ "def", "load_file_to_str", "(", "path", ")", ":", "# type: (str) -> str", "with", "open", "(", "path", ",", "'rt'", ")", "as", "f", ":", "string", "=", "f", ".", "read", "(", ")", ".", "replace", "(", "linesep", ",", "''", ")", "if", "not", "string",...
Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file
[ "Load", "file", "into", "a", "string", "removing", "newlines" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/loader.py#L113-L129
train
GaretJax/lancet
lancet/contrib/packaging_tools.py
contributors
def contributors(lancet, output): """ List all contributors visible in the git history. """ sorting = pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE commits = lancet.repo.walk(lancet.repo.head.target, sorting) contributors = ((c.author.name, c.author.email) for c in commits) contributors = O...
python
def contributors(lancet, output): """ List all contributors visible in the git history. """ sorting = pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE commits = lancet.repo.walk(lancet.repo.head.target, sorting) contributors = ((c.author.name, c.author.email) for c in commits) contributors = O...
[ "def", "contributors", "(", "lancet", ",", "output", ")", ":", "sorting", "=", "pygit2", ".", "GIT_SORT_TIME", "|", "pygit2", ".", "GIT_SORT_REVERSE", "commits", "=", "lancet", ".", "repo", ".", "walk", "(", "lancet", ".", "repo", ".", "head", ".", "targ...
List all contributors visible in the git history.
[ "List", "all", "contributors", "visible", "in", "the", "git", "history", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/contrib/packaging_tools.py#L14-L26
train
nbedi/typecaster
typecaster/utils.py
text_to_speech
def text_to_speech(text, synthesizer, synth_args, sentence_break): """ Converts given text to a pydub AudioSegment using a specified speech synthesizer. At the moment, IBM Watson's text-to-speech API is the only available synthesizer. :param text: The text that will be synthesized to audio....
python
def text_to_speech(text, synthesizer, synth_args, sentence_break): """ Converts given text to a pydub AudioSegment using a specified speech synthesizer. At the moment, IBM Watson's text-to-speech API is the only available synthesizer. :param text: The text that will be synthesized to audio....
[ "def", "text_to_speech", "(", "text", ",", "synthesizer", ",", "synth_args", ",", "sentence_break", ")", ":", "if", "len", "(", "text", ".", "split", "(", ")", ")", "<", "50", ":", "if", "synthesizer", "==", "'watson'", ":", "with", "open", "(", "'.tem...
Converts given text to a pydub AudioSegment using a specified speech synthesizer. At the moment, IBM Watson's text-to-speech API is the only available synthesizer. :param text: The text that will be synthesized to audio. :param synthesizer: The text-to-speech synthesizer to use. At the...
[ "Converts", "given", "text", "to", "a", "pydub", "AudioSegment", "using", "a", "specified", "speech", "synthesizer", ".", "At", "the", "moment", "IBM", "Watson", "s", "text", "-", "to", "-", "speech", "API", "is", "the", "only", "available", "synthesizer", ...
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/utils.py#L11-L53
train
nbedi/typecaster
typecaster/utils.py
watson_request
def watson_request(text, synth_args): """ Makes a single request to the IBM Watson text-to-speech API. :param text: The text that will be synthesized to audio. :param synth_args: A dictionary of arguments to add to the request. These should include username and password for auth...
python
def watson_request(text, synth_args): """ Makes a single request to the IBM Watson text-to-speech API. :param text: The text that will be synthesized to audio. :param synth_args: A dictionary of arguments to add to the request. These should include username and password for auth...
[ "def", "watson_request", "(", "text", ",", "synth_args", ")", ":", "params", "=", "{", "'text'", ":", "text", ",", "'accept'", ":", "'audio/wav'", "}", "if", "synth_args", "is", "not", "None", ":", "params", ".", "update", "(", "synth_args", ")", "if", ...
Makes a single request to the IBM Watson text-to-speech API. :param text: The text that will be synthesized to audio. :param synth_args: A dictionary of arguments to add to the request. These should include username and password for authentication.
[ "Makes", "a", "single", "request", "to", "the", "IBM", "Watson", "text", "-", "to", "-", "speech", "API", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/utils.py#L56-L82
train
nbedi/typecaster
typecaster/utils.py
build_rss_feed
def build_rss_feed(podcast): """ Builds a podcast RSS feed and returns an xml file. :param podcast: A Podcast model to build the RSS feed from. """ if not os.path.exists(podcast.output_path): os.makedirs(podcast.output_path) rss = ET.Element('rss', attrib={'xmlns:itunes': 'http...
python
def build_rss_feed(podcast): """ Builds a podcast RSS feed and returns an xml file. :param podcast: A Podcast model to build the RSS feed from. """ if not os.path.exists(podcast.output_path): os.makedirs(podcast.output_path) rss = ET.Element('rss', attrib={'xmlns:itunes': 'http...
[ "def", "build_rss_feed", "(", "podcast", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "podcast", ".", "output_path", ")", ":", "os", ".", "makedirs", "(", "podcast", ".", "output_path", ")", "rss", "=", "ET", ".", "Element", "(", "'r...
Builds a podcast RSS feed and returns an xml file. :param podcast: A Podcast model to build the RSS feed from.
[ "Builds", "a", "podcast", "RSS", "feed", "and", "returns", "an", "xml", "file", "." ]
09eee6d4fbad9f70c90364ea89ab39917f903afc
https://github.com/nbedi/typecaster/blob/09eee6d4fbad9f70c90364ea89ab39917f903afc/typecaster/utils.py#L85-L128
train
agile4you/bottle-neck
example.py
ResourceHandler.get
def get(self, uid=None): """Example retrieve API method. """ # Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == u...
python
def get(self, uid=None): """Example retrieve API method. """ # Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == u...
[ "def", "get", "(", "self", ",", "uid", "=", "None", ")", ":", "# Return resource collection", "if", "uid", "is", "None", ":", "return", "self", ".", "response_factory", ".", "ok", "(", "data", "=", "resource_db", ")", "# Return resource based on UID.", "try", ...
Example retrieve API method.
[ "Example", "retrieve", "API", "method", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L27-L43
train
agile4you/bottle-neck
example.py
ResourceHandler.post
def post(self): """Example POST method. """ resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record)
python
def post(self): """Example POST method. """ resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record)
[ "def", "post", "(", "self", ")", ":", "resource_data", "=", "self", ".", "request", ".", "json", "record", "=", "{", "'id'", ":", "str", "(", "len", "(", "resource_db", ")", "+", "1", ")", ",", "'name'", ":", "resource_data", ".", "get", "(", "'nam...
Example POST method.
[ "Example", "POST", "method", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L45-L56
train
agile4you/bottle-neck
example.py
ResourceHandler.put
def put(self, uid): """Example PUT method. """ resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_d...
python
def put(self, uid): """Example PUT method. """ resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_d...
[ "def", "put", "(", "self", ",", "uid", ")", ":", "resource_data", "=", "self", ".", "request", ".", "json", "try", ":", "record", "=", "resource_db", "[", "uid", "]", "except", "KeyError", ":", "return", "self", ".", "response_factory", ".", "not_found",...
Example PUT method.
[ "Example", "PUT", "method", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L58-L72
train
agile4you/bottle-neck
example.py
ResourceHandler.delete
def delete(self, uid): """Example DELETE method. """ try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory...
python
def delete(self, uid): """Example DELETE method. """ try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory...
[ "def", "delete", "(", "self", ",", "uid", ")", ":", "try", ":", "record", "=", "resource_db", "[", "uid", "]", ".", "copy", "(", ")", "except", "KeyError", ":", "return", "self", ".", "response_factory", ".", "not_found", "(", "errors", "=", "[", "'R...
Example DELETE method.
[ "Example", "DELETE", "method", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L74-L85
train
amcat/amcatclient
demo_wikinews_scraper.py
get_pages
def get_pages(url): """ Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat """ while True: yield url doc = html.parse(url).find("body") links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next...
python
def get_pages(url): """ Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat """ while True: yield url doc = html.parse(url).find("body") links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next...
[ "def", "get_pages", "(", "url", ")", ":", "while", "True", ":", "yield", "url", "doc", "=", "html", ".", "parse", "(", "url", ")", ".", "find", "(", "\"body\"", ")", "links", "=", "[", "a", "for", "a", "in", "doc", ".", "findall", "(", "\".//a\""...
Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat
[ "Return", "the", "pages", "from", "the", "starting", "url", "Technically", "look", "for", "the", "next", "50", "link", "yield", "and", "download", "it", "repeat" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L45-L56
train
amcat/amcatclient
demo_wikinews_scraper.py
get_article_urls
def get_article_urls(url): """ Return the articles from a page Technically, look for a div with class mw-search-result-heading and get the first link from this div """ doc = html.parse(url).getroot() for div in doc.cssselect("div.mw-search-result-heading"): href = div.cssselect("a")[...
python
def get_article_urls(url): """ Return the articles from a page Technically, look for a div with class mw-search-result-heading and get the first link from this div """ doc = html.parse(url).getroot() for div in doc.cssselect("div.mw-search-result-heading"): href = div.cssselect("a")[...
[ "def", "get_article_urls", "(", "url", ")", ":", "doc", "=", "html", ".", "parse", "(", "url", ")", ".", "getroot", "(", ")", "for", "div", "in", "doc", ".", "cssselect", "(", "\"div.mw-search-result-heading\"", ")", ":", "href", "=", "div", ".", "csss...
Return the articles from a page Technically, look for a div with class mw-search-result-heading and get the first link from this div
[ "Return", "the", "articles", "from", "a", "page", "Technically", "look", "for", "a", "div", "with", "class", "mw", "-", "search", "-", "result", "-", "heading", "and", "get", "the", "first", "link", "from", "this", "div" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L58-L70
train
amcat/amcatclient
demo_wikinews_scraper.py
get_article
def get_article(url): """ Return a single article as a 'amcat-ready' dict Uses the 'export' function of wikinews to get an xml article """ a = html.parse(url).getroot() title = a.cssselect(".firstHeading")[0].text_content() date = a.cssselect(".published")[0].text_content() date = dateti...
python
def get_article(url): """ Return a single article as a 'amcat-ready' dict Uses the 'export' function of wikinews to get an xml article """ a = html.parse(url).getroot() title = a.cssselect(".firstHeading")[0].text_content() date = a.cssselect(".published")[0].text_content() date = dateti...
[ "def", "get_article", "(", "url", ")", ":", "a", "=", "html", ".", "parse", "(", "url", ")", ".", "getroot", "(", ")", "title", "=", "a", ".", "cssselect", "(", "\".firstHeading\"", ")", "[", "0", "]", ".", "text_content", "(", ")", "date", "=", ...
Return a single article as a 'amcat-ready' dict Uses the 'export' function of wikinews to get an xml article
[ "Return", "a", "single", "article", "as", "a", "amcat", "-", "ready", "dict", "Uses", "the", "export", "function", "of", "wikinews", "to", "get", "an", "xml", "article" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L89-L106
train
amcat/amcatclient
demo_wikinews_scraper.py
scrape_wikinews
def scrape_wikinews(conn, project, articleset, query): """ Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name """ url = "http://en.wikinews.org/w/index.php?search={}&limit=50"....
python
def scrape_wikinews(conn, project, articleset, query): """ Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name """ url = "http://en.wikinews.org/w/index.php?search={}&limit=50"....
[ "def", "scrape_wikinews", "(", "conn", ",", "project", ",", "articleset", ",", "query", ")", ":", "url", "=", "\"http://en.wikinews.org/w/index.php?search={}&limit=50\"", ".", "format", "(", "query", ")", "logging", ".", "info", "(", "url", ")", "for", "page", ...
Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name
[ "Scrape", "wikinews", "articles", "from", "the", "given", "query" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L118-L133
train
walkr/nanoservice
benchmarks/bench_req_rep_raw.py
start_service
def start_service(addr, n): """ Start a service """ s = Service(addr) started = time.time() for _ in range(n): msg = s.socket.recv() s.socket.send(msg) s.socket.close() duration = time.time() - started print('Raw REP service stats:') util.print_stats(n, duration) re...
python
def start_service(addr, n): """ Start a service """ s = Service(addr) started = time.time() for _ in range(n): msg = s.socket.recv() s.socket.send(msg) s.socket.close() duration = time.time() - started print('Raw REP service stats:') util.print_stats(n, duration) re...
[ "def", "start_service", "(", "addr", ",", "n", ")", ":", "s", "=", "Service", "(", "addr", ")", "started", "=", "time", ".", "time", "(", ")", "for", "_", "in", "range", "(", "n", ")", ":", "msg", "=", "s", ".", "socket", ".", "recv", "(", ")...
Start a service
[ "Start", "a", "service" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/benchmarks/bench_req_rep_raw.py#L8-L21
train
walkr/nanoservice
benchmarks/bench_req_rep_raw.py
bench
def bench(client, n): """ Benchmark n requests """ items = list(range(n)) # Time client publish operations # ------------------------------ started = time.time() msg = b'x' for i in items: client.socket.send(msg) res = client.socket.recv() assert msg == res durat...
python
def bench(client, n): """ Benchmark n requests """ items = list(range(n)) # Time client publish operations # ------------------------------ started = time.time() msg = b'x' for i in items: client.socket.send(msg) res = client.socket.recv() assert msg == res durat...
[ "def", "bench", "(", "client", ",", "n", ")", ":", "items", "=", "list", "(", "range", "(", "n", ")", ")", "# Time client publish operations", "# ------------------------------", "started", "=", "time", ".", "time", "(", ")", "msg", "=", "b'x'", "for", "i"...
Benchmark n requests
[ "Benchmark", "n", "requests" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/benchmarks/bench_req_rep_raw.py#L24-L39
train
zmqless/python-zeroless
zeroless/zeroless.py
Sock.pub
def pub(self, topic=b'', embed_topic=False): """ Returns a callable that can be used to transmit a message, with a given ``topic``, in a publisher-subscriber fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one bein...
python
def pub(self, topic=b'', embed_topic=False): """ Returns a callable that can be used to transmit a message, with a given ``topic``, in a publisher-subscriber fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one bein...
[ "def", "pub", "(", "self", ",", "topic", "=", "b''", ",", "embed_topic", "=", "False", ")", ":", "if", "not", "isinstance", "(", "topic", ",", "bytes", ")", ":", "error", "=", "'Topic must be bytes'", "log", ".", "error", "(", "error", ")", "raise", ...
Returns a callable that can be used to transmit a message, with a given ``topic``, in a publisher-subscriber fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. By default, no topic w...
[ "Returns", "a", "callable", "that", "can", "be", "used", "to", "transmit", "a", "message", "with", "a", "given", "topic", "in", "a", "publisher", "-", "subscriber", "fashion", ".", "Note", "that", "the", "sender", "function", "has", "a", "print", "like", ...
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L114-L141
train
zmqless/python-zeroless
zeroless/zeroless.py
Sock.sub
def sub(self, topics=(b'',)): """ Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of t...
python
def sub(self, topics=(b'',)): """ Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of t...
[ "def", "sub", "(", "self", ",", "topics", "=", "(", "b''", ",", ")", ")", ":", "sock", "=", "self", ".", "__sock", "(", "zmq", ".", "SUB", ")", "for", "topic", "in", "topics", ":", "if", "not", "isinstance", "(", "topic", ",", "bytes", ")", ":"...
Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of topics to subscribe to (default=b'') :type ...
[ "Returns", "an", "iterable", "that", "can", "be", "used", "to", "iterate", "over", "incoming", "messages", "that", "were", "published", "with", "one", "of", "the", "topics", "specified", "in", "topics", ".", "Note", "that", "the", "iterable", "returns", "as"...
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L143-L162
train
zmqless/python-zeroless
zeroless/zeroless.py
Sock.push
def push(self): """ Returns a callable that can be used to transmit a message in a push-pull fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: function ...
python
def push(self): """ Returns a callable that can be used to transmit a message in a push-pull fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: function ...
[ "def", "push", "(", "self", ")", ":", "sock", "=", "self", ".", "__sock", "(", "zmq", ".", "PUSH", ")", "return", "self", ".", "__send_function", "(", "sock", ")" ]
Returns a callable that can be used to transmit a message in a push-pull fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: function
[ "Returns", "a", "callable", "that", "can", "be", "used", "to", "transmit", "a", "message", "in", "a", "push", "-", "pull", "fashion", ".", "Note", "that", "the", "sender", "function", "has", "a", "print", "like", "signature", "with", "an", "infinite", "n...
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L165-L175
train
zmqless/python-zeroless
zeroless/zeroless.py
Sock.pull
def pull(self): """ Returns an iterable that can be used to iterate over incoming messages, that were pushed by a push socket. Note that the iterable returns as many parts as sent by pushers. :rtype: generator """ sock = self.__sock(zmq.PULL) return self....
python
def pull(self): """ Returns an iterable that can be used to iterate over incoming messages, that were pushed by a push socket. Note that the iterable returns as many parts as sent by pushers. :rtype: generator """ sock = self.__sock(zmq.PULL) return self....
[ "def", "pull", "(", "self", ")", ":", "sock", "=", "self", ".", "__sock", "(", "zmq", ".", "PULL", ")", "return", "self", ".", "__recv_generator", "(", "sock", ")" ]
Returns an iterable that can be used to iterate over incoming messages, that were pushed by a push socket. Note that the iterable returns as many parts as sent by pushers. :rtype: generator
[ "Returns", "an", "iterable", "that", "can", "be", "used", "to", "iterate", "over", "incoming", "messages", "that", "were", "pushed", "by", "a", "push", "socket", ".", "Note", "that", "the", "iterable", "returns", "as", "many", "parts", "as", "sent", "by", ...
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L177-L186
train
zmqless/python-zeroless
zeroless/zeroless.py
Sock.request
def request(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by repliers. Also, the sender func...
python
def request(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by repliers. Also, the sender func...
[ "def", "request", "(", "self", ")", ":", "sock", "=", "self", ".", "__sock", "(", "zmq", ".", "REQ", ")", "return", "self", ".", "__send_function", "(", "sock", ")", ",", "self", ".", "__recv_generator", "(", "sock", ")" ]
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by repliers. Also, the sender function has a ``print`` like signa...
[ "Returns", "a", "callable", "and", "an", "iterable", "respectively", ".", "Those", "can", "be", "used", "to", "both", "transmit", "a", "message", "and", "/", "or", "iterate", "over", "incoming", "messages", "that", "were", "replied", "by", "a", "reply", "s...
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L189-L201
train
zmqless/python-zeroless
zeroless/zeroless.py
Sock.reply
def reply(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were requested by a request socket. Note that the iterable returns as many parts as sent by requesters. Also, the sender ...
python
def reply(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were requested by a request socket. Note that the iterable returns as many parts as sent by requesters. Also, the sender ...
[ "def", "reply", "(", "self", ")", ":", "sock", "=", "self", ".", "__sock", "(", "zmq", ".", "REP", ")", "return", "self", ".", "__send_function", "(", "sock", ")", ",", "self", ".", "__recv_generator", "(", "sock", ")" ]
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were requested by a request socket. Note that the iterable returns as many parts as sent by requesters. Also, the sender function has a ``print`` like...
[ "Returns", "a", "callable", "and", "an", "iterable", "respectively", ".", "Those", "can", "be", "used", "to", "both", "transmit", "a", "message", "and", "/", "or", "iterate", "over", "incoming", "messages", "that", "were", "requested", "by", "a", "request", ...
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L203-L215
train
zmqless/python-zeroless
zeroless/zeroless.py
Sock.pair
def pair(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has ...
python
def pair(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has ...
[ "def", "pair", "(", "self", ")", ":", "sock", "=", "self", ".", "__sock", "(", "zmq", ".", "PAIR", ")", "return", "self", ".", "__send_function", "(", "sock", ")", ",", "self", ".", "__recv_generator", "(", "sock", ")" ]
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has a ``print`` like signature, ...
[ "Returns", "a", "callable", "and", "an", "iterable", "respectively", ".", "Those", "can", "be", "used", "to", "both", "transmit", "a", "message", "and", "/", "or", "iterate", "over", "incoming", "messages", "that", "were", "sent", "by", "a", "pair", "socke...
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L218-L230
train
zmqless/python-zeroless
zeroless/zeroless.py
Client.connect
def connect(self, ip, port): """ Connects to a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self """ _check_valid_port_range(port) ...
python
def connect(self, ip, port): """ Connects to a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self """ _check_valid_port_range(port) ...
[ "def", "connect", "(", "self", ",", "ip", ",", "port", ")", ":", "_check_valid_port_range", "(", "port", ")", "address", "=", "(", "ip", ",", "port", ")", "if", "address", "in", "self", ".", "_addresses", ":", "error", "=", "'Already connected to {0} on po...
Connects to a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self
[ "Connects", "to", "a", "server", "at", "the", "specified", "ip", "and", "port", "." ]
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L269-L296
train
zmqless/python-zeroless
zeroless/zeroless.py
Client.disconnect
def disconnect(self, ip, port): """ Disconnects from a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self """ _check_valid_port_range(p...
python
def disconnect(self, ip, port): """ Disconnects from a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self """ _check_valid_port_range(p...
[ "def", "disconnect", "(", "self", ",", "ip", ",", "port", ")", ":", "_check_valid_port_range", "(", "port", ")", "address", "=", "(", "ip", ",", "port", ")", "try", ":", "self", ".", "_addresses", ".", "remove", "(", "address", ")", "except", "ValueErr...
Disconnects from a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self
[ "Disconnects", "from", "a", "server", "at", "the", "specified", "ip", "and", "port", "." ]
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L308-L331
train
zmqless/python-zeroless
zeroless/zeroless.py
Client.disconnect_all
def disconnect_all(self): """ Disconnects from all connected servers. :rtype: self """ addresses = deepcopy(self._addresses) for ip, port in addresses: self.disconnect(ip, port) return self
python
def disconnect_all(self): """ Disconnects from all connected servers. :rtype: self """ addresses = deepcopy(self._addresses) for ip, port in addresses: self.disconnect(ip, port) return self
[ "def", "disconnect_all", "(", "self", ")", ":", "addresses", "=", "deepcopy", "(", "self", ".", "_addresses", ")", "for", "ip", ",", "port", "in", "addresses", ":", "self", ".", "disconnect", "(", "ip", ",", "port", ")", "return", "self" ]
Disconnects from all connected servers. :rtype: self
[ "Disconnects", "from", "all", "connected", "servers", ".", ":", "rtype", ":", "self" ]
bff8ce0d12aae36537f41b57b2bd4ee087ed70e2
https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L343-L353
train
azaitsev/millify
millify/__init__.py
remove_exponent
def remove_exponent(d): """Remove exponent.""" return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
python
def remove_exponent(d): """Remove exponent.""" return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
[ "def", "remove_exponent", "(", "d", ")", ":", "return", "d", ".", "quantize", "(", "Decimal", "(", "1", ")", ")", "if", "d", "==", "d", ".", "to_integral", "(", ")", "else", "d", ".", "normalize", "(", ")" ]
Remove exponent.
[ "Remove", "exponent", "." ]
69f83ad6e15b79f073fcdec21358f255473eb518
https://github.com/azaitsev/millify/blob/69f83ad6e15b79f073fcdec21358f255473eb518/millify/__init__.py#L11-L13
train
azaitsev/millify
millify/__init__.py
millify
def millify(n, precision=0, drop_nulls=True, prefixes=[]): """Humanize number.""" millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'] if prefixes: millnames = [''] millnames.extend(prefixes) n = float(n) millidx = max(0, min(len(millnames) - 1, int(math....
python
def millify(n, precision=0, drop_nulls=True, prefixes=[]): """Humanize number.""" millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'] if prefixes: millnames = [''] millnames.extend(prefixes) n = float(n) millidx = max(0, min(len(millnames) - 1, int(math....
[ "def", "millify", "(", "n", ",", "precision", "=", "0", ",", "drop_nulls", "=", "True", ",", "prefixes", "=", "[", "]", ")", ":", "millnames", "=", "[", "''", ",", "'k'", ",", "'M'", ",", "'B'", ",", "'T'", ",", "'P'", ",", "'E'", ",", "'Z'", ...
Humanize number.
[ "Humanize", "number", "." ]
69f83ad6e15b79f073fcdec21358f255473eb518
https://github.com/azaitsev/millify/blob/69f83ad6e15b79f073fcdec21358f255473eb518/millify/__init__.py#L16-L28
train
azaitsev/millify
millify/__init__.py
prettify
def prettify(amount, separator=','): """Separate with predefined separator.""" orig = str(amount) new = re.sub("^(-?\d+)(\d{3})", "\g<1>{0}\g<2>".format(separator), str(amount)) if orig == new: return new else: return prettify(new)
python
def prettify(amount, separator=','): """Separate with predefined separator.""" orig = str(amount) new = re.sub("^(-?\d+)(\d{3})", "\g<1>{0}\g<2>".format(separator), str(amount)) if orig == new: return new else: return prettify(new)
[ "def", "prettify", "(", "amount", ",", "separator", "=", "','", ")", ":", "orig", "=", "str", "(", "amount", ")", "new", "=", "re", ".", "sub", "(", "\"^(-?\\d+)(\\d{3})\"", ",", "\"\\g<1>{0}\\g<2>\"", ".", "format", "(", "separator", ")", ",", "str", ...
Separate with predefined separator.
[ "Separate", "with", "predefined", "separator", "." ]
69f83ad6e15b79f073fcdec21358f255473eb518
https://github.com/azaitsev/millify/blob/69f83ad6e15b79f073fcdec21358f255473eb518/millify/__init__.py#L31-L38
train
the01/python-flotils
flotils/loadable.py
load_json
def load_json(json_data, decoder=None): """ Load data from json string :param json_data: Stringified json object :type json_data: str | unicode :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict ...
python
def load_json(json_data, decoder=None): """ Load data from json string :param json_data: Stringified json object :type json_data: str | unicode :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict ...
[ "def", "load_json", "(", "json_data", ",", "decoder", "=", "None", ")", ":", "if", "decoder", "is", "None", ":", "decoder", "=", "DateTimeDecoder", "return", "json", ".", "loads", "(", "json_data", ",", "object_hook", "=", "decoder", ".", "decode", ")" ]
Load data from json string :param json_data: Stringified json object :type json_data: str | unicode :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict
[ "Load", "data", "from", "json", "string" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L131-L144
train
the01/python-flotils
flotils/loadable.py
load_json_file
def load_json_file(file, decoder=None): """ Load data from json file :param file: Readable object or path to file :type file: FileIO | str :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict ""...
python
def load_json_file(file, decoder=None): """ Load data from json file :param file: Readable object or path to file :type file: FileIO | str :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict ""...
[ "def", "load_json_file", "(", "file", ",", "decoder", "=", "None", ")", ":", "if", "decoder", "is", "None", ":", "decoder", "=", "DateTimeDecoder", "if", "not", "hasattr", "(", "file", ",", "\"read\"", ")", ":", "with", "io", ".", "open", "(", "file", ...
Load data from json file :param file: Readable object or path to file :type file: FileIO | str :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict
[ "Load", "data", "from", "json", "file" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L147-L163
train
the01/python-flotils
flotils/loadable.py
save_json
def save_json(val, pretty=False, sort=True, encoder=None): """ Save data to json string :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) otherwise going to be compact :type pretty...
python
def save_json(val, pretty=False, sort=True, encoder=None): """ Save data to json string :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) otherwise going to be compact :type pretty...
[ "def", "save_json", "(", "val", ",", "pretty", "=", "False", ",", "sort", "=", "True", ",", "encoder", "=", "None", ")", ":", "if", "encoder", "is", "None", ":", "encoder", "=", "DateTimeEncoder", "if", "pretty", ":", "data", "=", "json", ".", "dumps...
Save data to json string :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) otherwise going to be compact :type pretty: bool :param sort: Sort keys (default: True) :type sort: bool ...
[ "Save", "data", "to", "json", "string" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L166-L201
train
the01/python-flotils
flotils/loadable.py
save_json_file
def save_json_file( file, val, pretty=False, compact=True, sort=True, encoder=None ): """ Save data to json file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | list | dict ...
python
def save_json_file( file, val, pretty=False, compact=True, sort=True, encoder=None ): """ Save data to json file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | list | dict ...
[ "def", "save_json_file", "(", "file", ",", "val", ",", "pretty", "=", "False", ",", "compact", "=", "True", ",", "sort", "=", "True", ",", "encoder", "=", "None", ")", ":", "# TODO: make pretty/compact into one bool?", "if", "encoder", "is", "None", ":", "...
Save data to json file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) :type pretty: bool :param compact: Format d...
[ "Save", "data", "to", "json", "file" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L204-L257
train
the01/python-flotils
flotils/loadable.py
load_yaml_file
def load_yaml_file(file): """ Load data from yaml file :param file: Readable object or path to file :type file: FileIO | str | unicode :return: Yaml data :rtype: None | int | float | str | unicode | list | dict """ if not hasattr(file, "read"): with io.open(file, "r", encoding="...
python
def load_yaml_file(file): """ Load data from yaml file :param file: Readable object or path to file :type file: FileIO | str | unicode :return: Yaml data :rtype: None | int | float | str | unicode | list | dict """ if not hasattr(file, "read"): with io.open(file, "r", encoding="...
[ "def", "load_yaml_file", "(", "file", ")", ":", "if", "not", "hasattr", "(", "file", ",", "\"read\"", ")", ":", "with", "io", ".", "open", "(", "file", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "return", "yaml", ".", "lo...
Load data from yaml file :param file: Readable object or path to file :type file: FileIO | str | unicode :return: Yaml data :rtype: None | int | float | str | unicode | list | dict
[ "Load", "data", "from", "yaml", "file" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L272-L284
train
the01/python-flotils
flotils/loadable.py
save_yaml_file
def save_yaml_file(file, val): """ Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict """ opened = False if not hasattr(file, "write")...
python
def save_yaml_file(file, val): """ Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict """ opened = False if not hasattr(file, "write")...
[ "def", "save_yaml_file", "(", "file", ",", "val", ")", ":", "opened", "=", "False", "if", "not", "hasattr", "(", "file", ",", "\"write\"", ")", ":", "file", "=", "io", ".", "open", "(", "file", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", ...
Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict
[ "Save", "data", "to", "yaml", "file" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L299-L318
train
the01/python-flotils
flotils/loadable.py
load_file
def load_file(path): """ Load file :param path: Path to file :type path: str | unicode :return: Loaded data :rtype: None | int | float | str | unicode | list | dict :raises IOError: If file not found or error accessing file """ res = {} if not path: IOError("No path spe...
python
def load_file(path): """ Load file :param path: Path to file :type path: str | unicode :return: Loaded data :rtype: None | int | float | str | unicode | list | dict :raises IOError: If file not found or error accessing file """ res = {} if not path: IOError("No path spe...
[ "def", "load_file", "(", "path", ")", ":", "res", "=", "{", "}", "if", "not", "path", ":", "IOError", "(", "\"No path specified to save\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "raise", "IOError", "(", "\"File not ...
Load file :param path: Path to file :type path: str | unicode :return: Loaded data :rtype: None | int | float | str | unicode | list | dict :raises IOError: If file not found or error accessing file
[ "Load", "file" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L321-L349
train
the01/python-flotils
flotils/loadable.py
save_file
def save_file(path, data, readable=False): """ Save to file :param path: File path to save :type path: str | unicode :param data: Data to save :type data: None | int | float | str | unicode | list | dict :param readable: Format file to be human readable (default: False) :type readable: ...
python
def save_file(path, data, readable=False): """ Save to file :param path: File path to save :type path: str | unicode :param data: Data to save :type data: None | int | float | str | unicode | list | dict :param readable: Format file to be human readable (default: False) :type readable: ...
[ "def", "save_file", "(", "path", ",", "data", ",", "readable", "=", "False", ")", ":", "if", "not", "path", ":", "IOError", "(", "\"No path specified to save\"", ")", "try", ":", "with", "io", ".", "open", "(", "path", ",", "\"w\"", ",", "encoding", "=...
Save to file :param path: File path to save :type path: str | unicode :param data: Data to save :type data: None | int | float | str | unicode | list | dict :param readable: Format file to be human readable (default: False) :type readable: bool :rtype: None :raises IOError: If empty pat...
[ "Save", "to", "file" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L352-L383
train
the01/python-flotils
flotils/loadable.py
join_path_prefix
def join_path_prefix(path, pre_path=None): """ If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str |...
python
def join_path_prefix(path, pre_path=None): """ If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str |...
[ "def", "join_path_prefix", "(", "path", ",", "pre_path", "=", "None", ")", ":", "if", "not", "path", ":", "return", "path", "if", "pre_path", "and", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "os", ".", "path", ".", "j...
If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str | None
[ "If", "path", "set", "and", "not", "absolute", "append", "it", "to", "pre", "path", "(", "if", "used", ")" ]
5954712776bb590107e5b2f4362d010bf74f77a1
https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L386-L403
train