id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
2,700
firecat53/urlscan
urlscan/urlscan.py
extract_with_context
def extract_with_context(lst, pred, before_context, after_context): """Extract URL and context from a given chunk. """ rval = [] start = 0 length = 0 while start < len(lst): usedfirst = False usedlast = False # Extend to the next match. while start + length < len(lst) and length < before_context + 1 \ and not pred(lst[start + length]): length += 1 # Slide to the next match. while start + length < len(lst) and not pred(lst[start + length]): start += 1 # If there was no next match, abort here (it's easier # to do this than to try to detect this case later). if start + length == len(lst): break # Now extend repeatedly until we can't find anything. while start + length < len(lst) and pred(lst[start + length]): extendlength = 1 # Read in the 'after' context and see if it holds a URL. while extendlength < after_context + 1 and start + length + \ extendlength < len(lst) and \ not pred(lst[start + length + extendlength]): extendlength += 1 length += extendlength if start + length < len(lst) and not pred(lst[start + length]): # Didn't find a matching line, so we either # hit the end or extended to after_context + 1.. # # Now read in possible 'before' context # from the next URL; if we don't find one, # we discard the readahead. extendlength = 1 while extendlength < before_context and start + length + \ extendlength < len(lst) and \ not pred(lst[start + length + extendlength]): extendlength += 1 if start + length + extendlength < len(lst) and \ pred(lst[start + length + extendlength]): length += extendlength if length > 0 and start + length <= len(lst): if start == 0: usedfirst = True if start + length == len(lst): usedlast = True rval.append((lst[start:start + length], usedfirst, usedlast)) start += length length = 0 return rval
python
def extract_with_context(lst, pred, before_context, after_context): rval = [] start = 0 length = 0 while start < len(lst): usedfirst = False usedlast = False # Extend to the next match. while start + length < len(lst) and length < before_context + 1 \ and not pred(lst[start + length]): length += 1 # Slide to the next match. while start + length < len(lst) and not pred(lst[start + length]): start += 1 # If there was no next match, abort here (it's easier # to do this than to try to detect this case later). if start + length == len(lst): break # Now extend repeatedly until we can't find anything. while start + length < len(lst) and pred(lst[start + length]): extendlength = 1 # Read in the 'after' context and see if it holds a URL. while extendlength < after_context + 1 and start + length + \ extendlength < len(lst) and \ not pred(lst[start + length + extendlength]): extendlength += 1 length += extendlength if start + length < len(lst) and not pred(lst[start + length]): # Didn't find a matching line, so we either # hit the end or extended to after_context + 1.. # # Now read in possible 'before' context # from the next URL; if we don't find one, # we discard the readahead. extendlength = 1 while extendlength < before_context and start + length + \ extendlength < len(lst) and \ not pred(lst[start + length + extendlength]): extendlength += 1 if start + length + extendlength < len(lst) and \ pred(lst[start + length + extendlength]): length += extendlength if length > 0 and start + length <= len(lst): if start == 0: usedfirst = True if start + length == len(lst): usedlast = True rval.append((lst[start:start + length], usedfirst, usedlast)) start += length length = 0 return rval
[ "def", "extract_with_context", "(", "lst", ",", "pred", ",", "before_context", ",", "after_context", ")", ":", "rval", "=", "[", "]", "start", "=", "0", "length", "=", "0", "while", "start", "<", "len", "(", "lst", ")", ":", "usedfirst", "=", "False", "usedlast", "=", "False", "# Extend to the next match.", "while", "start", "+", "length", "<", "len", "(", "lst", ")", "and", "length", "<", "before_context", "+", "1", "and", "not", "pred", "(", "lst", "[", "start", "+", "length", "]", ")", ":", "length", "+=", "1", "# Slide to the next match.", "while", "start", "+", "length", "<", "len", "(", "lst", ")", "and", "not", "pred", "(", "lst", "[", "start", "+", "length", "]", ")", ":", "start", "+=", "1", "# If there was no next match, abort here (it's easier", "# to do this than to try to detect this case later).", "if", "start", "+", "length", "==", "len", "(", "lst", ")", ":", "break", "# Now extend repeatedly until we can't find anything.", "while", "start", "+", "length", "<", "len", "(", "lst", ")", "and", "pred", "(", "lst", "[", "start", "+", "length", "]", ")", ":", "extendlength", "=", "1", "# Read in the 'after' context and see if it holds a URL.", "while", "extendlength", "<", "after_context", "+", "1", "and", "start", "+", "length", "+", "extendlength", "<", "len", "(", "lst", ")", "and", "not", "pred", "(", "lst", "[", "start", "+", "length", "+", "extendlength", "]", ")", ":", "extendlength", "+=", "1", "length", "+=", "extendlength", "if", "start", "+", "length", "<", "len", "(", "lst", ")", "and", "not", "pred", "(", "lst", "[", "start", "+", "length", "]", ")", ":", "# Didn't find a matching line, so we either", "# hit the end or extended to after_context + 1..", "#", "# Now read in possible 'before' context", "# from the next URL; if we don't find one,", "# we discard the readahead.", "extendlength", "=", "1", "while", "extendlength", "<", "before_context", "and", "start", "+", "length", "+", "extendlength", "<", "len", "(", "lst", ")", "and", "not", "pred", "(", "lst", "[", "start", "+", "length", "+", "extendlength", "]", ")", ":", "extendlength", "+=", "1", "if", "start", "+", "length", "+", "extendlength", "<", "len", "(", "lst", ")", "and", "pred", "(", "lst", "[", "start", "+", "length", "+", "extendlength", "]", ")", ":", "length", "+=", "extendlength", "if", "length", ">", "0", "and", "start", "+", "length", "<=", "len", "(", "lst", ")", ":", "if", "start", "==", "0", ":", "usedfirst", "=", "True", "if", "start", "+", "length", "==", "len", "(", "lst", ")", ":", "usedlast", "=", "True", "rval", ".", "append", "(", "(", "lst", "[", "start", ":", "start", "+", "length", "]", ",", "usedfirst", ",", "usedlast", ")", ")", "start", "+=", "length", "length", "=", "0", "return", "rval" ]
Extract URL and context from a given chunk.
[ "Extract", "URL", "and", "context", "from", "a", "given", "chunk", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L335-L394
2,701
firecat53/urlscan
urlscan/urlscan.py
extracturls
def extracturls(mesg): """Given a text message, extract all the URLs found in the message, along with their surrounding context. The output is a list of sequences of Chunk objects, corresponding to the contextual regions extracted from the string. """ lines = NLRE.split(mesg) # The number of lines of context above to provide. # above_context = 1 # The number of lines of context below to provide. # below_context = 1 # Plan here is to first transform lines into the form # [line_fragments] where each fragment is a chunk as # seen by parse_text_urls. Note that this means that # lines with more than one entry or one entry that's # a URL are the only lines containing URLs. linechunks = [parse_text_urls(l) for l in lines] return extract_with_context(linechunks, lambda chunk: len(chunk) > 1 or (len(chunk) == 1 and chunk[0].url is not None), 1, 1)
python
def extracturls(mesg): lines = NLRE.split(mesg) # The number of lines of context above to provide. # above_context = 1 # The number of lines of context below to provide. # below_context = 1 # Plan here is to first transform lines into the form # [line_fragments] where each fragment is a chunk as # seen by parse_text_urls. Note that this means that # lines with more than one entry or one entry that's # a URL are the only lines containing URLs. linechunks = [parse_text_urls(l) for l in lines] return extract_with_context(linechunks, lambda chunk: len(chunk) > 1 or (len(chunk) == 1 and chunk[0].url is not None), 1, 1)
[ "def", "extracturls", "(", "mesg", ")", ":", "lines", "=", "NLRE", ".", "split", "(", "mesg", ")", "# The number of lines of context above to provide.", "# above_context = 1", "# The number of lines of context below to provide.", "# below_context = 1", "# Plan here is to first transform lines into the form", "# [line_fragments] where each fragment is a chunk as", "# seen by parse_text_urls. Note that this means that", "# lines with more than one entry or one entry that's", "# a URL are the only lines containing URLs.", "linechunks", "=", "[", "parse_text_urls", "(", "l", ")", "for", "l", "in", "lines", "]", "return", "extract_with_context", "(", "linechunks", ",", "lambda", "chunk", ":", "len", "(", "chunk", ")", ">", "1", "or", "(", "len", "(", "chunk", ")", "==", "1", "and", "chunk", "[", "0", "]", ".", "url", "is", "not", "None", ")", ",", "1", ",", "1", ")" ]
Given a text message, extract all the URLs found in the message, along with their surrounding context. The output is a list of sequences of Chunk objects, corresponding to the contextual regions extracted from the string.
[ "Given", "a", "text", "message", "extract", "all", "the", "URLs", "found", "in", "the", "message", "along", "with", "their", "surrounding", "context", ".", "The", "output", "is", "a", "list", "of", "sequences", "of", "Chunk", "objects", "corresponding", "to", "the", "contextual", "regions", "extracted", "from", "the", "string", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L400-L424
2,702
firecat53/urlscan
urlscan/urlscan.py
extracthtmlurls
def extracthtmlurls(mesg): """Extract URLs with context from html type message. Similar to extracturls. """ chunk = HTMLChunker() chunk.feed(mesg) chunk.close() # above_context = 1 # below_context = 1 def somechunkisurl(chunks): for chnk in chunks: if chnk.url is not None: return True return False return extract_with_context(chunk.rval, somechunkisurl, 1, 1)
python
def extracthtmlurls(mesg): chunk = HTMLChunker() chunk.feed(mesg) chunk.close() # above_context = 1 # below_context = 1 def somechunkisurl(chunks): for chnk in chunks: if chnk.url is not None: return True return False return extract_with_context(chunk.rval, somechunkisurl, 1, 1)
[ "def", "extracthtmlurls", "(", "mesg", ")", ":", "chunk", "=", "HTMLChunker", "(", ")", "chunk", ".", "feed", "(", "mesg", ")", "chunk", ".", "close", "(", ")", "# above_context = 1", "# below_context = 1", "def", "somechunkisurl", "(", "chunks", ")", ":", "for", "chnk", "in", "chunks", ":", "if", "chnk", ".", "url", "is", "not", "None", ":", "return", "True", "return", "False", "return", "extract_with_context", "(", "chunk", ".", "rval", ",", "somechunkisurl", ",", "1", ",", "1", ")" ]
Extract URLs with context from html type message. Similar to extracturls.
[ "Extract", "URLs", "with", "context", "from", "html", "type", "message", ".", "Similar", "to", "extracturls", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L427-L443
2,703
firecat53/urlscan
urlscan/urlscan.py
decode_bytes
def decode_bytes(byt, enc='utf-8'): """Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string. """ try: strg = byt.decode(enc) except UnicodeDecodeError as err: strg = "Unable to decode message:\n{}\n{}".format(str(byt), err) except (AttributeError, UnicodeEncodeError): # If byt is already a string, just return it return byt return strg
python
def decode_bytes(byt, enc='utf-8'): try: strg = byt.decode(enc) except UnicodeDecodeError as err: strg = "Unable to decode message:\n{}\n{}".format(str(byt), err) except (AttributeError, UnicodeEncodeError): # If byt is already a string, just return it return byt return strg
[ "def", "decode_bytes", "(", "byt", ",", "enc", "=", "'utf-8'", ")", ":", "try", ":", "strg", "=", "byt", ".", "decode", "(", "enc", ")", "except", "UnicodeDecodeError", "as", "err", ":", "strg", "=", "\"Unable to decode message:\\n{}\\n{}\"", ".", "format", "(", "str", "(", "byt", ")", ",", "err", ")", "except", "(", "AttributeError", ",", "UnicodeEncodeError", ")", ":", "# If byt is already a string, just return it", "return", "byt", "return", "strg" ]
Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string.
[ "Given", "a", "string", "or", "bytes", "input", "return", "a", "string", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L446-L460
2,704
firecat53/urlscan
urlscan/urlscan.py
decode_msg
def decode_msg(msg, enc='utf-8'): """ Decodes a message fragment. Args: msg - A Message object representing the fragment enc - The encoding to use for decoding the message """ # We avoid the get_payload decoding machinery for raw # content-transfer-encodings potentially containing non-ascii characters, # such as 8bit or binary, as these are encoded using raw-unicode-escape which # seems to prevent subsequent utf-8 decoding. cte = str(msg.get('content-transfer-encoding', '')).lower() decode = cte not in ("8bit", "7bit", "binary") res = msg.get_payload(decode=decode) return decode_bytes(res, enc)
python
def decode_msg(msg, enc='utf-8'): # We avoid the get_payload decoding machinery for raw # content-transfer-encodings potentially containing non-ascii characters, # such as 8bit or binary, as these are encoded using raw-unicode-escape which # seems to prevent subsequent utf-8 decoding. cte = str(msg.get('content-transfer-encoding', '')).lower() decode = cte not in ("8bit", "7bit", "binary") res = msg.get_payload(decode=decode) return decode_bytes(res, enc)
[ "def", "decode_msg", "(", "msg", ",", "enc", "=", "'utf-8'", ")", ":", "# We avoid the get_payload decoding machinery for raw", "# content-transfer-encodings potentially containing non-ascii characters,", "# such as 8bit or binary, as these are encoded using raw-unicode-escape which", "# seems to prevent subsequent utf-8 decoding.", "cte", "=", "str", "(", "msg", ".", "get", "(", "'content-transfer-encoding'", ",", "''", ")", ")", ".", "lower", "(", ")", "decode", "=", "cte", "not", "in", "(", "\"8bit\"", ",", "\"7bit\"", ",", "\"binary\"", ")", "res", "=", "msg", ".", "get_payload", "(", "decode", "=", "decode", ")", "return", "decode_bytes", "(", "res", ",", "enc", ")" ]
Decodes a message fragment. Args: msg - A Message object representing the fragment enc - The encoding to use for decoding the message
[ "Decodes", "a", "message", "fragment", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L463-L477
2,705
firecat53/urlscan
urlscan/urlscan.py
msgurls
def msgurls(msg, urlidx=1): """Main entry function for urlscan.py """ # Written as a generator so I can easily choose only # one subpart in the future (e.g., for # multipart/alternative). Actually, I might even add # a browser for the message structure? enc = get_charset(msg) if msg.is_multipart(): for part in msg.get_payload(): for chunk in msgurls(part, urlidx): urlidx += 1 yield chunk elif msg.get_content_type() == "text/plain": decoded = decode_msg(msg, enc) for chunk in extracturls(decoded): urlidx += 1 yield chunk elif msg.get_content_type() == "text/html": decoded = decode_msg(msg, enc) for chunk in extracthtmlurls(decoded): urlidx += 1 yield chunk
python
def msgurls(msg, urlidx=1): # Written as a generator so I can easily choose only # one subpart in the future (e.g., for # multipart/alternative). Actually, I might even add # a browser for the message structure? enc = get_charset(msg) if msg.is_multipart(): for part in msg.get_payload(): for chunk in msgurls(part, urlidx): urlidx += 1 yield chunk elif msg.get_content_type() == "text/plain": decoded = decode_msg(msg, enc) for chunk in extracturls(decoded): urlidx += 1 yield chunk elif msg.get_content_type() == "text/html": decoded = decode_msg(msg, enc) for chunk in extracthtmlurls(decoded): urlidx += 1 yield chunk
[ "def", "msgurls", "(", "msg", ",", "urlidx", "=", "1", ")", ":", "# Written as a generator so I can easily choose only", "# one subpart in the future (e.g., for", "# multipart/alternative). Actually, I might even add", "# a browser for the message structure?", "enc", "=", "get_charset", "(", "msg", ")", "if", "msg", ".", "is_multipart", "(", ")", ":", "for", "part", "in", "msg", ".", "get_payload", "(", ")", ":", "for", "chunk", "in", "msgurls", "(", "part", ",", "urlidx", ")", ":", "urlidx", "+=", "1", "yield", "chunk", "elif", "msg", ".", "get_content_type", "(", ")", "==", "\"text/plain\"", ":", "decoded", "=", "decode_msg", "(", "msg", ",", "enc", ")", "for", "chunk", "in", "extracturls", "(", "decoded", ")", ":", "urlidx", "+=", "1", "yield", "chunk", "elif", "msg", ".", "get_content_type", "(", ")", "==", "\"text/html\"", ":", "decoded", "=", "decode_msg", "(", "msg", ",", "enc", ")", "for", "chunk", "in", "extracthtmlurls", "(", "decoded", ")", ":", "urlidx", "+=", "1", "yield", "chunk" ]
Main entry function for urlscan.py
[ "Main", "entry", "function", "for", "urlscan", ".", "py" ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L480-L503
2,706
firecat53/urlscan
urlscan/urlchoose.py
shorten_url
def shorten_url(url, cols, shorten): """Shorten long URLs to fit on one line. """ cols = ((cols - 6) * .85) # 6 cols for urlref and don't use while line if shorten is False or len(url) < cols: return url split = int(cols * .5) return url[:split] + "..." + url[-split:]
python
def shorten_url(url, cols, shorten): cols = ((cols - 6) * .85) # 6 cols for urlref and don't use while line if shorten is False or len(url) < cols: return url split = int(cols * .5) return url[:split] + "..." + url[-split:]
[ "def", "shorten_url", "(", "url", ",", "cols", ",", "shorten", ")", ":", "cols", "=", "(", "(", "cols", "-", "6", ")", "*", ".85", ")", "# 6 cols for urlref and don't use while line", "if", "shorten", "is", "False", "or", "len", "(", "url", ")", "<", "cols", ":", "return", "url", "split", "=", "int", "(", "cols", "*", ".5", ")", "return", "url", "[", ":", "split", "]", "+", "\"...\"", "+", "url", "[", "-", "split", ":", "]" ]
Shorten long URLs to fit on one line.
[ "Shorten", "long", "URLs", "to", "fit", "on", "one", "line", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L43-L51
2,707
firecat53/urlscan
urlscan/urlchoose.py
splittext
def splittext(text, search, attr): """Split a text string by search string and add Urwid display attribute to the search term. Args: text - string search - search string attr - attribute string to add Returns: urwid markup list ["string", ("default", " mo"), "re string"] for search="mo", text="string more string" and attr="default" """ if search: pat = re.compile("({})".format(re.escape(search)), re.IGNORECASE) else: return text final = pat.split(text) final = [(attr, i) if i.lower() == search.lower() else i for i in final] return final
python
def splittext(text, search, attr): if search: pat = re.compile("({})".format(re.escape(search)), re.IGNORECASE) else: return text final = pat.split(text) final = [(attr, i) if i.lower() == search.lower() else i for i in final] return final
[ "def", "splittext", "(", "text", ",", "search", ",", "attr", ")", ":", "if", "search", ":", "pat", "=", "re", ".", "compile", "(", "\"({})\"", ".", "format", "(", "re", ".", "escape", "(", "search", ")", ")", ",", "re", ".", "IGNORECASE", ")", "else", ":", "return", "text", "final", "=", "pat", ".", "split", "(", "text", ")", "final", "=", "[", "(", "attr", ",", "i", ")", "if", "i", ".", "lower", "(", ")", "==", "search", ".", "lower", "(", ")", "else", "i", "for", "i", "in", "final", "]", "return", "final" ]
Split a text string by search string and add Urwid display attribute to the search term. Args: text - string search - search string attr - attribute string to add Returns: urwid markup list ["string", ("default", " mo"), "re string"] for search="mo", text="string more string" and attr="default"
[ "Split", "a", "text", "string", "by", "search", "string", "and", "add", "Urwid", "display", "attribute", "to", "the", "search", "term", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L71-L89
2,708
firecat53/urlscan
urlscan/urlchoose.py
URLChooser.main
def main(self): """Urwid main event loop """ self.loop = urwid.MainLoop(self.top, self.palettes[self.palette_names[0]], screen=self.tui, handle_mouse=False, input_filter=self.handle_keys, unhandled_input=self.unhandled) self.loop.run()
python
def main(self): self.loop = urwid.MainLoop(self.top, self.palettes[self.palette_names[0]], screen=self.tui, handle_mouse=False, input_filter=self.handle_keys, unhandled_input=self.unhandled) self.loop.run()
[ "def", "main", "(", "self", ")", ":", "self", ".", "loop", "=", "urwid", ".", "MainLoop", "(", "self", ".", "top", ",", "self", ".", "palettes", "[", "self", ".", "palette_names", "[", "0", "]", "]", ",", "screen", "=", "self", ".", "tui", ",", "handle_mouse", "=", "False", ",", "input_filter", "=", "self", ".", "handle_keys", ",", "unhandled_input", "=", "self", ".", "unhandled", ")", "self", ".", "loop", ".", "run", "(", ")" ]
Urwid main event loop
[ "Urwid", "main", "event", "loop" ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L213-L220
2,709
firecat53/urlscan
urlscan/urlchoose.py
URLChooser.handle_keys
def handle_keys(self, keys, raw): """Handle widget default keys - 'Enter' or 'space' to load URL - 'Enter' to end search mode - add 'space' to search string in search mode - Workaround some small positioning bugs """ for j, k in enumerate(keys): if self.search is True: text = "Search: {}".format(self.search_string) if k == 'enter': # Catch 'enter' key to prevent opening URL in mkbrowseto self.enter = True if not self.items: self.search = False self.enter = False if self.search_string: footer = 'search' else: footer = 'default' text = "" footerwid = urwid.AttrMap(urwid.Text(text), footer) self.top.footer = footerwid elif k in self.activate_keys: self.search_string += k self._search() elif k == 'backspace': self.search_string = self.search_string[:-1] self._search() elif k in self.activate_keys and \ self.urls and \ self.search is False and \ self.help_menu is False: self._open_url() elif self.help_menu is True: self._help_menu() return [] if k == 'up': # Works around bug where the up arrow goes higher than the top list # item and unintentionally triggers context and palette switches. # Remaps 'up' to 'k' keys[j] = 'k' if k == 'home': # Remap 'home' to 'g'. Works around small bug where 'home' takes the cursor # above the top list item. keys[j] = 'g' # filter backspace out before the widget, it has a weird interaction return [i for i in keys if i != 'backspace']
python
def handle_keys(self, keys, raw): for j, k in enumerate(keys): if self.search is True: text = "Search: {}".format(self.search_string) if k == 'enter': # Catch 'enter' key to prevent opening URL in mkbrowseto self.enter = True if not self.items: self.search = False self.enter = False if self.search_string: footer = 'search' else: footer = 'default' text = "" footerwid = urwid.AttrMap(urwid.Text(text), footer) self.top.footer = footerwid elif k in self.activate_keys: self.search_string += k self._search() elif k == 'backspace': self.search_string = self.search_string[:-1] self._search() elif k in self.activate_keys and \ self.urls and \ self.search is False and \ self.help_menu is False: self._open_url() elif self.help_menu is True: self._help_menu() return [] if k == 'up': # Works around bug where the up arrow goes higher than the top list # item and unintentionally triggers context and palette switches. # Remaps 'up' to 'k' keys[j] = 'k' if k == 'home': # Remap 'home' to 'g'. Works around small bug where 'home' takes the cursor # above the top list item. keys[j] = 'g' # filter backspace out before the widget, it has a weird interaction return [i for i in keys if i != 'backspace']
[ "def", "handle_keys", "(", "self", ",", "keys", ",", "raw", ")", ":", "for", "j", ",", "k", "in", "enumerate", "(", "keys", ")", ":", "if", "self", ".", "search", "is", "True", ":", "text", "=", "\"Search: {}\"", ".", "format", "(", "self", ".", "search_string", ")", "if", "k", "==", "'enter'", ":", "# Catch 'enter' key to prevent opening URL in mkbrowseto", "self", ".", "enter", "=", "True", "if", "not", "self", ".", "items", ":", "self", ".", "search", "=", "False", "self", ".", "enter", "=", "False", "if", "self", ".", "search_string", ":", "footer", "=", "'search'", "else", ":", "footer", "=", "'default'", "text", "=", "\"\"", "footerwid", "=", "urwid", ".", "AttrMap", "(", "urwid", ".", "Text", "(", "text", ")", ",", "footer", ")", "self", ".", "top", ".", "footer", "=", "footerwid", "elif", "k", "in", "self", ".", "activate_keys", ":", "self", ".", "search_string", "+=", "k", "self", ".", "_search", "(", ")", "elif", "k", "==", "'backspace'", ":", "self", ".", "search_string", "=", "self", ".", "search_string", "[", ":", "-", "1", "]", "self", ".", "_search", "(", ")", "elif", "k", "in", "self", ".", "activate_keys", "and", "self", ".", "urls", "and", "self", ".", "search", "is", "False", "and", "self", ".", "help_menu", "is", "False", ":", "self", ".", "_open_url", "(", ")", "elif", "self", ".", "help_menu", "is", "True", ":", "self", ".", "_help_menu", "(", ")", "return", "[", "]", "if", "k", "==", "'up'", ":", "# Works around bug where the up arrow goes higher than the top list", "# item and unintentionally triggers context and palette switches.", "# Remaps 'up' to 'k'", "keys", "[", "j", "]", "=", "'k'", "if", "k", "==", "'home'", ":", "# Remap 'home' to 'g'. Works around small bug where 'home' takes the cursor", "# above the top list item.", "keys", "[", "j", "]", "=", "'g'", "# filter backspace out before the widget, it has a weird interaction", "return", "[", "i", "for", "i", "in", "keys", "if", "i", "!=", "'backspace'", "]" ]
Handle widget default keys - 'Enter' or 'space' to load URL - 'Enter' to end search mode - add 'space' to search string in search mode - Workaround some small positioning bugs
[ "Handle", "widget", "default", "keys" ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L222-L271
2,710
firecat53/urlscan
urlscan/urlchoose.py
URLChooser.unhandled
def unhandled(self, key): """Handle other keyboard actions not handled by the ListBox widget. """ self.key = key self.size = self.tui.get_cols_rows() if self.search is True: if self.enter is False and self.no_matches is False: if len(key) == 1 and key.isprintable(): self.search_string += key self._search() elif self.enter is True and not self.search_string: self.search = False self.enter = False return if not self.urls and key not in "Qq": return # No other actions are useful with no URLs if self.help_menu is False: try: self.keys[key]() except KeyError: pass
python
def unhandled(self, key): self.key = key self.size = self.tui.get_cols_rows() if self.search is True: if self.enter is False and self.no_matches is False: if len(key) == 1 and key.isprintable(): self.search_string += key self._search() elif self.enter is True and not self.search_string: self.search = False self.enter = False return if not self.urls and key not in "Qq": return # No other actions are useful with no URLs if self.help_menu is False: try: self.keys[key]() except KeyError: pass
[ "def", "unhandled", "(", "self", ",", "key", ")", ":", "self", ".", "key", "=", "key", "self", ".", "size", "=", "self", ".", "tui", ".", "get_cols_rows", "(", ")", "if", "self", ".", "search", "is", "True", ":", "if", "self", ".", "enter", "is", "False", "and", "self", ".", "no_matches", "is", "False", ":", "if", "len", "(", "key", ")", "==", "1", "and", "key", ".", "isprintable", "(", ")", ":", "self", ".", "search_string", "+=", "key", "self", ".", "_search", "(", ")", "elif", "self", ".", "enter", "is", "True", "and", "not", "self", ".", "search_string", ":", "self", ".", "search", "=", "False", "self", ".", "enter", "=", "False", "return", "if", "not", "self", ".", "urls", "and", "key", "not", "in", "\"Qq\"", ":", "return", "# No other actions are useful with no URLs", "if", "self", ".", "help_menu", "is", "False", ":", "try", ":", "self", ".", "keys", "[", "key", "]", "(", ")", "except", "KeyError", ":", "pass" ]
Handle other keyboard actions not handled by the ListBox widget.
[ "Handle", "other", "keyboard", "actions", "not", "handled", "by", "the", "ListBox", "widget", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L273-L294
2,711
firecat53/urlscan
urlscan/urlchoose.py
URLChooser._digits
def _digits(self): """ 0-9 """ self.number += self.key try: if self.compact is False: self.top.body.focus_position = \ self.items.index(self.items_com[max(int(self.number) - 1, 0)]) else: self.top.body.focus_position = \ self.items.index(self.items[max(int(self.number) - 1, 0)]) except IndexError: self.number = self.number[:-1] self.top.keypress(self.size, "") # Trick urwid into redisplaying the cursor if self.number: self._footer_start_thread("Selection: {}".format(self.number), 1)
python
def _digits(self): self.number += self.key try: if self.compact is False: self.top.body.focus_position = \ self.items.index(self.items_com[max(int(self.number) - 1, 0)]) else: self.top.body.focus_position = \ self.items.index(self.items[max(int(self.number) - 1, 0)]) except IndexError: self.number = self.number[:-1] self.top.keypress(self.size, "") # Trick urwid into redisplaying the cursor if self.number: self._footer_start_thread("Selection: {}".format(self.number), 1)
[ "def", "_digits", "(", "self", ")", ":", "self", ".", "number", "+=", "self", ".", "key", "try", ":", "if", "self", ".", "compact", "is", "False", ":", "self", ".", "top", ".", "body", ".", "focus_position", "=", "self", ".", "items", ".", "index", "(", "self", ".", "items_com", "[", "max", "(", "int", "(", "self", ".", "number", ")", "-", "1", ",", "0", ")", "]", ")", "else", ":", "self", ".", "top", ".", "body", ".", "focus_position", "=", "self", ".", "items", ".", "index", "(", "self", ".", "items", "[", "max", "(", "int", "(", "self", ".", "number", ")", "-", "1", ",", "0", ")", "]", ")", "except", "IndexError", ":", "self", ".", "number", "=", "self", ".", "number", "[", ":", "-", "1", "]", "self", ".", "top", ".", "keypress", "(", "self", ".", "size", ",", "\"\"", ")", "# Trick urwid into redisplaying the cursor", "if", "self", ".", "number", ":", "self", ".", "_footer_start_thread", "(", "\"Selection: {}\"", ".", "format", "(", "self", ".", "number", ")", ",", "1", ")" ]
0-9
[ "0", "-", "9" ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L357-L371
2,712
firecat53/urlscan
urlscan/urlchoose.py
URLChooser._search
def _search(self): """ Search - search URLs and text. """ text = "Search: {}".format(self.search_string) footerwid = urwid.AttrMap(urwid.Text(text), 'footer') self.top.footer = footerwid search_items = [] for grp in self.items_org: done = False for idx, item in enumerate(grp): if isinstance(item, urwid.Columns): for col_idx, col in enumerate(item.contents): if isinstance(col[0], urwid.decoration.AttrMap): grp[idx][col_idx].set_label(splittext(col[0].base_widget.label, self.search_string, '')) if self.search_string.lower() in col[0].base_widget.label.lower(): grp[idx][col_idx].set_label(splittext(col[0].base_widget.label, self.search_string, 'search')) done = True elif isinstance(item, urwid.Text): grp[idx].set_text(splittext(item.text, self.search_string, '')) if self.search_string.lower() in item.text.lower(): grp[idx].set_text(splittext(item.text, self.search_string, 'search')) done = True if done is True: search_items.extend(grp) self.items = search_items self.top.body = urwid.ListBox(self.items) if self.items: self.top.body.focus_position = 2 if self.compact is False else 0 # Trick urwid into redisplaying the cursor self.top.keypress(self.tui.get_cols_rows(), "") self.no_matches = False else: self.no_matches = True footerwid = urwid.AttrMap(urwid.Text(text + " No Matches"), 'footer') self.top.footer = footerwid
python
def _search(self): text = "Search: {}".format(self.search_string) footerwid = urwid.AttrMap(urwid.Text(text), 'footer') self.top.footer = footerwid search_items = [] for grp in self.items_org: done = False for idx, item in enumerate(grp): if isinstance(item, urwid.Columns): for col_idx, col in enumerate(item.contents): if isinstance(col[0], urwid.decoration.AttrMap): grp[idx][col_idx].set_label(splittext(col[0].base_widget.label, self.search_string, '')) if self.search_string.lower() in col[0].base_widget.label.lower(): grp[idx][col_idx].set_label(splittext(col[0].base_widget.label, self.search_string, 'search')) done = True elif isinstance(item, urwid.Text): grp[idx].set_text(splittext(item.text, self.search_string, '')) if self.search_string.lower() in item.text.lower(): grp[idx].set_text(splittext(item.text, self.search_string, 'search')) done = True if done is True: search_items.extend(grp) self.items = search_items self.top.body = urwid.ListBox(self.items) if self.items: self.top.body.focus_position = 2 if self.compact is False else 0 # Trick urwid into redisplaying the cursor self.top.keypress(self.tui.get_cols_rows(), "") self.no_matches = False else: self.no_matches = True footerwid = urwid.AttrMap(urwid.Text(text + " No Matches"), 'footer') self.top.footer = footerwid
[ "def", "_search", "(", "self", ")", ":", "text", "=", "\"Search: {}\"", ".", "format", "(", "self", ".", "search_string", ")", "footerwid", "=", "urwid", ".", "AttrMap", "(", "urwid", ".", "Text", "(", "text", ")", ",", "'footer'", ")", "self", ".", "top", ".", "footer", "=", "footerwid", "search_items", "=", "[", "]", "for", "grp", "in", "self", ".", "items_org", ":", "done", "=", "False", "for", "idx", ",", "item", "in", "enumerate", "(", "grp", ")", ":", "if", "isinstance", "(", "item", ",", "urwid", ".", "Columns", ")", ":", "for", "col_idx", ",", "col", "in", "enumerate", "(", "item", ".", "contents", ")", ":", "if", "isinstance", "(", "col", "[", "0", "]", ",", "urwid", ".", "decoration", ".", "AttrMap", ")", ":", "grp", "[", "idx", "]", "[", "col_idx", "]", ".", "set_label", "(", "splittext", "(", "col", "[", "0", "]", ".", "base_widget", ".", "label", ",", "self", ".", "search_string", ",", "''", ")", ")", "if", "self", ".", "search_string", ".", "lower", "(", ")", "in", "col", "[", "0", "]", ".", "base_widget", ".", "label", ".", "lower", "(", ")", ":", "grp", "[", "idx", "]", "[", "col_idx", "]", ".", "set_label", "(", "splittext", "(", "col", "[", "0", "]", ".", "base_widget", ".", "label", ",", "self", ".", "search_string", ",", "'search'", ")", ")", "done", "=", "True", "elif", "isinstance", "(", "item", ",", "urwid", ".", "Text", ")", ":", "grp", "[", "idx", "]", ".", "set_text", "(", "splittext", "(", "item", ".", "text", ",", "self", ".", "search_string", ",", "''", ")", ")", "if", "self", ".", "search_string", ".", "lower", "(", ")", "in", "item", ".", "text", ".", "lower", "(", ")", ":", "grp", "[", "idx", "]", ".", "set_text", "(", "splittext", "(", "item", ".", "text", ",", "self", ".", "search_string", ",", "'search'", ")", ")", "done", "=", "True", "if", "done", "is", "True", ":", "search_items", ".", "extend", "(", "grp", ")", "self", ".", "items", "=", "search_items", "self", ".", "top", ".", "body", "=", "urwid", ".", "ListBox", "(", "self", ".", "items", ")", "if", "self", ".", "items", ":", "self", ".", "top", ".", "body", ".", "focus_position", "=", "2", "if", "self", ".", "compact", "is", "False", "else", "0", "# Trick urwid into redisplaying the cursor", "self", ".", "top", ".", "keypress", "(", "self", ".", "tui", ".", "get_cols_rows", "(", ")", ",", "\"\"", ")", "self", ".", "no_matches", "=", "False", "else", ":", "self", ".", "no_matches", "=", "True", "footerwid", "=", "urwid", ".", "AttrMap", "(", "urwid", ".", "Text", "(", "text", "+", "\" No Matches\"", ")", ",", "'footer'", ")", "self", ".", "top", ".", "footer", "=", "footerwid" ]
Search - search URLs and text.
[ "Search", "-", "search", "URLs", "and", "text", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L547-L586
2,713
firecat53/urlscan
urlscan/urlchoose.py
URLChooser.draw_screen
def draw_screen(self, size): """Render curses screen """ self.tui.clear() canvas = self.top.render(size, focus=True) self.tui.draw_screen(size, canvas)
python
def draw_screen(self, size): self.tui.clear() canvas = self.top.render(size, focus=True) self.tui.draw_screen(size, canvas)
[ "def", "draw_screen", "(", "self", ",", "size", ")", ":", "self", ".", "tui", ".", "clear", "(", ")", "canvas", "=", "self", ".", "top", ".", "render", "(", "size", ",", "focus", "=", "True", ")", "self", ".", "tui", ".", "draw_screen", "(", "size", ",", "canvas", ")" ]
Render curses screen
[ "Render", "curses", "screen" ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L588-L594
2,714
firecat53/urlscan
urlscan/urlchoose.py
URLChooser.mkbrowseto
def mkbrowseto(self, url): """Create the urwid callback function to open the web browser or call another function with the URL. """ # Try-except block to work around webbrowser module bug # https://bugs.python.org/issue31014 try: browser = os.environ['BROWSER'] except KeyError: pass else: del os.environ['BROWSER'] webbrowser.register(browser, None, webbrowser.GenericBrowser(browser)) try_idx = webbrowser._tryorder.index(browser) webbrowser._tryorder.insert(0, webbrowser._tryorder.pop(try_idx)) def browse(*args): # double ()() to ensure self.search evaluated at runtime, not when # browse() is _created_. [0] is self.search, [1] is self.enter # self.enter prevents opening URL when in search mode if self._get_search()[0]() is True: if self._get_search()[1]() is True: self.search = False self.enter = False elif not self.run: webbrowser.open(url) elif self.run and self.pipe: process = Popen(shlex.split(self.run), stdout=PIPE, stdin=PIPE) process.communicate(input=url.encode(sys.getdefaultencoding())) else: Popen(self.run.format(url), shell=True).communicate() size = self.tui.get_cols_rows() self.draw_screen(size) return browse
python
def mkbrowseto(self, url): # Try-except block to work around webbrowser module bug # https://bugs.python.org/issue31014 try: browser = os.environ['BROWSER'] except KeyError: pass else: del os.environ['BROWSER'] webbrowser.register(browser, None, webbrowser.GenericBrowser(browser)) try_idx = webbrowser._tryorder.index(browser) webbrowser._tryorder.insert(0, webbrowser._tryorder.pop(try_idx)) def browse(*args): # double ()() to ensure self.search evaluated at runtime, not when # browse() is _created_. [0] is self.search, [1] is self.enter # self.enter prevents opening URL when in search mode if self._get_search()[0]() is True: if self._get_search()[1]() is True: self.search = False self.enter = False elif not self.run: webbrowser.open(url) elif self.run and self.pipe: process = Popen(shlex.split(self.run), stdout=PIPE, stdin=PIPE) process.communicate(input=url.encode(sys.getdefaultencoding())) else: Popen(self.run.format(url), shell=True).communicate() size = self.tui.get_cols_rows() self.draw_screen(size) return browse
[ "def", "mkbrowseto", "(", "self", ",", "url", ")", ":", "# Try-except block to work around webbrowser module bug", "# https://bugs.python.org/issue31014", "try", ":", "browser", "=", "os", ".", "environ", "[", "'BROWSER'", "]", "except", "KeyError", ":", "pass", "else", ":", "del", "os", ".", "environ", "[", "'BROWSER'", "]", "webbrowser", ".", "register", "(", "browser", ",", "None", ",", "webbrowser", ".", "GenericBrowser", "(", "browser", ")", ")", "try_idx", "=", "webbrowser", ".", "_tryorder", ".", "index", "(", "browser", ")", "webbrowser", ".", "_tryorder", ".", "insert", "(", "0", ",", "webbrowser", ".", "_tryorder", ".", "pop", "(", "try_idx", ")", ")", "def", "browse", "(", "*", "args", ")", ":", "# double ()() to ensure self.search evaluated at runtime, not when", "# browse() is _created_. [0] is self.search, [1] is self.enter", "# self.enter prevents opening URL when in search mode", "if", "self", ".", "_get_search", "(", ")", "[", "0", "]", "(", ")", "is", "True", ":", "if", "self", ".", "_get_search", "(", ")", "[", "1", "]", "(", ")", "is", "True", ":", "self", ".", "search", "=", "False", "self", ".", "enter", "=", "False", "elif", "not", "self", ".", "run", ":", "webbrowser", ".", "open", "(", "url", ")", "elif", "self", ".", "run", "and", "self", ".", "pipe", ":", "process", "=", "Popen", "(", "shlex", ".", "split", "(", "self", ".", "run", ")", ",", "stdout", "=", "PIPE", ",", "stdin", "=", "PIPE", ")", "process", ".", "communicate", "(", "input", "=", "url", ".", "encode", "(", "sys", ".", "getdefaultencoding", "(", ")", ")", ")", "else", ":", "Popen", "(", "self", ".", "run", ".", "format", "(", "url", ")", ",", "shell", "=", "True", ")", ".", "communicate", "(", ")", "size", "=", "self", ".", "tui", ".", "get_cols_rows", "(", ")", "self", ".", "draw_screen", "(", "size", ")", "return", "browse" ]
Create the urwid callback function to open the web browser or call another function with the URL.
[ "Create", "the", "urwid", "callback", "function", "to", "open", "the", "web", "browser", "or", "call", "another", "function", "with", "the", "URL", "." ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L599-L634
2,715
firecat53/urlscan
urlscan/urlchoose.py
URLChooser.process_urls
def process_urls(self, extractedurls, dedupe, shorten): """Process the 'extractedurls' and ready them for either the curses browser or non-interactive output Args: extractedurls dedupe - Remove duplicate URLs from list Returns: items - List of widgets for the ListBox urls - List of all URLs """ cols, _ = urwid.raw_display.Screen().get_cols_rows() items = [] urls = [] first = True for group, usedfirst, usedlast in extractedurls: if first: first = False items.append(urwid.Divider(div_char='-', top=1, bottom=1)) if dedupe is True: # If no unique URLs exist, then skip the group completely if not [chunk for chunks in group for chunk in chunks if chunk.url is not None and chunk.url not in urls]: continue groupurls = [] markup = [] if not usedfirst: markup.append(('msgtext:ellipses', '...\n')) for chunks in group: i = 0 while i < len(chunks): chunk = chunks[i] i += 1 if chunk.url is None: markup.append(('msgtext', chunk.markup)) else: if (dedupe is True and chunk.url not in urls) \ or dedupe is False: urls.append(chunk.url) groupurls.append(chunk.url) # Collect all immediately adjacent # chunks with the same URL. tmpmarkup = [] if chunk.markup: tmpmarkup.append(('msgtext', chunk.markup)) while i < len(chunks) and \ chunks[i].url == chunk.url: if chunks[i].markup: tmpmarkup.append(chunks[i].markup) i += 1 url_idx = urls.index(chunk.url) + 1 if dedupe is True else len(urls) markup += [tmpmarkup or '<URL>', ('urlref:number:braces', ' ['), ('urlref:number', repr(url_idx)), ('urlref:number:braces', ']')] markup += '\n' if not usedlast: markup += [('msgtext:ellipses', '...\n\n')] items.append(urwid.Text(markup)) i = len(urls) - len(groupurls) for url in groupurls: i += 1 markup = [(6, urwid.Text([('urlref:number:braces', '['), ('urlref:number', repr(i)), ('urlref:number:braces', ']'), ' '])), urwid.AttrMap(urwid.Button(shorten_url(url, cols, shorten), self.mkbrowseto(url), user_data=url), 'urlref:url', 'url:sel')] items.append(urwid.Columns(markup)) return items, urls
python
def process_urls(self, extractedurls, dedupe, shorten): cols, _ = urwid.raw_display.Screen().get_cols_rows() items = [] urls = [] first = True for group, usedfirst, usedlast in extractedurls: if first: first = False items.append(urwid.Divider(div_char='-', top=1, bottom=1)) if dedupe is True: # If no unique URLs exist, then skip the group completely if not [chunk for chunks in group for chunk in chunks if chunk.url is not None and chunk.url not in urls]: continue groupurls = [] markup = [] if not usedfirst: markup.append(('msgtext:ellipses', '...\n')) for chunks in group: i = 0 while i < len(chunks): chunk = chunks[i] i += 1 if chunk.url is None: markup.append(('msgtext', chunk.markup)) else: if (dedupe is True and chunk.url not in urls) \ or dedupe is False: urls.append(chunk.url) groupurls.append(chunk.url) # Collect all immediately adjacent # chunks with the same URL. tmpmarkup = [] if chunk.markup: tmpmarkup.append(('msgtext', chunk.markup)) while i < len(chunks) and \ chunks[i].url == chunk.url: if chunks[i].markup: tmpmarkup.append(chunks[i].markup) i += 1 url_idx = urls.index(chunk.url) + 1 if dedupe is True else len(urls) markup += [tmpmarkup or '<URL>', ('urlref:number:braces', ' ['), ('urlref:number', repr(url_idx)), ('urlref:number:braces', ']')] markup += '\n' if not usedlast: markup += [('msgtext:ellipses', '...\n\n')] items.append(urwid.Text(markup)) i = len(urls) - len(groupurls) for url in groupurls: i += 1 markup = [(6, urwid.Text([('urlref:number:braces', '['), ('urlref:number', repr(i)), ('urlref:number:braces', ']'), ' '])), urwid.AttrMap(urwid.Button(shorten_url(url, cols, shorten), self.mkbrowseto(url), user_data=url), 'urlref:url', 'url:sel')] items.append(urwid.Columns(markup)) return items, urls
[ "def", "process_urls", "(", "self", ",", "extractedurls", ",", "dedupe", ",", "shorten", ")", ":", "cols", ",", "_", "=", "urwid", ".", "raw_display", ".", "Screen", "(", ")", ".", "get_cols_rows", "(", ")", "items", "=", "[", "]", "urls", "=", "[", "]", "first", "=", "True", "for", "group", ",", "usedfirst", ",", "usedlast", "in", "extractedurls", ":", "if", "first", ":", "first", "=", "False", "items", ".", "append", "(", "urwid", ".", "Divider", "(", "div_char", "=", "'-'", ",", "top", "=", "1", ",", "bottom", "=", "1", ")", ")", "if", "dedupe", "is", "True", ":", "# If no unique URLs exist, then skip the group completely", "if", "not", "[", "chunk", "for", "chunks", "in", "group", "for", "chunk", "in", "chunks", "if", "chunk", ".", "url", "is", "not", "None", "and", "chunk", ".", "url", "not", "in", "urls", "]", ":", "continue", "groupurls", "=", "[", "]", "markup", "=", "[", "]", "if", "not", "usedfirst", ":", "markup", ".", "append", "(", "(", "'msgtext:ellipses'", ",", "'...\\n'", ")", ")", "for", "chunks", "in", "group", ":", "i", "=", "0", "while", "i", "<", "len", "(", "chunks", ")", ":", "chunk", "=", "chunks", "[", "i", "]", "i", "+=", "1", "if", "chunk", ".", "url", "is", "None", ":", "markup", ".", "append", "(", "(", "'msgtext'", ",", "chunk", ".", "markup", ")", ")", "else", ":", "if", "(", "dedupe", "is", "True", "and", "chunk", ".", "url", "not", "in", "urls", ")", "or", "dedupe", "is", "False", ":", "urls", ".", "append", "(", "chunk", ".", "url", ")", "groupurls", ".", "append", "(", "chunk", ".", "url", ")", "# Collect all immediately adjacent", "# chunks with the same URL.", "tmpmarkup", "=", "[", "]", "if", "chunk", ".", "markup", ":", "tmpmarkup", ".", "append", "(", "(", "'msgtext'", ",", "chunk", ".", "markup", ")", ")", "while", "i", "<", "len", "(", "chunks", ")", "and", "chunks", "[", "i", "]", ".", "url", "==", "chunk", ".", "url", ":", "if", "chunks", "[", "i", "]", ".", "markup", ":", "tmpmarkup", ".", "append", "(", "chunks", "[", "i", "]", ".", "markup", ")", "i", "+=", "1", "url_idx", "=", "urls", ".", "index", "(", "chunk", ".", "url", ")", "+", "1", "if", "dedupe", "is", "True", "else", "len", "(", "urls", ")", "markup", "+=", "[", "tmpmarkup", "or", "'<URL>'", ",", "(", "'urlref:number:braces'", ",", "' ['", ")", ",", "(", "'urlref:number'", ",", "repr", "(", "url_idx", ")", ")", ",", "(", "'urlref:number:braces'", ",", "']'", ")", "]", "markup", "+=", "'\\n'", "if", "not", "usedlast", ":", "markup", "+=", "[", "(", "'msgtext:ellipses'", ",", "'...\\n\\n'", ")", "]", "items", ".", "append", "(", "urwid", ".", "Text", "(", "markup", ")", ")", "i", "=", "len", "(", "urls", ")", "-", "len", "(", "groupurls", ")", "for", "url", "in", "groupurls", ":", "i", "+=", "1", "markup", "=", "[", "(", "6", ",", "urwid", ".", "Text", "(", "[", "(", "'urlref:number:braces'", ",", "'['", ")", ",", "(", "'urlref:number'", ",", "repr", "(", "i", ")", ")", ",", "(", "'urlref:number:braces'", ",", "']'", ")", ",", "' '", "]", ")", ")", ",", "urwid", ".", "AttrMap", "(", "urwid", ".", "Button", "(", "shorten_url", "(", "url", ",", "cols", ",", "shorten", ")", ",", "self", ".", "mkbrowseto", "(", "url", ")", ",", "user_data", "=", "url", ")", ",", "'urlref:url'", ",", "'url:sel'", ")", "]", "items", ".", "append", "(", "urwid", ".", "Columns", "(", "markup", ")", ")", "return", "items", ",", "urls" ]
Process the 'extractedurls' and ready them for either the curses browser or non-interactive output Args: extractedurls dedupe - Remove duplicate URLs from list Returns: items - List of widgets for the ListBox urls - List of all URLs
[ "Process", "the", "extractedurls", "and", "ready", "them", "for", "either", "the", "curses", "browser", "or", "non", "-", "interactive", "output" ]
2d10807d01167873733da3b478c784f8fa21bbc0
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L636-L711
2,716
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._get_key_file_path
def _get_key_file_path(): """Return the key file path.""" if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME), os.W_OK): return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME) return os.path.join(os.getcwd(), KEY_FILE_NAME)
python
def _get_key_file_path(): if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME), os.W_OK): return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME) return os.path.join(os.getcwd(), KEY_FILE_NAME)
[ "def", "_get_key_file_path", "(", ")", ":", "if", "os", ".", "getenv", "(", "USER_HOME", ")", "is", "not", "None", "and", "os", ".", "access", "(", "os", ".", "getenv", "(", "USER_HOME", ")", ",", "os", ".", "W_OK", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "getenv", "(", "USER_HOME", ")", ",", "KEY_FILE_NAME", ")", "return", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "KEY_FILE_NAME", ")" ]
Return the key file path.
[ "Return", "the", "key", "file", "path", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L39-L45
2,717
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.load_key_file
def load_key_file(self): """Try to load the client key for the current ip.""" self.client_key = None if self.key_file_path: key_file_path = self.key_file_path else: key_file_path = self._get_key_file_path() key_dict = {} logger.debug('load keyfile from %s', key_file_path); if os.path.isfile(key_file_path): with open(key_file_path, 'r') as f: raw_data = f.read() if raw_data: key_dict = json.loads(raw_data) logger.debug('getting client_key for %s from %s', self.ip, key_file_path); if self.ip in key_dict: self.client_key = key_dict[self.ip]
python
def load_key_file(self): self.client_key = None if self.key_file_path: key_file_path = self.key_file_path else: key_file_path = self._get_key_file_path() key_dict = {} logger.debug('load keyfile from %s', key_file_path); if os.path.isfile(key_file_path): with open(key_file_path, 'r') as f: raw_data = f.read() if raw_data: key_dict = json.loads(raw_data) logger.debug('getting client_key for %s from %s', self.ip, key_file_path); if self.ip in key_dict: self.client_key = key_dict[self.ip]
[ "def", "load_key_file", "(", "self", ")", ":", "self", ".", "client_key", "=", "None", "if", "self", ".", "key_file_path", ":", "key_file_path", "=", "self", ".", "key_file_path", "else", ":", "key_file_path", "=", "self", ".", "_get_key_file_path", "(", ")", "key_dict", "=", "{", "}", "logger", ".", "debug", "(", "'load keyfile from %s'", ",", "key_file_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "key_file_path", ")", ":", "with", "open", "(", "key_file_path", ",", "'r'", ")", "as", "f", ":", "raw_data", "=", "f", ".", "read", "(", ")", "if", "raw_data", ":", "key_dict", "=", "json", ".", "loads", "(", "raw_data", ")", "logger", ".", "debug", "(", "'getting client_key for %s from %s'", ",", "self", ".", "ip", ",", "key_file_path", ")", "if", "self", ".", "ip", "in", "key_dict", ":", "self", ".", "client_key", "=", "key_dict", "[", "self", ".", "ip", "]" ]
Try to load the client key for the current ip.
[ "Try", "to", "load", "the", "client", "key", "for", "the", "current", "ip", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L47-L66
2,718
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.save_key_file
def save_key_file(self): """Save the current client key.""" if self.client_key is None: return if self.key_file_path: key_file_path = self.key_file_path else: key_file_path = self._get_key_file_path() logger.debug('save keyfile to %s', key_file_path); with open(key_file_path, 'w+') as f: raw_data = f.read() key_dict = {} if raw_data: key_dict = json.loads(raw_data) key_dict[self.ip] = self.client_key f.write(json.dumps(key_dict))
python
def save_key_file(self): if self.client_key is None: return if self.key_file_path: key_file_path = self.key_file_path else: key_file_path = self._get_key_file_path() logger.debug('save keyfile to %s', key_file_path); with open(key_file_path, 'w+') as f: raw_data = f.read() key_dict = {} if raw_data: key_dict = json.loads(raw_data) key_dict[self.ip] = self.client_key f.write(json.dumps(key_dict))
[ "def", "save_key_file", "(", "self", ")", ":", "if", "self", ".", "client_key", "is", "None", ":", "return", "if", "self", ".", "key_file_path", ":", "key_file_path", "=", "self", ".", "key_file_path", "else", ":", "key_file_path", "=", "self", ".", "_get_key_file_path", "(", ")", "logger", ".", "debug", "(", "'save keyfile to %s'", ",", "key_file_path", ")", "with", "open", "(", "key_file_path", ",", "'w+'", ")", "as", "f", ":", "raw_data", "=", "f", ".", "read", "(", ")", "key_dict", "=", "{", "}", "if", "raw_data", ":", "key_dict", "=", "json", ".", "loads", "(", "raw_data", ")", "key_dict", "[", "self", ".", "ip", "]", "=", "self", ".", "client_key", "f", ".", "write", "(", "json", ".", "dumps", "(", "key_dict", ")", ")" ]
Save the current client key.
[ "Save", "the", "current", "client", "key", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L68-L89
2,719
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._send_register_payload
def _send_register_payload(self, websocket): """Send the register payload.""" file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME) data = codecs.open(file, 'r', 'utf-8') raw_handshake = data.read() handshake = json.loads(raw_handshake) handshake['payload']['client-key'] = self.client_key yield from websocket.send(json.dumps(handshake)) raw_response = yield from websocket.recv() response = json.loads(raw_response) if response['type'] == 'response' and \ response['payload']['pairingType'] == 'PROMPT': raw_response = yield from websocket.recv() response = json.loads(raw_response) if response['type'] == 'registered': self.client_key = response['payload']['client-key'] self.save_key_file()
python
def _send_register_payload(self, websocket): file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME) data = codecs.open(file, 'r', 'utf-8') raw_handshake = data.read() handshake = json.loads(raw_handshake) handshake['payload']['client-key'] = self.client_key yield from websocket.send(json.dumps(handshake)) raw_response = yield from websocket.recv() response = json.loads(raw_response) if response['type'] == 'response' and \ response['payload']['pairingType'] == 'PROMPT': raw_response = yield from websocket.recv() response = json.loads(raw_response) if response['type'] == 'registered': self.client_key = response['payload']['client-key'] self.save_key_file()
[ "def", "_send_register_payload", "(", "self", ",", "websocket", ")", ":", "file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "HANDSHAKE_FILE_NAME", ")", "data", "=", "codecs", ".", "open", "(", "file", ",", "'r'", ",", "'utf-8'", ")", "raw_handshake", "=", "data", ".", "read", "(", ")", "handshake", "=", "json", ".", "loads", "(", "raw_handshake", ")", "handshake", "[", "'payload'", "]", "[", "'client-key'", "]", "=", "self", ".", "client_key", "yield", "from", "websocket", ".", "send", "(", "json", ".", "dumps", "(", "handshake", ")", ")", "raw_response", "=", "yield", "from", "websocket", ".", "recv", "(", ")", "response", "=", "json", ".", "loads", "(", "raw_response", ")", "if", "response", "[", "'type'", "]", "==", "'response'", "and", "response", "[", "'payload'", "]", "[", "'pairingType'", "]", "==", "'PROMPT'", ":", "raw_response", "=", "yield", "from", "websocket", ".", "recv", "(", ")", "response", "=", "json", ".", "loads", "(", "raw_response", ")", "if", "response", "[", "'type'", "]", "==", "'registered'", ":", "self", ".", "client_key", "=", "response", "[", "'payload'", "]", "[", "'client-key'", "]", "self", ".", "save_key_file", "(", ")" ]
Send the register payload.
[ "Send", "the", "register", "payload", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L92-L112
2,720
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._register
def _register(self): """Register wrapper.""" logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) finally: logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
python
def _register(self): logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) finally: logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
[ "def", "_register", "(", "self", ")", ":", "logger", ".", "debug", "(", "'register on %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "try", ":", "websocket", "=", "yield", "from", "websockets", ".", "connect", "(", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ",", "timeout", "=", "self", ".", "timeout_connect", ")", "except", ":", "logger", ".", "error", "(", "'register failed to connect to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "return", "False", "logger", ".", "debug", "(", "'register websocket connected to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "try", ":", "yield", "from", "self", ".", "_send_register_payload", "(", "websocket", ")", "finally", ":", "logger", ".", "debug", "(", "'close register connection to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "yield", "from", "websocket", ".", "close", "(", ")" ]
Register wrapper.
[ "Register", "wrapper", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L119-L137
2,721
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.register
def register(self): """Pair client with tv.""" loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self._register())
python
def register(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self._register())
[ "def", "register", "(", "self", ")", ":", "loop", "=", "asyncio", ".", "new_event_loop", "(", ")", "asyncio", ".", "set_event_loop", "(", "loop", ")", "loop", ".", "run_until_complete", "(", "self", ".", "_register", "(", ")", ")" ]
Pair client with tv.
[ "Pair", "client", "with", "tv", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L139-L143
2,722
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._command
def _command(self, msg): """Send a command to the tv.""" logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) if not self.client_key: raise PyLGTVPairException("Unable to pair") yield from websocket.send(json.dumps(msg)) if msg['type'] == 'request': raw_response = yield from websocket.recv() self.last_response = json.loads(raw_response) finally: logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
python
def _command(self, msg): logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) if not self.client_key: raise PyLGTVPairException("Unable to pair") yield from websocket.send(json.dumps(msg)) if msg['type'] == 'request': raw_response = yield from websocket.recv() self.last_response = json.loads(raw_response) finally: logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
[ "def", "_command", "(", "self", ",", "msg", ")", ":", "logger", ".", "debug", "(", "'send command to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "try", ":", "websocket", "=", "yield", "from", "websockets", ".", "connect", "(", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ",", "timeout", "=", "self", ".", "timeout_connect", ")", "except", ":", "logger", ".", "debug", "(", "'command failed to connect to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "return", "False", "logger", ".", "debug", "(", "'command websocket connected to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "try", ":", "yield", "from", "self", ".", "_send_register_payload", "(", "websocket", ")", "if", "not", "self", ".", "client_key", ":", "raise", "PyLGTVPairException", "(", "\"Unable to pair\"", ")", "yield", "from", "websocket", ".", "send", "(", "json", ".", "dumps", "(", "msg", ")", ")", "if", "msg", "[", "'type'", "]", "==", "'request'", ":", "raw_response", "=", "yield", "from", "websocket", ".", "recv", "(", ")", "self", ".", "last_response", "=", "json", ".", "loads", "(", "raw_response", ")", "finally", ":", "logger", ".", "debug", "(", "'close command connection to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "yield", "from", "websocket", ".", "close", "(", ")" ]
Send a command to the tv.
[ "Send", "a", "command", "to", "the", "tv", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L146-L172
2,723
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.command
def command(self, request_type, uri, payload): """Build and send a command.""" self.command_count += 1 if payload is None: payload = {} message = { 'id': "{}_{}".format(type, self.command_count), 'type': request_type, 'uri': "ssap://{}".format(uri), 'payload': payload, } self.last_response = None try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(asyncio.wait_for(self._command(message), self.timeout_connect, loop=loop)) finally: loop.close()
python
def command(self, request_type, uri, payload): self.command_count += 1 if payload is None: payload = {} message = { 'id': "{}_{}".format(type, self.command_count), 'type': request_type, 'uri': "ssap://{}".format(uri), 'payload': payload, } self.last_response = None try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(asyncio.wait_for(self._command(message), self.timeout_connect, loop=loop)) finally: loop.close()
[ "def", "command", "(", "self", ",", "request_type", ",", "uri", ",", "payload", ")", ":", "self", ".", "command_count", "+=", "1", "if", "payload", "is", "None", ":", "payload", "=", "{", "}", "message", "=", "{", "'id'", ":", "\"{}_{}\"", ".", "format", "(", "type", ",", "self", ".", "command_count", ")", ",", "'type'", ":", "request_type", ",", "'uri'", ":", "\"ssap://{}\"", ".", "format", "(", "uri", ")", ",", "'payload'", ":", "payload", ",", "}", "self", ".", "last_response", "=", "None", "try", ":", "loop", "=", "asyncio", ".", "new_event_loop", "(", ")", "asyncio", ".", "set_event_loop", "(", "loop", ")", "loop", ".", "run_until_complete", "(", "asyncio", ".", "wait_for", "(", "self", ".", "_command", "(", "message", ")", ",", "self", ".", "timeout_connect", ",", "loop", "=", "loop", ")", ")", "finally", ":", "loop", ".", "close", "(", ")" ]
Build and send a command.
[ "Build", "and", "send", "a", "command", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L174-L195
2,724
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.send_message
def send_message(self, message, icon_path=None): """Show a floating message.""" icon_encoded_string = '' icon_extension = '' if icon_path is not None: icon_extension = os.path.splitext(icon_path)[1][1:] with open(icon_path, 'rb') as icon_file: icon_encoded_string = base64.b64encode(icon_file.read()).decode('ascii') self.request(EP_SHOW_MESSAGE, { 'message': message, 'iconData': icon_encoded_string, 'iconExtension': icon_extension })
python
def send_message(self, message, icon_path=None): icon_encoded_string = '' icon_extension = '' if icon_path is not None: icon_extension = os.path.splitext(icon_path)[1][1:] with open(icon_path, 'rb') as icon_file: icon_encoded_string = base64.b64encode(icon_file.read()).decode('ascii') self.request(EP_SHOW_MESSAGE, { 'message': message, 'iconData': icon_encoded_string, 'iconExtension': icon_extension })
[ "def", "send_message", "(", "self", ",", "message", ",", "icon_path", "=", "None", ")", ":", "icon_encoded_string", "=", "''", "icon_extension", "=", "''", "if", "icon_path", "is", "not", "None", ":", "icon_extension", "=", "os", ".", "path", ".", "splitext", "(", "icon_path", ")", "[", "1", "]", "[", "1", ":", "]", "with", "open", "(", "icon_path", ",", "'rb'", ")", "as", "icon_file", ":", "icon_encoded_string", "=", "base64", ".", "b64encode", "(", "icon_file", ".", "read", "(", ")", ")", ".", "decode", "(", "'ascii'", ")", "self", ".", "request", "(", "EP_SHOW_MESSAGE", ",", "{", "'message'", ":", "message", ",", "'iconData'", ":", "icon_encoded_string", ",", "'iconExtension'", ":", "icon_extension", "}", ")" ]
Show a floating message.
[ "Show", "a", "floating", "message", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L201-L215
2,725
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_apps
def get_apps(self): """Return all apps.""" self.request(EP_GET_APPS) return {} if self.last_response is None else self.last_response.get('payload').get('launchPoints')
python
def get_apps(self): self.request(EP_GET_APPS) return {} if self.last_response is None else self.last_response.get('payload').get('launchPoints')
[ "def", "get_apps", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_APPS", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", "(", "'launchPoints'", ")" ]
Return all apps.
[ "Return", "all", "apps", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L218-L221
2,726
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_current_app
def get_current_app(self): """Get the current app id.""" self.request(EP_GET_CURRENT_APP_INFO) return None if self.last_response is None else self.last_response.get('payload').get('appId')
python
def get_current_app(self): self.request(EP_GET_CURRENT_APP_INFO) return None if self.last_response is None else self.last_response.get('payload').get('appId')
[ "def", "get_current_app", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_CURRENT_APP_INFO", ")", "return", "None", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", "(", "'appId'", ")" ]
Get the current app id.
[ "Get", "the", "current", "app", "id", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L223-L226
2,727
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_services
def get_services(self): """Get all services.""" self.request(EP_GET_SERVICES) return {} if self.last_response is None else self.last_response.get('payload').get('services')
python
def get_services(self): self.request(EP_GET_SERVICES) return {} if self.last_response is None else self.last_response.get('payload').get('services')
[ "def", "get_services", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_SERVICES", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", "(", "'services'", ")" ]
Get all services.
[ "Get", "all", "services", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L255-L258
2,728
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_software_info
def get_software_info(self): """Return the current software status.""" self.request(EP_GET_SOFTWARE_INFO) return {} if self.last_response is None else self.last_response.get('payload')
python
def get_software_info(self): self.request(EP_GET_SOFTWARE_INFO) return {} if self.last_response is None else self.last_response.get('payload')
[ "def", "get_software_info", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_SOFTWARE_INFO", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")" ]
Return the current software status.
[ "Return", "the", "current", "software", "status", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L260-L263
2,729
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_inputs
def get_inputs(self): """Get all inputs.""" self.request(EP_GET_INPUTS) return {} if self.last_response is None else self.last_response.get('payload').get('devices')
python
def get_inputs(self): self.request(EP_GET_INPUTS) return {} if self.last_response is None else self.last_response.get('payload').get('devices')
[ "def", "get_inputs", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_INPUTS", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", "(", "'devices'", ")" ]
Get all inputs.
[ "Get", "all", "inputs", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L283-L286
2,730
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_audio_status
def get_audio_status(self): """Get the current audio status""" self.request(EP_GET_AUDIO_STATUS) return {} if self.last_response is None else self.last_response.get('payload')
python
def get_audio_status(self): self.request(EP_GET_AUDIO_STATUS) return {} if self.last_response is None else self.last_response.get('payload')
[ "def", "get_audio_status", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_AUDIO_STATUS", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")" ]
Get the current audio status
[ "Get", "the", "current", "audio", "status" ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L299-L302
2,731
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_volume
def get_volume(self): """Get the current volume.""" self.request(EP_GET_VOLUME) return 0 if self.last_response is None else self.last_response.get('payload').get('volume')
python
def get_volume(self): self.request(EP_GET_VOLUME) return 0 if self.last_response is None else self.last_response.get('payload').get('volume')
[ "def", "get_volume", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_VOLUME", ")", "return", "0", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", "(", "'volume'", ")" ]
Get the current volume.
[ "Get", "the", "current", "volume", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L314-L317
2,732
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_channels
def get_channels(self): """Get all tv channels.""" self.request(EP_GET_TV_CHANNELS) return {} if self.last_response is None else self.last_response.get('payload').get('channelList')
python
def get_channels(self): self.request(EP_GET_TV_CHANNELS) return {} if self.last_response is None else self.last_response.get('payload').get('channelList')
[ "def", "get_channels", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_TV_CHANNELS", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", "(", "'channelList'", ")" ]
Get all tv channels.
[ "Get", "all", "tv", "channels", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L343-L346
2,733
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_current_channel
def get_current_channel(self): """Get the current tv channel.""" self.request(EP_GET_CURRENT_CHANNEL) return {} if self.last_response is None else self.last_response.get('payload')
python
def get_current_channel(self): self.request(EP_GET_CURRENT_CHANNEL) return {} if self.last_response is None else self.last_response.get('payload')
[ "def", "get_current_channel", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_CURRENT_CHANNEL", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")" ]
Get the current tv channel.
[ "Get", "the", "current", "tv", "channel", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L348-L351
2,734
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_channel_info
def get_channel_info(self): """Get the current channel info.""" self.request(EP_GET_CHANNEL_INFO) return {} if self.last_response is None else self.last_response.get('payload')
python
def get_channel_info(self): self.request(EP_GET_CHANNEL_INFO) return {} if self.last_response is None else self.last_response.get('payload')
[ "def", "get_channel_info", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_CHANNEL_INFO", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")" ]
Get the current channel info.
[ "Get", "the", "current", "channel", "info", "." ]
a7d9ad87ce47e77180fe9262da785465219f4ed6
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L353-L356
2,735
ssato/python-anyconfig
src/anyconfig/backend/xml.py
elem_to_container
def elem_to_container(elem, container=dict, **options): """ Convert XML ElementTree Element to a collection of container objects. Elements are transformed to a node under special tagged nodes, attrs, text and children, to store the type of these elements basically, however, in some special cases like the followings, these nodes are attached to the parent node directly for later convenience. - There is only text element - There are only children elements each has unique keys among all :param elem: ET Element object or None :param container: callble to make a container object :param options: Keyword options - nspaces: A namespaces dict, {uri: prefix} or None - attrs, text, children: Tags for special nodes to keep XML info - merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation. """ dic = container() if elem is None: return dic elem.tag = _tweak_ns(elem.tag, **options) # {ns}tag -> ns_prefix:tag subdic = dic[elem.tag] = container() options["container"] = container if elem.text: _process_elem_text(elem, dic, subdic, **options) if elem.attrib: _process_elem_attrs(elem, dic, subdic, **options) if len(elem): _process_children_elems(elem, dic, subdic, **options) elif not elem.text and not elem.attrib: # ex. <tag/>. dic[elem.tag] = None return dic
python
def elem_to_container(elem, container=dict, **options): dic = container() if elem is None: return dic elem.tag = _tweak_ns(elem.tag, **options) # {ns}tag -> ns_prefix:tag subdic = dic[elem.tag] = container() options["container"] = container if elem.text: _process_elem_text(elem, dic, subdic, **options) if elem.attrib: _process_elem_attrs(elem, dic, subdic, **options) if len(elem): _process_children_elems(elem, dic, subdic, **options) elif not elem.text and not elem.attrib: # ex. <tag/>. dic[elem.tag] = None return dic
[ "def", "elem_to_container", "(", "elem", ",", "container", "=", "dict", ",", "*", "*", "options", ")", ":", "dic", "=", "container", "(", ")", "if", "elem", "is", "None", ":", "return", "dic", "elem", ".", "tag", "=", "_tweak_ns", "(", "elem", ".", "tag", ",", "*", "*", "options", ")", "# {ns}tag -> ns_prefix:tag", "subdic", "=", "dic", "[", "elem", ".", "tag", "]", "=", "container", "(", ")", "options", "[", "\"container\"", "]", "=", "container", "if", "elem", ".", "text", ":", "_process_elem_text", "(", "elem", ",", "dic", ",", "subdic", ",", "*", "*", "options", ")", "if", "elem", ".", "attrib", ":", "_process_elem_attrs", "(", "elem", ",", "dic", ",", "subdic", ",", "*", "*", "options", ")", "if", "len", "(", "elem", ")", ":", "_process_children_elems", "(", "elem", ",", "dic", ",", "subdic", ",", "*", "*", "options", ")", "elif", "not", "elem", ".", "text", "and", "not", "elem", ".", "attrib", ":", "# ex. <tag/>.", "dic", "[", "elem", ".", "tag", "]", "=", "None", "return", "dic" ]
Convert XML ElementTree Element to a collection of container objects. Elements are transformed to a node under special tagged nodes, attrs, text and children, to store the type of these elements basically, however, in some special cases like the followings, these nodes are attached to the parent node directly for later convenience. - There is only text element - There are only children elements each has unique keys among all :param elem: ET Element object or None :param container: callble to make a container object :param options: Keyword options - nspaces: A namespaces dict, {uri: prefix} or None - attrs, text, children: Tags for special nodes to keep XML info - merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation.
[ "Convert", "XML", "ElementTree", "Element", "to", "a", "collection", "of", "container", "objects", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L267-L307
2,736
ssato/python-anyconfig
src/anyconfig/backend/xml.py
root_to_container
def root_to_container(root, container=dict, nspaces=None, **options): """ Convert XML ElementTree Root Element to a collection of container objects. :param root: etree root object or None :param container: callble to make a container object :param nspaces: A namespaces dict, {uri: prefix} or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ tree = container() if root is None: return tree if nspaces is not None: for uri, prefix in nspaces.items(): root.attrib["xmlns:" + prefix if prefix else "xmlns"] = uri return elem_to_container(root, container=container, nspaces=nspaces, **_complement_tag_options(options))
python
def root_to_container(root, container=dict, nspaces=None, **options): tree = container() if root is None: return tree if nspaces is not None: for uri, prefix in nspaces.items(): root.attrib["xmlns:" + prefix if prefix else "xmlns"] = uri return elem_to_container(root, container=container, nspaces=nspaces, **_complement_tag_options(options))
[ "def", "root_to_container", "(", "root", ",", "container", "=", "dict", ",", "nspaces", "=", "None", ",", "*", "*", "options", ")", ":", "tree", "=", "container", "(", ")", "if", "root", "is", "None", ":", "return", "tree", "if", "nspaces", "is", "not", "None", ":", "for", "uri", ",", "prefix", "in", "nspaces", ".", "items", "(", ")", ":", "root", ".", "attrib", "[", "\"xmlns:\"", "+", "prefix", "if", "prefix", "else", "\"xmlns\"", "]", "=", "uri", "return", "elem_to_container", "(", "root", ",", "container", "=", "container", ",", "nspaces", "=", "nspaces", ",", "*", "*", "_complement_tag_options", "(", "options", ")", ")" ]
Convert XML ElementTree Root Element to a collection of container objects. :param root: etree root object or None :param container: callble to make a container object :param nspaces: A namespaces dict, {uri: prefix} or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"}
[ "Convert", "XML", "ElementTree", "Root", "Element", "to", "a", "collection", "of", "container", "objects", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L329-L350
2,737
ssato/python-anyconfig
src/anyconfig/backend/xml.py
container_to_etree
def container_to_etree(obj, parent=None, to_str=None, **options): """ Convert a dict-like object to XML ElementTree. :param obj: Container instance to convert to :param parent: XML ElementTree parent node object or None :param to_str: Callable to convert value to string or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ if to_str is None: to_str = _to_str_fn(**options) if not anyconfig.utils.is_dict_like(obj): if parent is not None and obj: parent.text = to_str(obj) # Parent is a leaf text node. return parent # All attributes and text should be set already. options = _complement_tag_options(options) (attrs, text, children) = operator.itemgetter(*_ATC)(options) for key, val in anyconfig.compat.iteritems(obj): if key == attrs: _elem_set_attrs(val, parent, to_str) elif key == text: parent.text = to_str(val) elif key == children: for celem in _elem_from_descendants(val, **options): parent.append(celem) else: parent = _get_or_update_parent(key, val, to_str, parent=parent, **options) return ET.ElementTree(parent)
python
def container_to_etree(obj, parent=None, to_str=None, **options): if to_str is None: to_str = _to_str_fn(**options) if not anyconfig.utils.is_dict_like(obj): if parent is not None and obj: parent.text = to_str(obj) # Parent is a leaf text node. return parent # All attributes and text should be set already. options = _complement_tag_options(options) (attrs, text, children) = operator.itemgetter(*_ATC)(options) for key, val in anyconfig.compat.iteritems(obj): if key == attrs: _elem_set_attrs(val, parent, to_str) elif key == text: parent.text = to_str(val) elif key == children: for celem in _elem_from_descendants(val, **options): parent.append(celem) else: parent = _get_or_update_parent(key, val, to_str, parent=parent, **options) return ET.ElementTree(parent)
[ "def", "container_to_etree", "(", "obj", ",", "parent", "=", "None", ",", "to_str", "=", "None", ",", "*", "*", "options", ")", ":", "if", "to_str", "is", "None", ":", "to_str", "=", "_to_str_fn", "(", "*", "*", "options", ")", "if", "not", "anyconfig", ".", "utils", ".", "is_dict_like", "(", "obj", ")", ":", "if", "parent", "is", "not", "None", "and", "obj", ":", "parent", ".", "text", "=", "to_str", "(", "obj", ")", "# Parent is a leaf text node.", "return", "parent", "# All attributes and text should be set already.", "options", "=", "_complement_tag_options", "(", "options", ")", "(", "attrs", ",", "text", ",", "children", ")", "=", "operator", ".", "itemgetter", "(", "*", "_ATC", ")", "(", "options", ")", "for", "key", ",", "val", "in", "anyconfig", ".", "compat", ".", "iteritems", "(", "obj", ")", ":", "if", "key", "==", "attrs", ":", "_elem_set_attrs", "(", "val", ",", "parent", ",", "to_str", ")", "elif", "key", "==", "text", ":", "parent", ".", "text", "=", "to_str", "(", "val", ")", "elif", "key", "==", "children", ":", "for", "celem", "in", "_elem_from_descendants", "(", "val", ",", "*", "*", "options", ")", ":", "parent", ".", "append", "(", "celem", ")", "else", ":", "parent", "=", "_get_or_update_parent", "(", "key", ",", "val", ",", "to_str", ",", "parent", "=", "parent", ",", "*", "*", "options", ")", "return", "ET", ".", "ElementTree", "(", "parent", ")" ]
Convert a dict-like object to XML ElementTree. :param obj: Container instance to convert to :param parent: XML ElementTree parent node object or None :param to_str: Callable to convert value to string or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"}
[ "Convert", "a", "dict", "-", "like", "object", "to", "XML", "ElementTree", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L410-L445
2,738
ssato/python-anyconfig
src/anyconfig/backend/xml.py
etree_write
def etree_write(tree, stream): """ Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to """ try: tree.write(stream, encoding="utf-8", xml_declaration=True) except TypeError: tree.write(stream, encoding="unicode", xml_declaration=True)
python
def etree_write(tree, stream): try: tree.write(stream, encoding="utf-8", xml_declaration=True) except TypeError: tree.write(stream, encoding="unicode", xml_declaration=True)
[ "def", "etree_write", "(", "tree", ",", "stream", ")", ":", "try", ":", "tree", ".", "write", "(", "stream", ",", "encoding", "=", "\"utf-8\"", ",", "xml_declaration", "=", "True", ")", "except", "TypeError", ":", "tree", ".", "write", "(", "stream", ",", "encoding", "=", "\"unicode\"", ",", "xml_declaration", "=", "True", ")" ]
Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to
[ "Write", "XML", "ElementTree", "root", "content", "into", "stream", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L448-L458
2,739
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
_customized_loader
def _customized_loader(container, loader=Loader, mapping_tag=_MAPPING_TAG): """ Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally """ def construct_mapping(loader, node, deep=False): """Construct python object from yaml mapping node, based on :meth:`yaml.BaseConstructor.construct_mapping` in PyYAML (MIT). """ loader.flatten_mapping(node) if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructorError(None, None, msg, node.start_mark) mapping = container() for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: eargs = ("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) raise yaml.constructor.ConstructorError(*eargs) value = loader.construct_object(value_node, deep=deep) mapping[key] = value return mapping tag = "tag:yaml.org,2002:python/unicode" def construct_ustr(loader, node): """Unicode string constructor""" return loader.construct_scalar(node) try: loader.add_constructor(tag, construct_ustr) except NameError: pass if type(container) != dict: loader.add_constructor(mapping_tag, construct_mapping) return loader
python
def _customized_loader(container, loader=Loader, mapping_tag=_MAPPING_TAG): def construct_mapping(loader, node, deep=False): """Construct python object from yaml mapping node, based on :meth:`yaml.BaseConstructor.construct_mapping` in PyYAML (MIT). """ loader.flatten_mapping(node) if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructorError(None, None, msg, node.start_mark) mapping = container() for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: eargs = ("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) raise yaml.constructor.ConstructorError(*eargs) value = loader.construct_object(value_node, deep=deep) mapping[key] = value return mapping tag = "tag:yaml.org,2002:python/unicode" def construct_ustr(loader, node): """Unicode string constructor""" return loader.construct_scalar(node) try: loader.add_constructor(tag, construct_ustr) except NameError: pass if type(container) != dict: loader.add_constructor(mapping_tag, construct_mapping) return loader
[ "def", "_customized_loader", "(", "container", ",", "loader", "=", "Loader", ",", "mapping_tag", "=", "_MAPPING_TAG", ")", ":", "def", "construct_mapping", "(", "loader", ",", "node", ",", "deep", "=", "False", ")", ":", "\"\"\"Construct python object from yaml mapping node, based on\n :meth:`yaml.BaseConstructor.construct_mapping` in PyYAML (MIT).\n \"\"\"", "loader", ".", "flatten_mapping", "(", "node", ")", "if", "not", "isinstance", "(", "node", ",", "yaml", ".", "MappingNode", ")", ":", "msg", "=", "\"expected a mapping node, but found %s\"", "%", "node", ".", "id", "raise", "yaml", ".", "constructor", ".", "ConstructorError", "(", "None", ",", "None", ",", "msg", ",", "node", ".", "start_mark", ")", "mapping", "=", "container", "(", ")", "for", "key_node", ",", "value_node", "in", "node", ".", "value", ":", "key", "=", "loader", ".", "construct_object", "(", "key_node", ",", "deep", "=", "deep", ")", "try", ":", "hash", "(", "key", ")", "except", "TypeError", "as", "exc", ":", "eargs", "=", "(", "\"while constructing a mapping\"", ",", "node", ".", "start_mark", ",", "\"found unacceptable key (%s)\"", "%", "exc", ",", "key_node", ".", "start_mark", ")", "raise", "yaml", ".", "constructor", ".", "ConstructorError", "(", "*", "eargs", ")", "value", "=", "loader", ".", "construct_object", "(", "value_node", ",", "deep", "=", "deep", ")", "mapping", "[", "key", "]", "=", "value", "return", "mapping", "tag", "=", "\"tag:yaml.org,2002:python/unicode\"", "def", "construct_ustr", "(", "loader", ",", "node", ")", ":", "\"\"\"Unicode string constructor\"\"\"", "return", "loader", ".", "construct_scalar", "(", "node", ")", "try", ":", "loader", ".", "add_constructor", "(", "tag", ",", "construct_ustr", ")", "except", "NameError", ":", "pass", "if", "type", "(", "container", ")", "!=", "dict", ":", "loader", ".", "add_constructor", "(", "mapping_tag", ",", "construct_mapping", ")", "return", "loader" ]
Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally
[ "Create", "or", "update", "loader", "with", "making", "given", "callble", "container", "to", "make", "mapping", "objects", "such", "as", "dict", "and", "OrderedDict", "used", "to", "construct", "python", "object", "from", "yaml", "mapping", "node", "internally", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L58-L104
2,740
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
yml_fnc
def yml_fnc(fname, *args, **options): """An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely """ key = "ac_safe" fnc = getattr(yaml, r"safe_" + fname if options.get(key) else fname) return fnc(*args, **common.filter_from_options(key, options))
python
def yml_fnc(fname, *args, **options): key = "ac_safe" fnc = getattr(yaml, r"safe_" + fname if options.get(key) else fname) return fnc(*args, **common.filter_from_options(key, options))
[ "def", "yml_fnc", "(", "fname", ",", "*", "args", ",", "*", "*", "options", ")", ":", "key", "=", "\"ac_safe\"", "fnc", "=", "getattr", "(", "yaml", ",", "r\"safe_\"", "+", "fname", "if", "options", ".", "get", "(", "key", ")", "else", "fname", ")", "return", "fnc", "(", "*", "args", ",", "*", "*", "common", ".", "filter_from_options", "(", "key", ",", "options", ")", ")" ]
An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely
[ "An", "wrapper", "of", "yaml", ".", "safe_load", "yaml", ".", "load", "yaml", ".", "safe_dump", "and", "yaml", ".", "dump", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L131-L142
2,741
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
yml_load
def yml_load(stream, container, yml_fnc=yml_fnc, **options): """An wrapper of yaml.safe_load and yaml.load. :param stream: a file or file-like object to load YAML content :param container: callble to make a container object :return: Mapping object """ if options.get("ac_safe", False): options = {} # yaml.safe_load does not process Loader opts. elif not options.get("Loader"): maybe_container = options.get("ac_dict", False) if maybe_container and callable(maybe_container): container = maybe_container options["Loader"] = _customized_loader(container) ret = yml_fnc("load", stream, **common.filter_from_options("ac_dict", options)) if ret is None: return container() return ret
python
def yml_load(stream, container, yml_fnc=yml_fnc, **options): if options.get("ac_safe", False): options = {} # yaml.safe_load does not process Loader opts. elif not options.get("Loader"): maybe_container = options.get("ac_dict", False) if maybe_container and callable(maybe_container): container = maybe_container options["Loader"] = _customized_loader(container) ret = yml_fnc("load", stream, **common.filter_from_options("ac_dict", options)) if ret is None: return container() return ret
[ "def", "yml_load", "(", "stream", ",", "container", ",", "yml_fnc", "=", "yml_fnc", ",", "*", "*", "options", ")", ":", "if", "options", ".", "get", "(", "\"ac_safe\"", ",", "False", ")", ":", "options", "=", "{", "}", "# yaml.safe_load does not process Loader opts.", "elif", "not", "options", ".", "get", "(", "\"Loader\"", ")", ":", "maybe_container", "=", "options", ".", "get", "(", "\"ac_dict\"", ",", "False", ")", "if", "maybe_container", "and", "callable", "(", "maybe_container", ")", ":", "container", "=", "maybe_container", "options", "[", "\"Loader\"", "]", "=", "_customized_loader", "(", "container", ")", "ret", "=", "yml_fnc", "(", "\"load\"", ",", "stream", ",", "*", "*", "common", ".", "filter_from_options", "(", "\"ac_dict\"", ",", "options", ")", ")", "if", "ret", "is", "None", ":", "return", "container", "(", ")", "return", "ret" ]
An wrapper of yaml.safe_load and yaml.load. :param stream: a file or file-like object to load YAML content :param container: callble to make a container object :return: Mapping object
[ "An", "wrapper", "of", "yaml", ".", "safe_load", "and", "yaml", ".", "load", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L145-L167
2,742
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
yml_dump
def yml_dump(data, stream, yml_fnc=yml_fnc, **options): """An wrapper of yaml.safe_dump and yaml.dump. :param data: Some data to dump :param stream: a file or file-like object to dump YAML data """ _is_dict = anyconfig.utils.is_dict_like(data) if options.get("ac_safe", False): options = {} elif not options.get("Dumper", False) and _is_dict: # TODO: Any other way to get its constructor? maybe_container = options.get("ac_dict", type(data)) options["Dumper"] = _customized_dumper(maybe_container) if _is_dict: # Type information and the order of items are lost on dump currently. data = anyconfig.dicts.convert_to(data, ac_dict=dict) options = common.filter_from_options("ac_dict", options) return yml_fnc("dump", data, stream, **options)
python
def yml_dump(data, stream, yml_fnc=yml_fnc, **options): _is_dict = anyconfig.utils.is_dict_like(data) if options.get("ac_safe", False): options = {} elif not options.get("Dumper", False) and _is_dict: # TODO: Any other way to get its constructor? maybe_container = options.get("ac_dict", type(data)) options["Dumper"] = _customized_dumper(maybe_container) if _is_dict: # Type information and the order of items are lost on dump currently. data = anyconfig.dicts.convert_to(data, ac_dict=dict) options = common.filter_from_options("ac_dict", options) return yml_fnc("dump", data, stream, **options)
[ "def", "yml_dump", "(", "data", ",", "stream", ",", "yml_fnc", "=", "yml_fnc", ",", "*", "*", "options", ")", ":", "_is_dict", "=", "anyconfig", ".", "utils", ".", "is_dict_like", "(", "data", ")", "if", "options", ".", "get", "(", "\"ac_safe\"", ",", "False", ")", ":", "options", "=", "{", "}", "elif", "not", "options", ".", "get", "(", "\"Dumper\"", ",", "False", ")", "and", "_is_dict", ":", "# TODO: Any other way to get its constructor?", "maybe_container", "=", "options", ".", "get", "(", "\"ac_dict\"", ",", "type", "(", "data", ")", ")", "options", "[", "\"Dumper\"", "]", "=", "_customized_dumper", "(", "maybe_container", ")", "if", "_is_dict", ":", "# Type information and the order of items are lost on dump currently.", "data", "=", "anyconfig", ".", "dicts", ".", "convert_to", "(", "data", ",", "ac_dict", "=", "dict", ")", "options", "=", "common", ".", "filter_from_options", "(", "\"ac_dict\"", ",", "options", ")", "return", "yml_fnc", "(", "\"dump\"", ",", "data", ",", "stream", ",", "*", "*", "options", ")" ]
An wrapper of yaml.safe_dump and yaml.dump. :param data: Some data to dump :param stream: a file or file-like object to dump YAML data
[ "An", "wrapper", "of", "yaml", ".", "safe_dump", "and", "yaml", ".", "dump", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L170-L190
2,743
ssato/python-anyconfig
src/anyconfig/dicts.py
_split_path
def _split_path(path, seps=PATH_SEPS): """ Parse path expression and return list of path items. :param path: Path expression may contain separator chars. :param seps: Separator char candidates. :return: A list of keys to fetch object[s] later. >>> assert _split_path('') == [] >>> assert _split_path('/') == [''] # JSON Pointer spec expects this. >>> for p in ('/a', '.a', 'a', 'a.'): ... assert _split_path(p) == ['a'], p >>> assert _split_path('/a/b/c') == _split_path('a.b.c') == ['a', 'b', 'c'] >>> assert _split_path('abc') == ['abc'] """ if not path: return [] for sep in seps: if sep in path: if path == sep: # Special case, '/' or '.' only. return [''] return [x for x in path.split(sep) if x] return [path]
python
def _split_path(path, seps=PATH_SEPS): if not path: return [] for sep in seps: if sep in path: if path == sep: # Special case, '/' or '.' only. return [''] return [x for x in path.split(sep) if x] return [path]
[ "def", "_split_path", "(", "path", ",", "seps", "=", "PATH_SEPS", ")", ":", "if", "not", "path", ":", "return", "[", "]", "for", "sep", "in", "seps", ":", "if", "sep", "in", "path", ":", "if", "path", "==", "sep", ":", "# Special case, '/' or '.' only.", "return", "[", "''", "]", "return", "[", "x", "for", "x", "in", "path", ".", "split", "(", "sep", ")", "if", "x", "]", "return", "[", "path", "]" ]
Parse path expression and return list of path items. :param path: Path expression may contain separator chars. :param seps: Separator char candidates. :return: A list of keys to fetch object[s] later. >>> assert _split_path('') == [] >>> assert _split_path('/') == [''] # JSON Pointer spec expects this. >>> for p in ('/a', '.a', 'a', 'a.'): ... assert _split_path(p) == ['a'], p >>> assert _split_path('/a/b/c') == _split_path('a.b.c') == ['a', 'b', 'c'] >>> assert _split_path('abc') == ['abc']
[ "Parse", "path", "expression", "and", "return", "list", "of", "path", "items", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L50-L74
2,744
ssato/python-anyconfig
src/anyconfig/dicts.py
mk_nested_dic
def mk_nested_dic(path, val, seps=PATH_SEPS): """ Make a nested dict iteratively. :param path: Path expression to make a nested dict :param val: Value to set :param seps: Separator char candidates >>> mk_nested_dic("a.b.c", 1) {'a': {'b': {'c': 1}}} >>> mk_nested_dic("/a/b/c", 1) {'a': {'b': {'c': 1}}} """ ret = None for key in reversed(_split_path(path, seps)): ret = {key: val if ret is None else ret.copy()} return ret
python
def mk_nested_dic(path, val, seps=PATH_SEPS): ret = None for key in reversed(_split_path(path, seps)): ret = {key: val if ret is None else ret.copy()} return ret
[ "def", "mk_nested_dic", "(", "path", ",", "val", ",", "seps", "=", "PATH_SEPS", ")", ":", "ret", "=", "None", "for", "key", "in", "reversed", "(", "_split_path", "(", "path", ",", "seps", ")", ")", ":", "ret", "=", "{", "key", ":", "val", "if", "ret", "is", "None", "else", "ret", ".", "copy", "(", ")", "}", "return", "ret" ]
Make a nested dict iteratively. :param path: Path expression to make a nested dict :param val: Value to set :param seps: Separator char candidates >>> mk_nested_dic("a.b.c", 1) {'a': {'b': {'c': 1}}} >>> mk_nested_dic("/a/b/c", 1) {'a': {'b': {'c': 1}}}
[ "Make", "a", "nested", "dict", "iteratively", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L77-L94
2,745
ssato/python-anyconfig
src/anyconfig/dicts.py
get
def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG): """getter for nested dicts. :param dic: a dict[-like] object :param path: Path expression to point object wanted :param seps: Separator char candidates :return: A tuple of (result_object, error_message) >>> d = {'a': {'b': {'c': 0, 'd': [1, 2]}}, '': 3} >>> assert get(d, '/') == (3, '') # key becomes '' (empty string). >>> assert get(d, "/a/b/c") == (0, '') >>> sorted(get(d, "a.b")[0].items()) [('c', 0), ('d', [1, 2])] >>> (get(d, "a.b.d"), get(d, "/a/b/d/1")) (([1, 2], ''), (2, '')) >>> get(d, "a.b.key_not_exist") # doctest: +ELLIPSIS (None, "'...'") >>> get(d, "/a/b/d/2") (None, 'list index out of range') >>> get(d, "/a/b/d/-") # doctest: +ELLIPSIS (None, 'list indices must be integers...') """ items = [_jsnp_unescape(p) for p in _split_path(path, seps)] if not items: return (dic, '') try: if len(items) == 1: return (dic[items[0]], '') prnt = functools.reduce(operator.getitem, items[:-1], dic) arr = anyconfig.utils.is_list_like(prnt) and idx_reg.match(items[-1]) return (prnt[int(items[-1])], '') if arr else (prnt[items[-1]], '') except (TypeError, KeyError, IndexError) as exc: return (None, str(exc))
python
def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG): items = [_jsnp_unescape(p) for p in _split_path(path, seps)] if not items: return (dic, '') try: if len(items) == 1: return (dic[items[0]], '') prnt = functools.reduce(operator.getitem, items[:-1], dic) arr = anyconfig.utils.is_list_like(prnt) and idx_reg.match(items[-1]) return (prnt[int(items[-1])], '') if arr else (prnt[items[-1]], '') except (TypeError, KeyError, IndexError) as exc: return (None, str(exc))
[ "def", "get", "(", "dic", ",", "path", ",", "seps", "=", "PATH_SEPS", ",", "idx_reg", "=", "_JSNP_GET_ARRAY_IDX_REG", ")", ":", "items", "=", "[", "_jsnp_unescape", "(", "p", ")", "for", "p", "in", "_split_path", "(", "path", ",", "seps", ")", "]", "if", "not", "items", ":", "return", "(", "dic", ",", "''", ")", "try", ":", "if", "len", "(", "items", ")", "==", "1", ":", "return", "(", "dic", "[", "items", "[", "0", "]", "]", ",", "''", ")", "prnt", "=", "functools", ".", "reduce", "(", "operator", ".", "getitem", ",", "items", "[", ":", "-", "1", "]", ",", "dic", ")", "arr", "=", "anyconfig", ".", "utils", ".", "is_list_like", "(", "prnt", ")", "and", "idx_reg", ".", "match", "(", "items", "[", "-", "1", "]", ")", "return", "(", "prnt", "[", "int", "(", "items", "[", "-", "1", "]", ")", "]", ",", "''", ")", "if", "arr", "else", "(", "prnt", "[", "items", "[", "-", "1", "]", "]", ",", "''", ")", "except", "(", "TypeError", ",", "KeyError", ",", "IndexError", ")", "as", "exc", ":", "return", "(", "None", ",", "str", "(", "exc", ")", ")" ]
getter for nested dicts. :param dic: a dict[-like] object :param path: Path expression to point object wanted :param seps: Separator char candidates :return: A tuple of (result_object, error_message) >>> d = {'a': {'b': {'c': 0, 'd': [1, 2]}}, '': 3} >>> assert get(d, '/') == (3, '') # key becomes '' (empty string). >>> assert get(d, "/a/b/c") == (0, '') >>> sorted(get(d, "a.b")[0].items()) [('c', 0), ('d', [1, 2])] >>> (get(d, "a.b.d"), get(d, "/a/b/d/1")) (([1, 2], ''), (2, '')) >>> get(d, "a.b.key_not_exist") # doctest: +ELLIPSIS (None, "'...'") >>> get(d, "/a/b/d/2") (None, 'list index out of range') >>> get(d, "/a/b/d/-") # doctest: +ELLIPSIS (None, 'list indices must be integers...')
[ "getter", "for", "nested", "dicts", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L97-L131
2,746
ssato/python-anyconfig
src/anyconfig/dicts.py
set_
def set_(dic, path, val, seps=PATH_SEPS): """setter for nested dicts. :param dic: a dict[-like] object support recursive merge operations :param path: Path expression to point object wanted :param seps: Separator char candidates >>> d = dict(a=1, b=dict(c=2, )) >>> set_(d, 'a.b.d', 3) >>> d['a']['b']['d'] 3 """ merge(dic, mk_nested_dic(path, val, seps), ac_merge=MS_DICTS)
python
def set_(dic, path, val, seps=PATH_SEPS): merge(dic, mk_nested_dic(path, val, seps), ac_merge=MS_DICTS)
[ "def", "set_", "(", "dic", ",", "path", ",", "val", ",", "seps", "=", "PATH_SEPS", ")", ":", "merge", "(", "dic", ",", "mk_nested_dic", "(", "path", ",", "val", ",", "seps", ")", ",", "ac_merge", "=", "MS_DICTS", ")" ]
setter for nested dicts. :param dic: a dict[-like] object support recursive merge operations :param path: Path expression to point object wanted :param seps: Separator char candidates >>> d = dict(a=1, b=dict(c=2, )) >>> set_(d, 'a.b.d', 3) >>> d['a']['b']['d'] 3
[ "setter", "for", "nested", "dicts", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L134-L146
2,747
ssato/python-anyconfig
src/anyconfig/dicts.py
_update_with_replace
def _update_with_replace(self, other, key, val=None, **options): """ Replace value of a mapping object 'self' with 'other' has if both have same keys on update. Otherwise, just keep the value of 'self'. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated """ self[key] = other[key] if val is None else val
python
def _update_with_replace(self, other, key, val=None, **options): self[key] = other[key] if val is None else val
[ "def", "_update_with_replace", "(", "self", ",", "other", ",", "key", ",", "val", "=", "None", ",", "*", "*", "options", ")", ":", "self", "[", "key", "]", "=", "other", "[", "key", "]", "if", "val", "is", "None", "else", "val" ]
Replace value of a mapping object 'self' with 'other' has if both have same keys on update. Otherwise, just keep the value of 'self'. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated
[ "Replace", "value", "of", "a", "mapping", "object", "self", "with", "other", "has", "if", "both", "have", "same", "keys", "on", "update", ".", "Otherwise", "just", "keep", "the", "value", "of", "self", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L161-L173
2,748
ssato/python-anyconfig
src/anyconfig/dicts.py
_update_with_merge
def _update_with_merge(self, other, key, val=None, merge_lists=False, **options): """ Merge the value of self with other's recursively. Behavior of merge will be vary depends on types of original and new values. - mapping vs. mapping -> merge recursively - list vs. list -> vary depends on 'merge_lists'. see its description. :param other: a dict[-like] object or a list of (key, value) tuples :param key: key of mapping object to update :param val: value to update self[key] :param merge_lists: Merge not only dicts but also lists. For example, [1, 2, 3], [3, 4] ==> [1, 2, 3, 4] [1, 2, 2], [2, 4] ==> [1, 2, 2, 4] :return: None but 'self' will be updated """ if val is None: val = other[key] if key in self: val0 = self[key] # Original value if anyconfig.utils.is_dict_like(val0): # It needs recursive updates. merge(self[key], val, merge_lists=merge_lists, **options) elif merge_lists and _are_list_like(val, val0): _merge_list(self, key, val) else: _merge_other(self, key, val) else: self[key] = val
python
def _update_with_merge(self, other, key, val=None, merge_lists=False, **options): if val is None: val = other[key] if key in self: val0 = self[key] # Original value if anyconfig.utils.is_dict_like(val0): # It needs recursive updates. merge(self[key], val, merge_lists=merge_lists, **options) elif merge_lists and _are_list_like(val, val0): _merge_list(self, key, val) else: _merge_other(self, key, val) else: self[key] = val
[ "def", "_update_with_merge", "(", "self", ",", "other", ",", "key", ",", "val", "=", "None", ",", "merge_lists", "=", "False", ",", "*", "*", "options", ")", ":", "if", "val", "is", "None", ":", "val", "=", "other", "[", "key", "]", "if", "key", "in", "self", ":", "val0", "=", "self", "[", "key", "]", "# Original value", "if", "anyconfig", ".", "utils", ".", "is_dict_like", "(", "val0", ")", ":", "# It needs recursive updates.", "merge", "(", "self", "[", "key", "]", ",", "val", ",", "merge_lists", "=", "merge_lists", ",", "*", "*", "options", ")", "elif", "merge_lists", "and", "_are_list_like", "(", "val", ",", "val0", ")", ":", "_merge_list", "(", "self", ",", "key", ",", "val", ")", "else", ":", "_merge_other", "(", "self", ",", "key", ",", "val", ")", "else", ":", "self", "[", "key", "]", "=", "val" ]
Merge the value of self with other's recursively. Behavior of merge will be vary depends on types of original and new values. - mapping vs. mapping -> merge recursively - list vs. list -> vary depends on 'merge_lists'. see its description. :param other: a dict[-like] object or a list of (key, value) tuples :param key: key of mapping object to update :param val: value to update self[key] :param merge_lists: Merge not only dicts but also lists. For example, [1, 2, 3], [3, 4] ==> [1, 2, 3, 4] [1, 2, 2], [2, 4] ==> [1, 2, 2, 4] :return: None but 'self' will be updated
[ "Merge", "the", "value", "of", "self", "with", "other", "s", "recursively", ".", "Behavior", "of", "merge", "will", "be", "vary", "depends", "on", "types", "of", "original", "and", "new", "values", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L208-L240
2,749
ssato/python-anyconfig
src/anyconfig/dicts.py
_update_with_merge_lists
def _update_with_merge_lists(self, other, key, val=None, **options): """ Similar to _update_with_merge but merge lists always. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated """ _update_with_merge(self, other, key, val=val, merge_lists=True, **options)
python
def _update_with_merge_lists(self, other, key, val=None, **options): _update_with_merge(self, other, key, val=val, merge_lists=True, **options)
[ "def", "_update_with_merge_lists", "(", "self", ",", "other", ",", "key", ",", "val", "=", "None", ",", "*", "*", "options", ")", ":", "_update_with_merge", "(", "self", ",", "other", ",", "key", ",", "val", "=", "val", ",", "merge_lists", "=", "True", ",", "*", "*", "options", ")" ]
Similar to _update_with_merge but merge lists always. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated
[ "Similar", "to", "_update_with_merge", "but", "merge", "lists", "always", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L243-L254
2,750
ssato/python-anyconfig
src/anyconfig/dicts.py
_get_update_fn
def _get_update_fn(strategy): """ Select dict-like class based on merge strategy and orderness of keys. :param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts. :return: Callable to update objects """ if strategy is None: strategy = MS_DICTS try: return _MERGE_FNS[strategy] except KeyError: if callable(strategy): return strategy raise ValueError("Wrong merge strategy: %r" % strategy)
python
def _get_update_fn(strategy): if strategy is None: strategy = MS_DICTS try: return _MERGE_FNS[strategy] except KeyError: if callable(strategy): return strategy raise ValueError("Wrong merge strategy: %r" % strategy)
[ "def", "_get_update_fn", "(", "strategy", ")", ":", "if", "strategy", "is", "None", ":", "strategy", "=", "MS_DICTS", "try", ":", "return", "_MERGE_FNS", "[", "strategy", "]", "except", "KeyError", ":", "if", "callable", "(", "strategy", ")", ":", "return", "strategy", "raise", "ValueError", "(", "\"Wrong merge strategy: %r\"", "%", "strategy", ")" ]
Select dict-like class based on merge strategy and orderness of keys. :param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts. :return: Callable to update objects
[ "Select", "dict", "-", "like", "class", "based", "on", "merge", "strategy", "and", "orderness", "of", "keys", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L263-L278
2,751
ssato/python-anyconfig
src/anyconfig/backend/properties.py
_parseline
def _parseline(line): """ Parse a line of Java properties file. :param line: A string to parse, must not start with ' ', '#' or '!' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline(" ") (None, '') >>> _parseline("aaa:") ('aaa', '') >>> _parseline(" aaa:") ('aaa', '') >>> _parseline("aaa") ('aaa', '') >>> _parseline("url = http://localhost") ('url', 'http://localhost') >>> _parseline("calendar.japanese.type: LocalGregorianCalendar") ('calendar.japanese.type', 'LocalGregorianCalendar') """ pair = re.split(r"(?:\s+)?(?:(?<!\\)[=:])", line.strip(), 1) key = pair[0].rstrip() if len(pair) < 2: LOGGER.warning("Invalid line found: %s", line) return (key or None, '') return (key, pair[1].strip())
python
def _parseline(line): pair = re.split(r"(?:\s+)?(?:(?<!\\)[=:])", line.strip(), 1) key = pair[0].rstrip() if len(pair) < 2: LOGGER.warning("Invalid line found: %s", line) return (key or None, '') return (key, pair[1].strip())
[ "def", "_parseline", "(", "line", ")", ":", "pair", "=", "re", ".", "split", "(", "r\"(?:\\s+)?(?:(?<!\\\\)[=:])\"", ",", "line", ".", "strip", "(", ")", ",", "1", ")", "key", "=", "pair", "[", "0", "]", ".", "rstrip", "(", ")", "if", "len", "(", "pair", ")", "<", "2", ":", "LOGGER", ".", "warning", "(", "\"Invalid line found: %s\"", ",", "line", ")", "return", "(", "key", "or", "None", ",", "''", ")", "return", "(", "key", ",", "pair", "[", "1", "]", ".", "strip", "(", ")", ")" ]
Parse a line of Java properties file. :param line: A string to parse, must not start with ' ', '#' or '!' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline(" ") (None, '') >>> _parseline("aaa:") ('aaa', '') >>> _parseline(" aaa:") ('aaa', '') >>> _parseline("aaa") ('aaa', '') >>> _parseline("url = http://localhost") ('url', 'http://localhost') >>> _parseline("calendar.japanese.type: LocalGregorianCalendar") ('calendar.japanese.type', 'LocalGregorianCalendar')
[ "Parse", "a", "line", "of", "Java", "properties", "file", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/properties.py#L46-L74
2,752
ssato/python-anyconfig
src/anyconfig/backend/properties.py
_pre_process_line
def _pre_process_line(line, comment_markers=_COMMENT_MARKERS): """ Preprocess a line in properties; strip comments, etc. :param line: A string not starting w/ any white spaces and ending w/ line breaks. It may be empty. see also: :func:`load`. :param comment_markers: Comment markers, e.g. '#' (hash) >>> _pre_process_line('') is None True >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> _pre_process_line("# " + s0) is None True >>> _pre_process_line("! " + s0) is None True >>> _pre_process_line(s0 + "# comment") 'calendar.japanese.type: LocalGregorianCalendar# comment' """ if not line: return None if any(c in line for c in comment_markers): if line.startswith(comment_markers): return None return line
python
def _pre_process_line(line, comment_markers=_COMMENT_MARKERS): if not line: return None if any(c in line for c in comment_markers): if line.startswith(comment_markers): return None return line
[ "def", "_pre_process_line", "(", "line", ",", "comment_markers", "=", "_COMMENT_MARKERS", ")", ":", "if", "not", "line", ":", "return", "None", "if", "any", "(", "c", "in", "line", "for", "c", "in", "comment_markers", ")", ":", "if", "line", ".", "startswith", "(", "comment_markers", ")", ":", "return", "None", "return", "line" ]
Preprocess a line in properties; strip comments, etc. :param line: A string not starting w/ any white spaces and ending w/ line breaks. It may be empty. see also: :func:`load`. :param comment_markers: Comment markers, e.g. '#' (hash) >>> _pre_process_line('') is None True >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> _pre_process_line("# " + s0) is None True >>> _pre_process_line("! " + s0) is None True >>> _pre_process_line(s0 + "# comment") 'calendar.japanese.type: LocalGregorianCalendar# comment'
[ "Preprocess", "a", "line", "in", "properties", ";", "strip", "comments", "etc", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/properties.py#L77-L103
2,753
ssato/python-anyconfig
src/anyconfig/backend/properties.py
load
def load(stream, container=dict, comment_markers=_COMMENT_MARKERS): """ Load and parse Java properties file given as a fiel or file-like object 'stream'. :param stream: A file or file like object of Java properties files :param container: Factory function to create a dict-like object to store properties :param comment_markers: Comment markers, e.g. '#' (hash) :return: Dict-like object holding properties >>> to_strm = anyconfig.compat.StringIO >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> load(to_strm('')) {} >>> load(to_strm("# " + s0)) {} >>> load(to_strm("! " + s0)) {} >>> load(to_strm("calendar.japanese.type:")) {'calendar.japanese.type': ''} >>> load(to_strm(s0)) {'calendar.japanese.type': 'LocalGregorianCalendar'} >>> load(to_strm(s0 + "# ...")) {'calendar.japanese.type': 'LocalGregorianCalendar# ...'} >>> s1 = r"key=a\\:b" >>> load(to_strm(s1)) {'key': 'a:b'} >>> s2 = '''application/postscript: \\ ... x=Postscript File;y=.eps,.ps ... ''' >>> load(to_strm(s2)) {'application/postscript': 'x=Postscript File;y=.eps,.ps'} """ ret = container() prev = "" for line in stream.readlines(): line = _pre_process_line(prev + line.strip().rstrip(), comment_markers) # I don't think later case may happen but just in case. if line is None or not line: continue prev = "" # re-initialize for later use. if line.endswith("\\"): prev += line.rstrip(" \\") continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Failed to parse the line: %s", line) continue ret[key] = unescape(val) return ret
python
def load(stream, container=dict, comment_markers=_COMMENT_MARKERS): ret = container() prev = "" for line in stream.readlines(): line = _pre_process_line(prev + line.strip().rstrip(), comment_markers) # I don't think later case may happen but just in case. if line is None or not line: continue prev = "" # re-initialize for later use. if line.endswith("\\"): prev += line.rstrip(" \\") continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Failed to parse the line: %s", line) continue ret[key] = unescape(val) return ret
[ "def", "load", "(", "stream", ",", "container", "=", "dict", ",", "comment_markers", "=", "_COMMENT_MARKERS", ")", ":", "ret", "=", "container", "(", ")", "prev", "=", "\"\"", "for", "line", "in", "stream", ".", "readlines", "(", ")", ":", "line", "=", "_pre_process_line", "(", "prev", "+", "line", ".", "strip", "(", ")", ".", "rstrip", "(", ")", ",", "comment_markers", ")", "# I don't think later case may happen but just in case.", "if", "line", "is", "None", "or", "not", "line", ":", "continue", "prev", "=", "\"\"", "# re-initialize for later use.", "if", "line", ".", "endswith", "(", "\"\\\\\"", ")", ":", "prev", "+=", "line", ".", "rstrip", "(", "\" \\\\\"", ")", "continue", "(", "key", ",", "val", ")", "=", "_parseline", "(", "line", ")", "if", "key", "is", "None", ":", "LOGGER", ".", "warning", "(", "\"Failed to parse the line: %s\"", ",", "line", ")", "continue", "ret", "[", "key", "]", "=", "unescape", "(", "val", ")", "return", "ret" ]
Load and parse Java properties file given as a fiel or file-like object 'stream'. :param stream: A file or file like object of Java properties files :param container: Factory function to create a dict-like object to store properties :param comment_markers: Comment markers, e.g. '#' (hash) :return: Dict-like object holding properties >>> to_strm = anyconfig.compat.StringIO >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> load(to_strm('')) {} >>> load(to_strm("# " + s0)) {} >>> load(to_strm("! " + s0)) {} >>> load(to_strm("calendar.japanese.type:")) {'calendar.japanese.type': ''} >>> load(to_strm(s0)) {'calendar.japanese.type': 'LocalGregorianCalendar'} >>> load(to_strm(s0 + "# ...")) {'calendar.japanese.type': 'LocalGregorianCalendar# ...'} >>> s1 = r"key=a\\:b" >>> load(to_strm(s1)) {'key': 'a:b'} >>> s2 = '''application/postscript: \\ ... x=Postscript File;y=.eps,.ps ... ''' >>> load(to_strm(s2)) {'application/postscript': 'x=Postscript File;y=.eps,.ps'}
[ "Load", "and", "parse", "Java", "properties", "file", "given", "as", "a", "fiel", "or", "file", "-", "like", "object", "stream", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/properties.py#L136-L193
2,754
ssato/python-anyconfig
src/anyconfig/template.py
render_s
def render_s(tmpl_s, ctx=None, paths=None, filters=None): """ Compile and render given template string 'tmpl_s' with context 'context'. :param tmpl_s: Template string :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param filters: Custom filters to add into template engine :return: Compiled result (str) >>> render_s("aaa") == "aaa" True >>> s = render_s('a = {{ a }}, b = "{{ b }}"', {'a': 1, 'b': 'bbb'}) >>> if SUPPORTED: ... assert s == 'a = 1, b = "bbb"' """ if paths is None: paths = [os.curdir] env = tmpl_env(paths) if env is None: return tmpl_s if filters is not None: env.filters.update(filters) if ctx is None: ctx = {} return tmpl_env(paths).from_string(tmpl_s).render(**ctx)
python
def render_s(tmpl_s, ctx=None, paths=None, filters=None): if paths is None: paths = [os.curdir] env = tmpl_env(paths) if env is None: return tmpl_s if filters is not None: env.filters.update(filters) if ctx is None: ctx = {} return tmpl_env(paths).from_string(tmpl_s).render(**ctx)
[ "def", "render_s", "(", "tmpl_s", ",", "ctx", "=", "None", ",", "paths", "=", "None", ",", "filters", "=", "None", ")", ":", "if", "paths", "is", "None", ":", "paths", "=", "[", "os", ".", "curdir", "]", "env", "=", "tmpl_env", "(", "paths", ")", "if", "env", "is", "None", ":", "return", "tmpl_s", "if", "filters", "is", "not", "None", ":", "env", ".", "filters", ".", "update", "(", "filters", ")", "if", "ctx", "is", "None", ":", "ctx", "=", "{", "}", "return", "tmpl_env", "(", "paths", ")", ".", "from_string", "(", "tmpl_s", ")", ".", "render", "(", "*", "*", "ctx", ")" ]
Compile and render given template string 'tmpl_s' with context 'context'. :param tmpl_s: Template string :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param filters: Custom filters to add into template engine :return: Compiled result (str) >>> render_s("aaa") == "aaa" True >>> s = render_s('a = {{ a }}, b = "{{ b }}"', {'a': 1, 'b': 'bbb'}) >>> if SUPPORTED: ... assert s == 'a = 1, b = "bbb"'
[ "Compile", "and", "render", "given", "template", "string", "tmpl_s", "with", "context", "context", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L92-L122
2,755
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_to_s
def _to_s(val, sep=", "): """Convert any to string. :param val: An object :param sep: separator between values >>> _to_s([1, 2, 3]) '1, 2, 3' >>> _to_s("aaa") 'aaa' """ if anyconfig.utils.is_iterable(val): return sep.join(str(x) for x in val) return str(val)
python
def _to_s(val, sep=", "): if anyconfig.utils.is_iterable(val): return sep.join(str(x) for x in val) return str(val)
[ "def", "_to_s", "(", "val", ",", "sep", "=", "\", \"", ")", ":", "if", "anyconfig", ".", "utils", ".", "is_iterable", "(", "val", ")", ":", "return", "sep", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "val", ")", "return", "str", "(", "val", ")" ]
Convert any to string. :param val: An object :param sep: separator between values >>> _to_s([1, 2, 3]) '1, 2, 3' >>> _to_s("aaa") 'aaa'
[ "Convert", "any", "to", "string", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L75-L89
2,756
ssato/python-anyconfig
src/anyconfig/query.py
query
def query(data, **options): """ Filter data with given JMESPath expression. See also: https://github.com/jmespath/jmespath.py and http://jmespath.org. :param data: Target object (a dict or a dict-like object) to query :param options: Keyword option may include 'ac_query' which is a string represents JMESPath expression. :return: Maybe queried result data, primitive (int, str, ...) or dict """ expression = options.get("ac_query", None) if expression is None or not expression: return data try: pexp = jmespath.compile(expression) return pexp.search(data) except ValueError as exc: # jmespath.exceptions.*Error inherit from it. LOGGER.warning("Failed to compile or search: exp=%s, exc=%r", expression, exc) except (NameError, AttributeError): LOGGER.warning("Filter module (jmespath) is not available. " "Do nothing.") return data
python
def query(data, **options): expression = options.get("ac_query", None) if expression is None or not expression: return data try: pexp = jmespath.compile(expression) return pexp.search(data) except ValueError as exc: # jmespath.exceptions.*Error inherit from it. LOGGER.warning("Failed to compile or search: exp=%s, exc=%r", expression, exc) except (NameError, AttributeError): LOGGER.warning("Filter module (jmespath) is not available. " "Do nothing.") return data
[ "def", "query", "(", "data", ",", "*", "*", "options", ")", ":", "expression", "=", "options", ".", "get", "(", "\"ac_query\"", ",", "None", ")", "if", "expression", "is", "None", "or", "not", "expression", ":", "return", "data", "try", ":", "pexp", "=", "jmespath", ".", "compile", "(", "expression", ")", "return", "pexp", ".", "search", "(", "data", ")", "except", "ValueError", "as", "exc", ":", "# jmespath.exceptions.*Error inherit from it.", "LOGGER", ".", "warning", "(", "\"Failed to compile or search: exp=%s, exc=%r\"", ",", "expression", ",", "exc", ")", "except", "(", "NameError", ",", "AttributeError", ")", ":", "LOGGER", ".", "warning", "(", "\"Filter module (jmespath) is not available. \"", "\"Do nothing.\"", ")", "return", "data" ]
Filter data with given JMESPath expression. See also: https://github.com/jmespath/jmespath.py and http://jmespath.org. :param data: Target object (a dict or a dict-like object) to query :param options: Keyword option may include 'ac_query' which is a string represents JMESPath expression. :return: Maybe queried result data, primitive (int, str, ...) or dict
[ "Filter", "data", "with", "given", "JMESPath", "expression", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/query.py#L22-L49
2,757
ssato/python-anyconfig
src/anyconfig/utils.py
groupby
def groupby(itr, key_fn=None): """ An wrapper function around itertools.groupby to sort each results. :param itr: Iterable object, a list/tuple/genrator, etc. :param key_fn: Key function to sort 'itr'. >>> import operator >>> itr = [("a", 1), ("b", -1), ("c", 1)] >>> res = groupby(itr, operator.itemgetter(1)) >>> [(key, tuple(grp)) for key, grp in res] [(-1, (('b', -1),)), (1, (('a', 1), ('c', 1)))] """ return itertools.groupby(sorted(itr, key=key_fn), key=key_fn)
python
def groupby(itr, key_fn=None): return itertools.groupby(sorted(itr, key=key_fn), key=key_fn)
[ "def", "groupby", "(", "itr", ",", "key_fn", "=", "None", ")", ":", "return", "itertools", ".", "groupby", "(", "sorted", "(", "itr", ",", "key", "=", "key_fn", ")", ",", "key", "=", "key_fn", ")" ]
An wrapper function around itertools.groupby to sort each results. :param itr: Iterable object, a list/tuple/genrator, etc. :param key_fn: Key function to sort 'itr'. >>> import operator >>> itr = [("a", 1), ("b", -1), ("c", 1)] >>> res = groupby(itr, operator.itemgetter(1)) >>> [(key, tuple(grp)) for key, grp in res] [(-1, (('b', -1),)), (1, (('a', 1), ('c', 1)))]
[ "An", "wrapper", "function", "around", "itertools", ".", "groupby", "to", "sort", "each", "results", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L22-L35
2,758
ssato/python-anyconfig
src/anyconfig/utils.py
is_paths
def is_paths(maybe_paths, marker='*'): """ Does given object 'maybe_paths' consist of path or path pattern strings? """ return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str (is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or (is_iterable(maybe_paths) and all(is_path(p) or is_ioinfo(p) for p in maybe_paths)))
python
def is_paths(maybe_paths, marker='*'): return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str (is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or (is_iterable(maybe_paths) and all(is_path(p) or is_ioinfo(p) for p in maybe_paths)))
[ "def", "is_paths", "(", "maybe_paths", ",", "marker", "=", "'*'", ")", ":", "return", "(", "(", "is_path", "(", "maybe_paths", ")", "and", "marker", "in", "maybe_paths", ")", "or", "# Path str", "(", "is_path_obj", "(", "maybe_paths", ")", "and", "marker", "in", "maybe_paths", ".", "as_posix", "(", ")", ")", "or", "(", "is_iterable", "(", "maybe_paths", ")", "and", "all", "(", "is_path", "(", "p", ")", "or", "is_ioinfo", "(", "p", ")", "for", "p", "in", "maybe_paths", ")", ")", ")" ]
Does given object 'maybe_paths' consist of path or path pattern strings?
[ "Does", "given", "object", "maybe_paths", "consist", "of", "path", "or", "path", "pattern", "strings?" ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L220-L227
2,759
ssato/python-anyconfig
src/anyconfig/utils.py
get_path_from_stream
def get_path_from_stream(strm): """ Try to get file path from given file or file-like object 'strm'. :param strm: A file or file-like object :return: Path of given file or file-like object or None :raises: ValueError >>> assert __file__ == get_path_from_stream(open(__file__, 'r')) >>> assert get_path_from_stream(anyconfig.compat.StringIO()) is None >>> get_path_from_stream(__file__) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ... """ if not is_file_stream(strm): raise ValueError("Given object does not look a file/file-like " "object: %r" % strm) path = getattr(strm, "name", None) if path is not None: try: return normpath(path) except (TypeError, ValueError): pass return None
python
def get_path_from_stream(strm): if not is_file_stream(strm): raise ValueError("Given object does not look a file/file-like " "object: %r" % strm) path = getattr(strm, "name", None) if path is not None: try: return normpath(path) except (TypeError, ValueError): pass return None
[ "def", "get_path_from_stream", "(", "strm", ")", ":", "if", "not", "is_file_stream", "(", "strm", ")", ":", "raise", "ValueError", "(", "\"Given object does not look a file/file-like \"", "\"object: %r\"", "%", "strm", ")", "path", "=", "getattr", "(", "strm", ",", "\"name\"", ",", "None", ")", "if", "path", "is", "not", "None", ":", "try", ":", "return", "normpath", "(", "path", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "return", "None" ]
Try to get file path from given file or file-like object 'strm'. :param strm: A file or file-like object :return: Path of given file or file-like object or None :raises: ValueError >>> assert __file__ == get_path_from_stream(open(__file__, 'r')) >>> assert get_path_from_stream(anyconfig.compat.StringIO()) is None >>> get_path_from_stream(__file__) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...
[ "Try", "to", "get", "file", "path", "from", "given", "file", "or", "file", "-", "like", "object", "strm", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L230-L256
2,760
ssato/python-anyconfig
src/anyconfig/utils.py
_try_to_get_extension
def _try_to_get_extension(obj): """ Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py' """ if is_path(obj): path = obj elif is_path_obj(obj): return obj.suffix[1:] elif is_file_stream(obj): try: path = get_path_from_stream(obj) except ValueError: return None elif is_ioinfo(obj): path = obj.path else: return None if path: return get_file_extension(path) return None
python
def _try_to_get_extension(obj): if is_path(obj): path = obj elif is_path_obj(obj): return obj.suffix[1:] elif is_file_stream(obj): try: path = get_path_from_stream(obj) except ValueError: return None elif is_ioinfo(obj): path = obj.path else: return None if path: return get_file_extension(path) return None
[ "def", "_try_to_get_extension", "(", "obj", ")", ":", "if", "is_path", "(", "obj", ")", ":", "path", "=", "obj", "elif", "is_path_obj", "(", "obj", ")", ":", "return", "obj", ".", "suffix", "[", "1", ":", "]", "elif", "is_file_stream", "(", "obj", ")", ":", "try", ":", "path", "=", "get_path_from_stream", "(", "obj", ")", "except", "ValueError", ":", "return", "None", "elif", "is_ioinfo", "(", "obj", ")", ":", "path", "=", "obj", ".", "path", "else", ":", "return", "None", "if", "path", ":", "return", "get_file_extension", "(", "path", ")", "return", "None" ]
Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py'
[ "Try", "to", "get", "file", "extension", "from", "given", "path", "or", "file", "object", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L259-L290
2,761
ssato/python-anyconfig
src/anyconfig/utils.py
filter_options
def filter_options(keys, options): """ Filter 'options' with given 'keys'. :param keys: key names of optional keyword arguments :param options: optional keyword arguments to filter with 'keys' >>> filter_options(("aaa", ), dict(aaa=1, bbb=2)) {'aaa': 1} >>> filter_options(("aaa", ), dict(bbb=2)) {} """ return dict((k, options[k]) for k in keys if k in options)
python
def filter_options(keys, options): return dict((k, options[k]) for k in keys if k in options)
[ "def", "filter_options", "(", "keys", ",", "options", ")", ":", "return", "dict", "(", "(", "k", ",", "options", "[", "k", "]", ")", "for", "k", "in", "keys", "if", "k", "in", "options", ")" ]
Filter 'options' with given 'keys'. :param keys: key names of optional keyword arguments :param options: optional keyword arguments to filter with 'keys' >>> filter_options(("aaa", ), dict(aaa=1, bbb=2)) {'aaa': 1} >>> filter_options(("aaa", ), dict(bbb=2)) {}
[ "Filter", "options", "with", "given", "keys", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L441-L453
2,762
ssato/python-anyconfig
src/anyconfig/utils.py
memoize
def memoize(fnc): """memoization function. >>> import random >>> imax = 100 >>> def fnc1(arg=True): ... return arg and random.choice((True, False)) >>> fnc2 = memoize(fnc1) >>> (ret1, ret2) = (fnc1(), fnc2()) >>> assert any(fnc1() != ret1 for i in range(imax)) >>> assert all(fnc2() == ret2 for i in range(imax)) """ cache = dict() @functools.wraps(fnc) def wrapped(*args, **kwargs): """Decorated one""" key = repr(args) + repr(kwargs) if key not in cache: cache[key] = fnc(*args, **kwargs) return cache[key] return wrapped
python
def memoize(fnc): cache = dict() @functools.wraps(fnc) def wrapped(*args, **kwargs): """Decorated one""" key = repr(args) + repr(kwargs) if key not in cache: cache[key] = fnc(*args, **kwargs) return cache[key] return wrapped
[ "def", "memoize", "(", "fnc", ")", ":", "cache", "=", "dict", "(", ")", "@", "functools", ".", "wraps", "(", "fnc", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Decorated one\"\"\"", "key", "=", "repr", "(", "args", ")", "+", "repr", "(", "kwargs", ")", "if", "key", "not", "in", "cache", ":", "cache", "[", "key", "]", "=", "fnc", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "cache", "[", "key", "]", "return", "wrapped" ]
memoization function. >>> import random >>> imax = 100 >>> def fnc1(arg=True): ... return arg and random.choice((True, False)) >>> fnc2 = memoize(fnc1) >>> (ret1, ret2) = (fnc1(), fnc2()) >>> assert any(fnc1() != ret1 for i in range(imax)) >>> assert all(fnc2() == ret2 for i in range(imax))
[ "memoization", "function", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L456-L479
2,763
ssato/python-anyconfig
src/anyconfig/api.py
open
def open(path, mode=None, ac_parser=None, **options): """ Open given configuration file with appropriate open flag. :param path: Configuration file path :param mode: Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing. Please note that even if you specify 'r' or 'w', it will be changed to 'rb' or 'wb' if selected backend, xml and configobj for example, for given config file prefer that. :param options: Optional keyword arguments passed to the internal file opening APIs of each backends such like 'buffering' optional parameter passed to builtin 'open' function. :return: A file object or None on any errors :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ psr = find(path, forced_type=ac_parser) if mode is not None and mode.startswith('w'): return psr.wopen(path, **options) return psr.ropen(path, **options)
python
def open(path, mode=None, ac_parser=None, **options): psr = find(path, forced_type=ac_parser) if mode is not None and mode.startswith('w'): return psr.wopen(path, **options) return psr.ropen(path, **options)
[ "def", "open", "(", "path", ",", "mode", "=", "None", ",", "ac_parser", "=", "None", ",", "*", "*", "options", ")", ":", "psr", "=", "find", "(", "path", ",", "forced_type", "=", "ac_parser", ")", "if", "mode", "is", "not", "None", "and", "mode", ".", "startswith", "(", "'w'", ")", ":", "return", "psr", ".", "wopen", "(", "path", ",", "*", "*", "options", ")", "return", "psr", ".", "ropen", "(", "path", ",", "*", "*", "options", ")" ]
Open given configuration file with appropriate open flag. :param path: Configuration file path :param mode: Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing. Please note that even if you specify 'r' or 'w', it will be changed to 'rb' or 'wb' if selected backend, xml and configobj for example, for given config file prefer that. :param options: Optional keyword arguments passed to the internal file opening APIs of each backends such like 'buffering' optional parameter passed to builtin 'open' function. :return: A file object or None on any errors :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
[ "Open", "given", "configuration", "file", "with", "appropriate", "open", "flag", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L223-L246
2,764
ssato/python-anyconfig
src/anyconfig/api.py
single_load
def single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single one. :param input\_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments such as: - Options common in :func:`single_load`, :func:`multi_load`, :func:`load` and :func:`loads`: - ac_dict: callable (function or class) to make mapping objects from loaded data if the selected backend can customize that such as JSON which supports that with 'object_pairs_hook' option, or None. If this option was not given or None, dict or :class:`collections.OrderedDict` will be used to make result as mapping object depends on if ac_ordered (see below) is True and selected backend can keep the order of items loaded. See also :meth:`_container_factory` of :class:`anyconfig.backend.base.Parser` for more implementation details. - ac_ordered: True if you want to keep resuls ordered. Please note that order of items may be lost depends on the selected backend. - ac_schema: JSON schema file path to validate given config file - ac_query: JMESPath expression to query data - Common backend options: - ac_ignore_missing: Ignore and just return empty result if given file 'input\_' does not exist actually. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ cnf = _single_load(input_, ac_parser=ac_parser, ac_template=ac_template, ac_context=ac_context, **options) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
python
def single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single one. :param input\_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments such as: - Options common in :func:`single_load`, :func:`multi_load`, :func:`load` and :func:`loads`: - ac_dict: callable (function or class) to make mapping objects from loaded data if the selected backend can customize that such as JSON which supports that with 'object_pairs_hook' option, or None. If this option was not given or None, dict or :class:`collections.OrderedDict` will be used to make result as mapping object depends on if ac_ordered (see below) is True and selected backend can keep the order of items loaded. See also :meth:`_container_factory` of :class:`anyconfig.backend.base.Parser` for more implementation details. - ac_ordered: True if you want to keep resuls ordered. Please note that order of items may be lost depends on the selected backend. - ac_schema: JSON schema file path to validate given config file - ac_query: JMESPath expression to query data - Common backend options: - ac_ignore_missing: Ignore and just return empty result if given file 'input\_' does not exist actually. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ cnf = _single_load(input_, ac_parser=ac_parser, ac_template=ac_template, ac_context=ac_context, **options) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
[ "def", "single_load", "(", "input_", ",", "ac_parser", "=", "None", ",", "ac_template", "=", "False", ",", "ac_context", "=", "None", ",", "*", "*", "options", ")", ":", "cnf", "=", "_single_load", "(", "input_", ",", "ac_parser", "=", "ac_parser", ",", "ac_template", "=", "ac_template", ",", "ac_context", "=", "ac_context", ",", "*", "*", "options", ")", "schema", "=", "_maybe_schema", "(", "ac_template", "=", "ac_template", ",", "ac_context", "=", "ac_context", ",", "*", "*", "options", ")", "cnf", "=", "_try_validate", "(", "cnf", ",", "schema", ",", "*", "*", "options", ")", "return", "anyconfig", ".", "query", ".", "query", "(", "cnf", ",", "*", "*", "options", ")" ]
r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single one. :param input\_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments such as: - Options common in :func:`single_load`, :func:`multi_load`, :func:`load` and :func:`loads`: - ac_dict: callable (function or class) to make mapping objects from loaded data if the selected backend can customize that such as JSON which supports that with 'object_pairs_hook' option, or None. If this option was not given or None, dict or :class:`collections.OrderedDict` will be used to make result as mapping object depends on if ac_ordered (see below) is True and selected backend can keep the order of items loaded. See also :meth:`_container_factory` of :class:`anyconfig.backend.base.Parser` for more implementation details. - ac_ordered: True if you want to keep resuls ordered. Please note that order of items may be lost depends on the selected backend. - ac_schema: JSON schema file path to validate given config file - ac_query: JMESPath expression to query data - Common backend options: - ac_ignore_missing: Ignore and just return empty result if given file 'input\_' does not exist actually. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
[ "r", "Load", "single", "configuration", "file", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L290-L348
2,765
ssato/python-anyconfig
src/anyconfig/api.py
multi_load
def multi_load(inputs, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load multiple config files. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given inputs are multiple ones. The first argument 'inputs' may be a list of a file paths or a glob pattern specifying them or a pathlib.Path object represents file[s] or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. About glob patterns, for example, is, if a.yml, b.yml and c.yml are in the dir /etc/foo/conf.d/, the followings give same results:: multi_load(["/etc/foo/conf.d/a.yml", "/etc/foo/conf.d/b.yml", "/etc/foo/conf.d/c.yml", ]) multi_load("/etc/foo/conf.d/*.yml") :param inputs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from :param ac_parser: Forced parser type or parser object :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Mapping object presents context to instantiate template :param options: Optional keyword arguments: - ac_dict, ac_ordered, ac_schema and ac_query are the options common in :func:`single_load`, :func:`multi_load`, :func:`load`: and :func:`loads`. See the descriptions of them in :func:`single_load`. - Options specific to this function and :func:`load`: - ac_merge (merge): Specify strategy of how to merge results loaded from multiple configuration files. See the doc of :mod:`anyconfig.dicts` for more details of strategies. The default is anyconfig.dicts.MS_DICTS. - ac_marker (marker): Globbing marker to detect paths patterns. - Common backend options: - ignore_missing: Ignore and just return empty result if given file 'path' does not exist. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) options["ac_schema"] = None # Avoid to load schema more than twice. paths = anyconfig.utils.expand_paths(inputs, marker=marker) if anyconfig.utils.are_same_file_types(paths): ac_parser = find(paths[0], forced_type=ac_parser) cnf = ac_context for path in paths: opts = options.copy() cups = _single_load(path, ac_parser=ac_parser, ac_template=ac_template, ac_context=cnf, **opts) if cups: if cnf is None: cnf = cups else: merge(cnf, cups, **options) if cnf is None: return anyconfig.dicts.convert_to({}, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
python
def multi_load(inputs, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load multiple config files. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given inputs are multiple ones. The first argument 'inputs' may be a list of a file paths or a glob pattern specifying them or a pathlib.Path object represents file[s] or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. About glob patterns, for example, is, if a.yml, b.yml and c.yml are in the dir /etc/foo/conf.d/, the followings give same results:: multi_load(["/etc/foo/conf.d/a.yml", "/etc/foo/conf.d/b.yml", "/etc/foo/conf.d/c.yml", ]) multi_load("/etc/foo/conf.d/*.yml") :param inputs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from :param ac_parser: Forced parser type or parser object :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Mapping object presents context to instantiate template :param options: Optional keyword arguments: - ac_dict, ac_ordered, ac_schema and ac_query are the options common in :func:`single_load`, :func:`multi_load`, :func:`load`: and :func:`loads`. See the descriptions of them in :func:`single_load`. - Options specific to this function and :func:`load`: - ac_merge (merge): Specify strategy of how to merge results loaded from multiple configuration files. See the doc of :mod:`anyconfig.dicts` for more details of strategies. The default is anyconfig.dicts.MS_DICTS. - ac_marker (marker): Globbing marker to detect paths patterns. - Common backend options: - ignore_missing: Ignore and just return empty result if given file 'path' does not exist. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) options["ac_schema"] = None # Avoid to load schema more than twice. paths = anyconfig.utils.expand_paths(inputs, marker=marker) if anyconfig.utils.are_same_file_types(paths): ac_parser = find(paths[0], forced_type=ac_parser) cnf = ac_context for path in paths: opts = options.copy() cups = _single_load(path, ac_parser=ac_parser, ac_template=ac_template, ac_context=cnf, **opts) if cups: if cnf is None: cnf = cups else: merge(cnf, cups, **options) if cnf is None: return anyconfig.dicts.convert_to({}, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
[ "def", "multi_load", "(", "inputs", ",", "ac_parser", "=", "None", ",", "ac_template", "=", "False", ",", "ac_context", "=", "None", ",", "*", "*", "options", ")", ":", "marker", "=", "options", ".", "setdefault", "(", "\"ac_marker\"", ",", "options", ".", "get", "(", "\"marker\"", ",", "'*'", ")", ")", "schema", "=", "_maybe_schema", "(", "ac_template", "=", "ac_template", ",", "ac_context", "=", "ac_context", ",", "*", "*", "options", ")", "options", "[", "\"ac_schema\"", "]", "=", "None", "# Avoid to load schema more than twice.", "paths", "=", "anyconfig", ".", "utils", ".", "expand_paths", "(", "inputs", ",", "marker", "=", "marker", ")", "if", "anyconfig", ".", "utils", ".", "are_same_file_types", "(", "paths", ")", ":", "ac_parser", "=", "find", "(", "paths", "[", "0", "]", ",", "forced_type", "=", "ac_parser", ")", "cnf", "=", "ac_context", "for", "path", "in", "paths", ":", "opts", "=", "options", ".", "copy", "(", ")", "cups", "=", "_single_load", "(", "path", ",", "ac_parser", "=", "ac_parser", ",", "ac_template", "=", "ac_template", ",", "ac_context", "=", "cnf", ",", "*", "*", "opts", ")", "if", "cups", ":", "if", "cnf", "is", "None", ":", "cnf", "=", "cups", "else", ":", "merge", "(", "cnf", ",", "cups", ",", "*", "*", "options", ")", "if", "cnf", "is", "None", ":", "return", "anyconfig", ".", "dicts", ".", "convert_to", "(", "{", "}", ",", "*", "*", "options", ")", "cnf", "=", "_try_validate", "(", "cnf", ",", "schema", ",", "*", "*", "options", ")", "return", "anyconfig", ".", "query", ".", "query", "(", "cnf", ",", "*", "*", "options", ")" ]
r""" Load multiple config files. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given inputs are multiple ones. The first argument 'inputs' may be a list of a file paths or a glob pattern specifying them or a pathlib.Path object represents file[s] or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. About glob patterns, for example, is, if a.yml, b.yml and c.yml are in the dir /etc/foo/conf.d/, the followings give same results:: multi_load(["/etc/foo/conf.d/a.yml", "/etc/foo/conf.d/b.yml", "/etc/foo/conf.d/c.yml", ]) multi_load("/etc/foo/conf.d/*.yml") :param inputs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from :param ac_parser: Forced parser type or parser object :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Mapping object presents context to instantiate template :param options: Optional keyword arguments: - ac_dict, ac_ordered, ac_schema and ac_query are the options common in :func:`single_load`, :func:`multi_load`, :func:`load`: and :func:`loads`. See the descriptions of them in :func:`single_load`. - Options specific to this function and :func:`load`: - ac_merge (merge): Specify strategy of how to merge results loaded from multiple configuration files. See the doc of :mod:`anyconfig.dicts` for more details of strategies. The default is anyconfig.dicts.MS_DICTS. - ac_marker (marker): Globbing marker to detect paths patterns. - Common backend options: - ignore_missing: Ignore and just return empty result if given file 'path' does not exist. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
[ "r", "Load", "multiple", "config", "files", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L351-L432
2,766
ssato/python-anyconfig
src/anyconfig/api.py
load
def load(path_specs, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): r""" Load single or multiple config files or multiple config files specified in given paths pattern or pathlib.Path object represents config files or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs. :param path_specs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. :param ac_parser: Forced parser type or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` and :func:`multi_load` :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) if anyconfig.utils.is_path_like_object(path_specs, marker): return single_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options) if not anyconfig.utils.is_paths(path_specs, marker): raise ValueError("Possible invalid input %r" % path_specs) return multi_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options)
python
def load(path_specs, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): r""" Load single or multiple config files or multiple config files specified in given paths pattern or pathlib.Path object represents config files or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs. :param path_specs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. :param ac_parser: Forced parser type or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` and :func:`multi_load` :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) if anyconfig.utils.is_path_like_object(path_specs, marker): return single_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options) if not anyconfig.utils.is_paths(path_specs, marker): raise ValueError("Possible invalid input %r" % path_specs) return multi_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options)
[ "def", "load", "(", "path_specs", ",", "ac_parser", "=", "None", ",", "ac_dict", "=", "None", ",", "ac_template", "=", "False", ",", "ac_context", "=", "None", ",", "*", "*", "options", ")", ":", "marker", "=", "options", ".", "setdefault", "(", "\"ac_marker\"", ",", "options", ".", "get", "(", "\"marker\"", ",", "'*'", ")", ")", "if", "anyconfig", ".", "utils", ".", "is_path_like_object", "(", "path_specs", ",", "marker", ")", ":", "return", "single_load", "(", "path_specs", ",", "ac_parser", "=", "ac_parser", ",", "ac_dict", "=", "ac_dict", ",", "ac_template", "=", "ac_template", ",", "ac_context", "=", "ac_context", ",", "*", "*", "options", ")", "if", "not", "anyconfig", ".", "utils", ".", "is_paths", "(", "path_specs", ",", "marker", ")", ":", "raise", "ValueError", "(", "\"Possible invalid input %r\"", "%", "path_specs", ")", "return", "multi_load", "(", "path_specs", ",", "ac_parser", "=", "ac_parser", ",", "ac_dict", "=", "ac_dict", ",", "ac_template", "=", "ac_template", ",", "ac_context", "=", "ac_context", ",", "*", "*", "options", ")" ]
r""" Load single or multiple config files or multiple config files specified in given paths pattern or pathlib.Path object represents config files or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs. :param path_specs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. :param ac_parser: Forced parser type or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` and :func:`multi_load` :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
[ "r", "Load", "single", "or", "multiple", "config", "files", "or", "multiple", "config", "files", "specified", "in", "given", "paths", "pattern", "or", "pathlib", ".", "Path", "object", "represents", "config", "files", "or", "a", "namedtuple", "anyconfig", ".", "globals", ".", "IOInfo", "object", "represents", "some", "inputs", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L435-L477
2,767
ssato/python-anyconfig
src/anyconfig/api.py
dump
def dump(data, out, ac_parser=None, **options): """ Save 'data' to 'out'. :param data: A mapping object may have configurations data to dump :param out: An output file path, a file, a file-like object, :class:`pathlib.Path` object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents output to dump some data to. :param ac_parser: Forced parser type or parser object :param options: Backend specific optional arguments, e.g. {"indent": 2} for JSON loader/dumper backend :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ ioi = anyconfig.ioinfo.make(out) psr = find(ioi, forced_type=ac_parser) LOGGER.info("Dumping: %s", ioi.path) psr.dump(data, ioi, **options)
python
def dump(data, out, ac_parser=None, **options): ioi = anyconfig.ioinfo.make(out) psr = find(ioi, forced_type=ac_parser) LOGGER.info("Dumping: %s", ioi.path) psr.dump(data, ioi, **options)
[ "def", "dump", "(", "data", ",", "out", ",", "ac_parser", "=", "None", ",", "*", "*", "options", ")", ":", "ioi", "=", "anyconfig", ".", "ioinfo", ".", "make", "(", "out", ")", "psr", "=", "find", "(", "ioi", ",", "forced_type", "=", "ac_parser", ")", "LOGGER", ".", "info", "(", "\"Dumping: %s\"", ",", "ioi", ".", "path", ")", "psr", ".", "dump", "(", "data", ",", "ioi", ",", "*", "*", "options", ")" ]
Save 'data' to 'out'. :param data: A mapping object may have configurations data to dump :param out: An output file path, a file, a file-like object, :class:`pathlib.Path` object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents output to dump some data to. :param ac_parser: Forced parser type or parser object :param options: Backend specific optional arguments, e.g. {"indent": 2} for JSON loader/dumper backend :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
[ "Save", "data", "to", "out", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L526-L545
2,768
ssato/python-anyconfig
src/anyconfig/api.py
dumps
def dumps(data, ac_parser=None, **options): """ Return string representation of 'data' in forced type format. :param data: Config data object to dump :param ac_parser: Forced parser type or ID or parser object :param options: see :func:`dump` :return: Backend-specific string representation for the given data :raises: ValueError, UnknownProcessorTypeError """ psr = find(None, forced_type=ac_parser) return psr.dumps(data, **options)
python
def dumps(data, ac_parser=None, **options): psr = find(None, forced_type=ac_parser) return psr.dumps(data, **options)
[ "def", "dumps", "(", "data", ",", "ac_parser", "=", "None", ",", "*", "*", "options", ")", ":", "psr", "=", "find", "(", "None", ",", "forced_type", "=", "ac_parser", ")", "return", "psr", ".", "dumps", "(", "data", ",", "*", "*", "options", ")" ]
Return string representation of 'data' in forced type format. :param data: Config data object to dump :param ac_parser: Forced parser type or ID or parser object :param options: see :func:`dump` :return: Backend-specific string representation for the given data :raises: ValueError, UnknownProcessorTypeError
[ "Return", "string", "representation", "of", "data", "in", "forced", "type", "format", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L548-L560
2,769
ssato/python-anyconfig
src/anyconfig/parser.py
parse_single
def parse_single(str_): """ Very simple parser to parse expressions represent some single values. :param str_: a string to parse :return: Int | Bool | String >>> parse_single(None) '' >>> parse_single("0") 0 >>> parse_single("123") 123 >>> parse_single("True") True >>> parse_single("a string") 'a string' >>> parse_single('"a string"') 'a string' >>> parse_single("'a string'") 'a string' >>> parse_single("0.1") '0.1' >>> parse_single(" a string contains extra whitespaces ") 'a string contains extra whitespaces' """ if str_ is None: return '' str_ = str_.strip() if not str_: return '' if BOOL_PATTERN.match(str_) is not None: return bool(str_) if INT_PATTERN.match(str_) is not None: return int(str_) if STR_PATTERN.match(str_) is not None: return str_[1:-1] return str_
python
def parse_single(str_): if str_ is None: return '' str_ = str_.strip() if not str_: return '' if BOOL_PATTERN.match(str_) is not None: return bool(str_) if INT_PATTERN.match(str_) is not None: return int(str_) if STR_PATTERN.match(str_) is not None: return str_[1:-1] return str_
[ "def", "parse_single", "(", "str_", ")", ":", "if", "str_", "is", "None", ":", "return", "''", "str_", "=", "str_", ".", "strip", "(", ")", "if", "not", "str_", ":", "return", "''", "if", "BOOL_PATTERN", ".", "match", "(", "str_", ")", "is", "not", "None", ":", "return", "bool", "(", "str_", ")", "if", "INT_PATTERN", ".", "match", "(", "str_", ")", "is", "not", "None", ":", "return", "int", "(", "str_", ")", "if", "STR_PATTERN", ".", "match", "(", "str_", ")", "is", "not", "None", ":", "return", "str_", "[", "1", ":", "-", "1", "]", "return", "str_" ]
Very simple parser to parse expressions represent some single values. :param str_: a string to parse :return: Int | Bool | String >>> parse_single(None) '' >>> parse_single("0") 0 >>> parse_single("123") 123 >>> parse_single("True") True >>> parse_single("a string") 'a string' >>> parse_single('"a string"') 'a string' >>> parse_single("'a string'") 'a string' >>> parse_single("0.1") '0.1' >>> parse_single(" a string contains extra whitespaces ") 'a string contains extra whitespaces'
[ "Very", "simple", "parser", "to", "parse", "expressions", "represent", "some", "single", "values", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L17-L60
2,770
ssato/python-anyconfig
src/anyconfig/parser.py
parse_list
def parse_list(str_, sep=","): """ Simple parser to parse expressions reprensent some list values. :param str_: a string to parse :param sep: Char to separate items of list :return: [Int | Bool | String] >>> parse_list("") [] >>> parse_list("1") [1] >>> parse_list("a,b") ['a', 'b'] >>> parse_list("1,2") [1, 2] >>> parse_list("a,b,") ['a', 'b'] """ return [parse_single(x) for x in str_.split(sep) if x]
python
def parse_list(str_, sep=","): return [parse_single(x) for x in str_.split(sep) if x]
[ "def", "parse_list", "(", "str_", ",", "sep", "=", "\",\"", ")", ":", "return", "[", "parse_single", "(", "x", ")", "for", "x", "in", "str_", ".", "split", "(", "sep", ")", "if", "x", "]" ]
Simple parser to parse expressions reprensent some list values. :param str_: a string to parse :param sep: Char to separate items of list :return: [Int | Bool | String] >>> parse_list("") [] >>> parse_list("1") [1] >>> parse_list("a,b") ['a', 'b'] >>> parse_list("1,2") [1, 2] >>> parse_list("a,b,") ['a', 'b']
[ "Simple", "parser", "to", "parse", "expressions", "reprensent", "some", "list", "values", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L63-L82
2,771
ssato/python-anyconfig
src/anyconfig/parser.py
attr_val_itr
def attr_val_itr(str_, avs_sep=":", vs_sep=",", as_sep=";"): """ Atrribute and value pair parser. :param str_: String represents a list of pairs of attribute and value :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes """ for rel in parse_list(str_, as_sep): if avs_sep not in rel or rel.endswith(avs_sep): continue (_attr, _values) = parse_list(rel, avs_sep) if vs_sep in str(_values): _values = parse_list(_values, vs_sep) if _values: yield (_attr, _values)
python
def attr_val_itr(str_, avs_sep=":", vs_sep=",", as_sep=";"): for rel in parse_list(str_, as_sep): if avs_sep not in rel or rel.endswith(avs_sep): continue (_attr, _values) = parse_list(rel, avs_sep) if vs_sep in str(_values): _values = parse_list(_values, vs_sep) if _values: yield (_attr, _values)
[ "def", "attr_val_itr", "(", "str_", ",", "avs_sep", "=", "\":\"", ",", "vs_sep", "=", "\",\"", ",", "as_sep", "=", "\";\"", ")", ":", "for", "rel", "in", "parse_list", "(", "str_", ",", "as_sep", ")", ":", "if", "avs_sep", "not", "in", "rel", "or", "rel", ".", "endswith", "(", "avs_sep", ")", ":", "continue", "(", "_attr", ",", "_values", ")", "=", "parse_list", "(", "rel", ",", "avs_sep", ")", "if", "vs_sep", "in", "str", "(", "_values", ")", ":", "_values", "=", "parse_list", "(", "_values", ",", "vs_sep", ")", "if", "_values", ":", "yield", "(", "_attr", ",", "_values", ")" ]
Atrribute and value pair parser. :param str_: String represents a list of pairs of attribute and value :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes
[ "Atrribute", "and", "value", "pair", "parser", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L85-L104
2,772
ssato/python-anyconfig
src/anyconfig/cli.py
_exit_with_output
def _exit_with_output(content, exit_code=0): """ Exit the program with printing out messages. :param content: content to print out :param exit_code: Exit code """ (sys.stdout if exit_code == 0 else sys.stderr).write(content + os.linesep) sys.exit(exit_code)
python
def _exit_with_output(content, exit_code=0): (sys.stdout if exit_code == 0 else sys.stderr).write(content + os.linesep) sys.exit(exit_code)
[ "def", "_exit_with_output", "(", "content", ",", "exit_code", "=", "0", ")", ":", "(", "sys", ".", "stdout", "if", "exit_code", "==", "0", "else", "sys", ".", "stderr", ")", ".", "write", "(", "content", "+", "os", ".", "linesep", ")", "sys", ".", "exit", "(", "exit_code", ")" ]
Exit the program with printing out messages. :param content: content to print out :param exit_code: Exit code
[ "Exit", "the", "program", "with", "printing", "out", "messages", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L190-L198
2,773
ssato/python-anyconfig
src/anyconfig/cli.py
_show_psrs
def _show_psrs(): """Show list of info of parsers available """ sep = os.linesep types = "Supported types: " + ", ".join(API.list_types()) cids = "IDs: " + ", ".join(c for c, _ps in API.list_by_cid()) x_vs_ps = [" %s: %s" % (x, ", ".join(p.cid() for p in ps)) for x, ps in API.list_by_extension()] exts = "File extensions:" + sep + sep.join(x_vs_ps) _exit_with_output(sep.join([types, exts, cids]))
python
def _show_psrs(): sep = os.linesep types = "Supported types: " + ", ".join(API.list_types()) cids = "IDs: " + ", ".join(c for c, _ps in API.list_by_cid()) x_vs_ps = [" %s: %s" % (x, ", ".join(p.cid() for p in ps)) for x, ps in API.list_by_extension()] exts = "File extensions:" + sep + sep.join(x_vs_ps) _exit_with_output(sep.join([types, exts, cids]))
[ "def", "_show_psrs", "(", ")", ":", "sep", "=", "os", ".", "linesep", "types", "=", "\"Supported types: \"", "+", "\", \"", ".", "join", "(", "API", ".", "list_types", "(", ")", ")", "cids", "=", "\"IDs: \"", "+", "\", \"", ".", "join", "(", "c", "for", "c", ",", "_ps", "in", "API", ".", "list_by_cid", "(", ")", ")", "x_vs_ps", "=", "[", "\" %s: %s\"", "%", "(", "x", ",", "\", \"", ".", "join", "(", "p", ".", "cid", "(", ")", "for", "p", "in", "ps", ")", ")", "for", "x", ",", "ps", "in", "API", ".", "list_by_extension", "(", ")", "]", "exts", "=", "\"File extensions:\"", "+", "sep", "+", "sep", ".", "join", "(", "x_vs_ps", ")", "_exit_with_output", "(", "sep", ".", "join", "(", "[", "types", ",", "exts", ",", "cids", "]", ")", ")" ]
Show list of info of parsers available
[ "Show", "list", "of", "info", "of", "parsers", "available" ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L201-L213
2,774
ssato/python-anyconfig
src/anyconfig/cli.py
_parse_args
def _parse_args(argv): """ Show supported config format types or usage. :param argv: Argument list to parse or None (sys.argv will be set). :return: argparse.Namespace object or None (exit before return) """ parser = make_parser() args = parser.parse_args(argv) LOGGER.setLevel(to_log_level(args.loglevel)) if args.inputs: if '-' in args.inputs: args.inputs = sys.stdin else: if args.list: _show_psrs() elif args.env: cnf = os.environ.copy() _output_result(cnf, args.output, args.otype or "json", None, None) sys.exit(0) else: parser.print_usage() sys.exit(1) if args.validate and args.schema is None: _exit_with_output("--validate option requires --scheme option", 1) return args
python
def _parse_args(argv): parser = make_parser() args = parser.parse_args(argv) LOGGER.setLevel(to_log_level(args.loglevel)) if args.inputs: if '-' in args.inputs: args.inputs = sys.stdin else: if args.list: _show_psrs() elif args.env: cnf = os.environ.copy() _output_result(cnf, args.output, args.otype or "json", None, None) sys.exit(0) else: parser.print_usage() sys.exit(1) if args.validate and args.schema is None: _exit_with_output("--validate option requires --scheme option", 1) return args
[ "def", "_parse_args", "(", "argv", ")", ":", "parser", "=", "make_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "LOGGER", ".", "setLevel", "(", "to_log_level", "(", "args", ".", "loglevel", ")", ")", "if", "args", ".", "inputs", ":", "if", "'-'", "in", "args", ".", "inputs", ":", "args", ".", "inputs", "=", "sys", ".", "stdin", "else", ":", "if", "args", ".", "list", ":", "_show_psrs", "(", ")", "elif", "args", ".", "env", ":", "cnf", "=", "os", ".", "environ", ".", "copy", "(", ")", "_output_result", "(", "cnf", ",", "args", ".", "output", ",", "args", ".", "otype", "or", "\"json\"", ",", "None", ",", "None", ")", "sys", ".", "exit", "(", "0", ")", "else", ":", "parser", ".", "print_usage", "(", ")", "sys", ".", "exit", "(", "1", ")", "if", "args", ".", "validate", "and", "args", ".", "schema", "is", "None", ":", "_exit_with_output", "(", "\"--validate option requires --scheme option\"", ",", "1", ")", "return", "args" ]
Show supported config format types or usage. :param argv: Argument list to parse or None (sys.argv will be set). :return: argparse.Namespace object or None (exit before return)
[ "Show", "supported", "config", "format", "types", "or", "usage", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L216-L244
2,775
ssato/python-anyconfig
src/anyconfig/schema.py
validate
def validate(data, schema, ac_schema_safe=True, ac_schema_errors=False, **options): """ Validate target object with given schema object, loaded from JSON schema. See also: https://python-jsonschema.readthedocs.org/en/latest/validate/ :parae data: Target object (a dict or a dict-like object) to validate :param schema: Schema object (a dict or a dict-like object) instantiated from schema JSON file or schema JSON string :param options: Other keyword options such as: - ac_schema_safe: Exception (jsonschema.ValidationError or jsonschema.SchemaError or others) will be thrown during validation process due to any validation or related errors. However, these will be catched by default, and will be re-raised if 'ac_safe' is False. - ac_schema_errors: Lazily yield each of the validation errors and returns all of them if validation fails. :return: (True if validation succeeded else False, error message[s]) """ if not JSONSCHEMA_IS_AVAIL: return (True, _NA_MSG) options = anyconfig.utils.filter_options(("cls", ), options) if ac_schema_errors: return _validate_all(data, schema, **options) return _validate(data, schema, ac_schema_safe, **options)
python
def validate(data, schema, ac_schema_safe=True, ac_schema_errors=False, **options): if not JSONSCHEMA_IS_AVAIL: return (True, _NA_MSG) options = anyconfig.utils.filter_options(("cls", ), options) if ac_schema_errors: return _validate_all(data, schema, **options) return _validate(data, schema, ac_schema_safe, **options)
[ "def", "validate", "(", "data", ",", "schema", ",", "ac_schema_safe", "=", "True", ",", "ac_schema_errors", "=", "False", ",", "*", "*", "options", ")", ":", "if", "not", "JSONSCHEMA_IS_AVAIL", ":", "return", "(", "True", ",", "_NA_MSG", ")", "options", "=", "anyconfig", ".", "utils", ".", "filter_options", "(", "(", "\"cls\"", ",", ")", ",", "options", ")", "if", "ac_schema_errors", ":", "return", "_validate_all", "(", "data", ",", "schema", ",", "*", "*", "options", ")", "return", "_validate", "(", "data", ",", "schema", ",", "ac_schema_safe", ",", "*", "*", "options", ")" ]
Validate target object with given schema object, loaded from JSON schema. See also: https://python-jsonschema.readthedocs.org/en/latest/validate/ :parae data: Target object (a dict or a dict-like object) to validate :param schema: Schema object (a dict or a dict-like object) instantiated from schema JSON file or schema JSON string :param options: Other keyword options such as: - ac_schema_safe: Exception (jsonschema.ValidationError or jsonschema.SchemaError or others) will be thrown during validation process due to any validation or related errors. However, these will be catched by default, and will be re-raised if 'ac_safe' is False. - ac_schema_errors: Lazily yield each of the validation errors and returns all of them if validation fails. :return: (True if validation succeeded else False, error message[s])
[ "Validate", "target", "object", "with", "given", "schema", "object", "loaded", "from", "JSON", "schema", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L84-L113
2,776
ssato/python-anyconfig
src/anyconfig/schema.py
array_to_schema
def array_to_schema(arr, **options): """ Generate a JSON schema object with type annotation added for given object. :param arr: Array of mapping objects like dicts :param options: Other keyword options such as: - ac_schema_strict: True if more strict (precise) schema is needed - ac_schema_typemap: Type to JSON schema type mappings :return: Another mapping objects represents JSON schema of items """ (typemap, strict) = _process_options(**options) arr = list(arr) scm = dict(type=typemap[list], items=gen_schema(arr[0] if arr else "str", **options)) if strict: nitems = len(arr) scm["minItems"] = nitems scm["uniqueItems"] = len(set(arr)) == nitems return scm
python
def array_to_schema(arr, **options): (typemap, strict) = _process_options(**options) arr = list(arr) scm = dict(type=typemap[list], items=gen_schema(arr[0] if arr else "str", **options)) if strict: nitems = len(arr) scm["minItems"] = nitems scm["uniqueItems"] = len(set(arr)) == nitems return scm
[ "def", "array_to_schema", "(", "arr", ",", "*", "*", "options", ")", ":", "(", "typemap", ",", "strict", ")", "=", "_process_options", "(", "*", "*", "options", ")", "arr", "=", "list", "(", "arr", ")", "scm", "=", "dict", "(", "type", "=", "typemap", "[", "list", "]", ",", "items", "=", "gen_schema", "(", "arr", "[", "0", "]", "if", "arr", "else", "\"str\"", ",", "*", "*", "options", ")", ")", "if", "strict", ":", "nitems", "=", "len", "(", "arr", ")", "scm", "[", "\"minItems\"", "]", "=", "nitems", "scm", "[", "\"uniqueItems\"", "]", "=", "len", "(", "set", "(", "arr", ")", ")", "==", "nitems", "return", "scm" ]
Generate a JSON schema object with type annotation added for given object. :param arr: Array of mapping objects like dicts :param options: Other keyword options such as: - ac_schema_strict: True if more strict (precise) schema is needed - ac_schema_typemap: Type to JSON schema type mappings :return: Another mapping objects represents JSON schema of items
[ "Generate", "a", "JSON", "schema", "object", "with", "type", "annotation", "added", "for", "given", "object", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L126-L148
2,777
ssato/python-anyconfig
src/anyconfig/backend/base.py
ensure_outdir_exists
def ensure_outdir_exists(filepath): """ Make dir to dump 'filepath' if that dir does not exist. :param filepath: path of file to dump """ outdir = os.path.dirname(filepath) if outdir and not os.path.exists(outdir): LOGGER.debug("Making output dir: %s", outdir) os.makedirs(outdir)
python
def ensure_outdir_exists(filepath): outdir = os.path.dirname(filepath) if outdir and not os.path.exists(outdir): LOGGER.debug("Making output dir: %s", outdir) os.makedirs(outdir)
[ "def", "ensure_outdir_exists", "(", "filepath", ")", ":", "outdir", "=", "os", ".", "path", ".", "dirname", "(", "filepath", ")", "if", "outdir", "and", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "LOGGER", ".", "debug", "(", "\"Making output dir: %s\"", ",", "outdir", ")", "os", ".", "makedirs", "(", "outdir", ")" ]
Make dir to dump 'filepath' if that dir does not exist. :param filepath: path of file to dump
[ "Make", "dir", "to", "dump", "filepath", "if", "that", "dir", "does", "not", "exist", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L63-L73
2,778
ssato/python-anyconfig
src/anyconfig/backend/base.py
load_with_fn
def load_with_fn(load_fn, content_or_strm, container, allow_primitives=False, **options): """ Load data from given string or stream 'content_or_strm'. :param load_fn: Callable to load data :param content_or_strm: data content or stream provides it :param container: callble to make a container object :param allow_primitives: True if the parser.load* may return objects of primitive data types other than mapping types such like JSON parser :param options: keyword options passed to 'load_fn' :return: container object holding data """ ret = load_fn(content_or_strm, **options) if anyconfig.utils.is_dict_like(ret): return container() if (ret is None or not ret) else container(ret) return ret if allow_primitives else container(ret)
python
def load_with_fn(load_fn, content_or_strm, container, allow_primitives=False, **options): ret = load_fn(content_or_strm, **options) if anyconfig.utils.is_dict_like(ret): return container() if (ret is None or not ret) else container(ret) return ret if allow_primitives else container(ret)
[ "def", "load_with_fn", "(", "load_fn", ",", "content_or_strm", ",", "container", ",", "allow_primitives", "=", "False", ",", "*", "*", "options", ")", ":", "ret", "=", "load_fn", "(", "content_or_strm", ",", "*", "*", "options", ")", "if", "anyconfig", ".", "utils", ".", "is_dict_like", "(", "ret", ")", ":", "return", "container", "(", ")", "if", "(", "ret", "is", "None", "or", "not", "ret", ")", "else", "container", "(", "ret", ")", "return", "ret", "if", "allow_primitives", "else", "container", "(", "ret", ")" ]
Load data from given string or stream 'content_or_strm'. :param load_fn: Callable to load data :param content_or_strm: data content or stream provides it :param container: callble to make a container object :param allow_primitives: True if the parser.load* may return objects of primitive data types other than mapping types such like JSON parser :param options: keyword options passed to 'load_fn' :return: container object holding data
[ "Load", "data", "from", "given", "string", "or", "stream", "content_or_strm", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L555-L574
2,779
ssato/python-anyconfig
src/anyconfig/backend/base.py
dump_with_fn
def dump_with_fn(dump_fn, data, stream, **options): """ Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or file-like object 'stream'. :param dump_fn: Callable to dump data :param data: Data to dump :param stream: File or file like object or None :param options: optional keyword parameters :return: String represents data if stream is None or None """ if stream is None: return dump_fn(data, **options) return dump_fn(data, stream, **options)
python
def dump_with_fn(dump_fn, data, stream, **options): if stream is None: return dump_fn(data, **options) return dump_fn(data, stream, **options)
[ "def", "dump_with_fn", "(", "dump_fn", ",", "data", ",", "stream", ",", "*", "*", "options", ")", ":", "if", "stream", "is", "None", ":", "return", "dump_fn", "(", "data", ",", "*", "*", "options", ")", "return", "dump_fn", "(", "data", ",", "stream", ",", "*", "*", "options", ")" ]
Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or file-like object 'stream'. :param dump_fn: Callable to dump data :param data: Data to dump :param stream: File or file like object or None :param options: optional keyword parameters :return: String represents data if stream is None or None
[ "Dump", "data", "to", "a", "string", "if", "stream", "is", "None", "or", "dump", "data", "to", "a", "file", "or", "file", "-", "like", "object", "stream", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L577-L592
2,780
ssato/python-anyconfig
src/anyconfig/backend/base.py
LoaderMixin._container_factory
def _container_factory(self, **options): """ The order of prirorities are ac_dict, backend specific dict class option, ac_ordered. :param options: Keyword options may contain 'ac_ordered'. :return: Factory (class or function) to make an container. """ ac_dict = options.get("ac_dict", False) _dicts = [x for x in (options.get(o) for o in self.dict_options()) if x] if self.dict_options() and ac_dict and callable(ac_dict): return ac_dict # Higher priority than ac_ordered. if _dicts and callable(_dicts[0]): return _dicts[0] if self.ordered() and options.get("ac_ordered", False): return anyconfig.compat.OrderedDict return dict
python
def _container_factory(self, **options): ac_dict = options.get("ac_dict", False) _dicts = [x for x in (options.get(o) for o in self.dict_options()) if x] if self.dict_options() and ac_dict and callable(ac_dict): return ac_dict # Higher priority than ac_ordered. if _dicts and callable(_dicts[0]): return _dicts[0] if self.ordered() and options.get("ac_ordered", False): return anyconfig.compat.OrderedDict return dict
[ "def", "_container_factory", "(", "self", ",", "*", "*", "options", ")", ":", "ac_dict", "=", "options", ".", "get", "(", "\"ac_dict\"", ",", "False", ")", "_dicts", "=", "[", "x", "for", "x", "in", "(", "options", ".", "get", "(", "o", ")", "for", "o", "in", "self", ".", "dict_options", "(", ")", ")", "if", "x", "]", "if", "self", ".", "dict_options", "(", ")", "and", "ac_dict", "and", "callable", "(", "ac_dict", ")", ":", "return", "ac_dict", "# Higher priority than ac_ordered.", "if", "_dicts", "and", "callable", "(", "_dicts", "[", "0", "]", ")", ":", "return", "_dicts", "[", "0", "]", "if", "self", ".", "ordered", "(", ")", "and", "options", ".", "get", "(", "\"ac_ordered\"", ",", "False", ")", ":", "return", "anyconfig", ".", "compat", ".", "OrderedDict", "return", "dict" ]
The order of prirorities are ac_dict, backend specific dict class option, ac_ordered. :param options: Keyword options may contain 'ac_ordered'. :return: Factory (class or function) to make an container.
[ "The", "order", "of", "prirorities", "are", "ac_dict", "backend", "specific", "dict", "class", "option", "ac_ordered", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L175-L194
2,781
ssato/python-anyconfig
src/anyconfig/backend/base.py
LoaderMixin._load_options
def _load_options(self, container, **options): """ Select backend specific loading options. """ # Force set dict option if available in backend. For example, # options["object_hook"] will be OrderedDict if 'container' was # OrderedDict in JSON backend. for opt in self.dict_options(): options.setdefault(opt, container) return anyconfig.utils.filter_options(self._load_opts, options)
python
def _load_options(self, container, **options): # Force set dict option if available in backend. For example, # options["object_hook"] will be OrderedDict if 'container' was # OrderedDict in JSON backend. for opt in self.dict_options(): options.setdefault(opt, container) return anyconfig.utils.filter_options(self._load_opts, options)
[ "def", "_load_options", "(", "self", ",", "container", ",", "*", "*", "options", ")", ":", "# Force set dict option if available in backend. For example,", "# options[\"object_hook\"] will be OrderedDict if 'container' was", "# OrderedDict in JSON backend.", "for", "opt", "in", "self", ".", "dict_options", "(", ")", ":", "options", ".", "setdefault", "(", "opt", ",", "container", ")", "return", "anyconfig", ".", "utils", ".", "filter_options", "(", "self", ".", "_load_opts", ",", "options", ")" ]
Select backend specific loading options.
[ "Select", "backend", "specific", "loading", "options", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L196-L206
2,782
ssato/python-anyconfig
src/anyconfig/backend/base.py
LoaderMixin.load_from_string
def load_from_string(self, content, container, **kwargs): """ Load config from given string 'content'. :param content: Config content string :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters """ _not_implemented(self, content, container, **kwargs)
python
def load_from_string(self, content, container, **kwargs): _not_implemented(self, content, container, **kwargs)
[ "def", "load_from_string", "(", "self", ",", "content", ",", "container", ",", "*", "*", "kwargs", ")", ":", "_not_implemented", "(", "self", ",", "content", ",", "container", ",", "*", "*", "kwargs", ")" ]
Load config from given string 'content'. :param content: Config content string :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
[ "Load", "config", "from", "given", "string", "content", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L208-L218
2,783
ssato/python-anyconfig
src/anyconfig/backend/base.py
LoaderMixin.load_from_stream
def load_from_stream(self, stream, container, **kwargs): """ Load config from given file like object 'stream`. :param stream: Config file or file like object :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters """ _not_implemented(self, stream, container, **kwargs)
python
def load_from_stream(self, stream, container, **kwargs): _not_implemented(self, stream, container, **kwargs)
[ "def", "load_from_stream", "(", "self", ",", "stream", ",", "container", ",", "*", "*", "kwargs", ")", ":", "_not_implemented", "(", "self", ",", "stream", ",", "container", ",", "*", "*", "kwargs", ")" ]
Load config from given file like object 'stream`. :param stream: Config file or file like object :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
[ "Load", "config", "from", "given", "file", "like", "object", "stream", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L232-L242
2,784
ssato/python-anyconfig
src/anyconfig/backend/base.py
LoaderMixin.loads
def loads(self, content, **options): """ Load config from given string 'content' after some checks. :param content: Config file content :param options: options will be passed to backend specific loading functions. please note that options have to be sanitized w/ :func:`anyconfig.utils.filter_options` later to filter out options not in _load_opts. :return: dict or dict-like object holding configurations """ container = self._container_factory(**options) if not content or content is None: return container() options = self._load_options(container, **options) return self.load_from_string(content, container, **options)
python
def loads(self, content, **options): container = self._container_factory(**options) if not content or content is None: return container() options = self._load_options(container, **options) return self.load_from_string(content, container, **options)
[ "def", "loads", "(", "self", ",", "content", ",", "*", "*", "options", ")", ":", "container", "=", "self", ".", "_container_factory", "(", "*", "*", "options", ")", "if", "not", "content", "or", "content", "is", "None", ":", "return", "container", "(", ")", "options", "=", "self", ".", "_load_options", "(", "container", ",", "*", "*", "options", ")", "return", "self", ".", "load_from_string", "(", "content", ",", "container", ",", "*", "*", "options", ")" ]
Load config from given string 'content' after some checks. :param content: Config file content :param options: options will be passed to backend specific loading functions. please note that options have to be sanitized w/ :func:`anyconfig.utils.filter_options` later to filter out options not in _load_opts. :return: dict or dict-like object holding configurations
[ "Load", "config", "from", "given", "string", "content", "after", "some", "checks", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L244-L262
2,785
ssato/python-anyconfig
src/anyconfig/backend/base.py
DumperMixin.dump
def dump(self, cnf, ioi, **kwargs): """ Dump config 'cnf' to output object of which 'ioi' refering. :param cnf: Configuration data to dump :param ioi: an 'anyconfig.globals.IOInfo' namedtuple object provides various info of input object to load data from :param kwargs: optional keyword parameters to be sanitized :: dict :raises IOError, OSError, AttributeError: When dump failed. """ kwargs = anyconfig.utils.filter_options(self._dump_opts, kwargs) if anyconfig.utils.is_stream_ioinfo(ioi): self.dump_to_stream(cnf, ioi.src, **kwargs) else: ensure_outdir_exists(ioi.path) self.dump_to_path(cnf, ioi.path, **kwargs)
python
def dump(self, cnf, ioi, **kwargs): kwargs = anyconfig.utils.filter_options(self._dump_opts, kwargs) if anyconfig.utils.is_stream_ioinfo(ioi): self.dump_to_stream(cnf, ioi.src, **kwargs) else: ensure_outdir_exists(ioi.path) self.dump_to_path(cnf, ioi.path, **kwargs)
[ "def", "dump", "(", "self", ",", "cnf", ",", "ioi", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "anyconfig", ".", "utils", ".", "filter_options", "(", "self", ".", "_dump_opts", ",", "kwargs", ")", "if", "anyconfig", ".", "utils", ".", "is_stream_ioinfo", "(", "ioi", ")", ":", "self", ".", "dump_to_stream", "(", "cnf", ",", "ioi", ".", "src", ",", "*", "*", "kwargs", ")", "else", ":", "ensure_outdir_exists", "(", "ioi", ".", "path", ")", "self", ".", "dump_to_path", "(", "cnf", ",", "ioi", ".", "path", ",", "*", "*", "kwargs", ")" ]
Dump config 'cnf' to output object of which 'ioi' refering. :param cnf: Configuration data to dump :param ioi: an 'anyconfig.globals.IOInfo' namedtuple object provides various info of input object to load data from :param kwargs: optional keyword parameters to be sanitized :: dict :raises IOError, OSError, AttributeError: When dump failed.
[ "Dump", "config", "cnf", "to", "output", "object", "of", "which", "ioi", "refering", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L362-L380
2,786
ssato/python-anyconfig
src/anyconfig/backend/base.py
FromStringLoaderMixin.load_from_stream
def load_from_stream(self, stream, container, **kwargs): """ Load config from given stream 'stream'. :param stream: Config file or file-like object :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters """ return self.load_from_string(stream.read(), container, **kwargs)
python
def load_from_stream(self, stream, container, **kwargs): return self.load_from_string(stream.read(), container, **kwargs)
[ "def", "load_from_stream", "(", "self", ",", "stream", ",", "container", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "load_from_string", "(", "stream", ".", "read", "(", ")", ",", "container", ",", "*", "*", "kwargs", ")" ]
Load config from given stream 'stream'. :param stream: Config file or file-like object :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
[ "Load", "config", "from", "given", "stream", "stream", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L407-L417
2,787
ssato/python-anyconfig
src/anyconfig/backend/base.py
FromStreamLoaderMixin.load_from_string
def load_from_string(self, content, container, **kwargs): """ Load config from given string 'cnf_content'. :param content: Config content string :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters """ return self.load_from_stream(anyconfig.compat.StringIO(content), container, **kwargs)
python
def load_from_string(self, content, container, **kwargs): return self.load_from_stream(anyconfig.compat.StringIO(content), container, **kwargs)
[ "def", "load_from_string", "(", "self", ",", "content", ",", "container", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "load_from_stream", "(", "anyconfig", ".", "compat", ".", "StringIO", "(", "content", ")", ",", "container", ",", "*", "*", "kwargs", ")" ]
Load config from given string 'cnf_content'. :param content: Config content string :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
[ "Load", "config", "from", "given", "string", "cnf_content", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L441-L452
2,788
ssato/python-anyconfig
src/anyconfig/backend/base.py
StringStreamFnParser.load_from_string
def load_from_string(self, content, container, **options): """ Load configuration data from given string 'content'. :param content: Configuration string :param container: callble to make a container object :param options: keyword options passed to '_load_from_string_fn' :return: container object holding the configuration data """ return load_with_fn(self._load_from_string_fn, content, container, allow_primitives=self.allow_primitives(), **options)
python
def load_from_string(self, content, container, **options): return load_with_fn(self._load_from_string_fn, content, container, allow_primitives=self.allow_primitives(), **options)
[ "def", "load_from_string", "(", "self", ",", "content", ",", "container", ",", "*", "*", "options", ")", ":", "return", "load_with_fn", "(", "self", ".", "_load_from_string_fn", ",", "content", ",", "container", ",", "allow_primitives", "=", "self", ".", "allow_primitives", "(", ")", ",", "*", "*", "options", ")" ]
Load configuration data from given string 'content'. :param content: Configuration string :param container: callble to make a container object :param options: keyword options passed to '_load_from_string_fn' :return: container object holding the configuration data
[ "Load", "configuration", "data", "from", "given", "string", "content", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L618-L630
2,789
ssato/python-anyconfig
src/anyconfig/backend/base.py
StringStreamFnParser.load_from_stream
def load_from_stream(self, stream, container, **options): """ Load data from given stream 'stream'. :param stream: Stream provides configuration data :param container: callble to make a container object :param options: keyword options passed to '_load_from_stream_fn' :return: container object holding the configuration data """ return load_with_fn(self._load_from_stream_fn, stream, container, allow_primitives=self.allow_primitives(), **options)
python
def load_from_stream(self, stream, container, **options): return load_with_fn(self._load_from_stream_fn, stream, container, allow_primitives=self.allow_primitives(), **options)
[ "def", "load_from_stream", "(", "self", ",", "stream", ",", "container", ",", "*", "*", "options", ")", ":", "return", "load_with_fn", "(", "self", ".", "_load_from_stream_fn", ",", "stream", ",", "container", ",", "allow_primitives", "=", "self", ".", "allow_primitives", "(", ")", ",", "*", "*", "options", ")" ]
Load data from given stream 'stream'. :param stream: Stream provides configuration data :param container: callble to make a container object :param options: keyword options passed to '_load_from_stream_fn' :return: container object holding the configuration data
[ "Load", "data", "from", "given", "stream", "stream", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L632-L644
2,790
ssato/python-anyconfig
src/anyconfig/ioinfo.py
guess_io_type
def guess_io_type(obj): """Guess input or output type of 'obj'. :param obj: a path string, a pathlib.Path or a file / file-like object :return: IOInfo type defined in anyconfig.globals.IOI_TYPES >>> apath = "/path/to/a_conf.ext" >>> assert guess_io_type(apath) == IOI_PATH_STR >>> from anyconfig.compat import pathlib >>> if pathlib is not None: ... assert guess_io_type(pathlib.Path(apath)) == IOI_PATH_OBJ >>> assert guess_io_type(open(__file__)) == IOI_STREAM >>> guess_io_type(1) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ... """ if obj is None: return IOI_NONE if anyconfig.utils.is_path(obj): return IOI_PATH_STR if anyconfig.utils.is_path_obj(obj): return IOI_PATH_OBJ if anyconfig.utils.is_file_stream(obj): return IOI_STREAM raise ValueError("Unknown I/O type object: %r" % obj)
python
def guess_io_type(obj): if obj is None: return IOI_NONE if anyconfig.utils.is_path(obj): return IOI_PATH_STR if anyconfig.utils.is_path_obj(obj): return IOI_PATH_OBJ if anyconfig.utils.is_file_stream(obj): return IOI_STREAM raise ValueError("Unknown I/O type object: %r" % obj)
[ "def", "guess_io_type", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "IOI_NONE", "if", "anyconfig", ".", "utils", ".", "is_path", "(", "obj", ")", ":", "return", "IOI_PATH_STR", "if", "anyconfig", ".", "utils", ".", "is_path_obj", "(", "obj", ")", ":", "return", "IOI_PATH_OBJ", "if", "anyconfig", ".", "utils", ".", "is_file_stream", "(", "obj", ")", ":", "return", "IOI_STREAM", "raise", "ValueError", "(", "\"Unknown I/O type object: %r\"", "%", "obj", ")" ]
Guess input or output type of 'obj'. :param obj: a path string, a pathlib.Path or a file / file-like object :return: IOInfo type defined in anyconfig.globals.IOI_TYPES >>> apath = "/path/to/a_conf.ext" >>> assert guess_io_type(apath) == IOI_PATH_STR >>> from anyconfig.compat import pathlib >>> if pathlib is not None: ... assert guess_io_type(pathlib.Path(apath)) == IOI_PATH_OBJ >>> assert guess_io_type(open(__file__)) == IOI_STREAM >>> guess_io_type(1) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...
[ "Guess", "input", "or", "output", "type", "of", "obj", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/ioinfo.py#L23-L50
2,791
ssato/python-anyconfig
src/anyconfig/backend/shellvars.py
_parseline
def _parseline(line): """ Parse a line contains shell variable definition. :param line: A string to parse, must not start with '#' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline("aaa=") ('aaa', '') >>> _parseline("aaa=bbb") ('aaa', 'bbb') >>> _parseline("aaa='bb b'") ('aaa', 'bb b') >>> _parseline('aaa="bb#b"') ('aaa', 'bb#b') >>> _parseline('aaa="bb\\"b"') ('aaa', 'bb"b') >>> _parseline("aaa=bbb # ccc") ('aaa', 'bbb') """ match = re.match(r"^\s*(export)?\s*(\S+)=(?:(?:" r"(?:\"(.*[^\\])\")|(?:'(.*[^\\])')|" r"(?:([^\"'#\s]+)))?)\s*#*", line) if not match: LOGGER.warning("Invalid line found: %s", line) return (None, None) tpl = match.groups() vals = list(itertools.dropwhile(lambda x: x is None, tpl[2:])) return (tpl[1], vals[0] if vals else '')
python
def _parseline(line): match = re.match(r"^\s*(export)?\s*(\S+)=(?:(?:" r"(?:\"(.*[^\\])\")|(?:'(.*[^\\])')|" r"(?:([^\"'#\s]+)))?)\s*#*", line) if not match: LOGGER.warning("Invalid line found: %s", line) return (None, None) tpl = match.groups() vals = list(itertools.dropwhile(lambda x: x is None, tpl[2:])) return (tpl[1], vals[0] if vals else '')
[ "def", "_parseline", "(", "line", ")", ":", "match", "=", "re", ".", "match", "(", "r\"^\\s*(export)?\\s*(\\S+)=(?:(?:\"", "r\"(?:\\\"(.*[^\\\\])\\\")|(?:'(.*[^\\\\])')|\"", "r\"(?:([^\\\"'#\\s]+)))?)\\s*#*\"", ",", "line", ")", "if", "not", "match", ":", "LOGGER", ".", "warning", "(", "\"Invalid line found: %s\"", ",", "line", ")", "return", "(", "None", ",", "None", ")", "tpl", "=", "match", ".", "groups", "(", ")", "vals", "=", "list", "(", "itertools", ".", "dropwhile", "(", "lambda", "x", ":", "x", "is", "None", ",", "tpl", "[", "2", ":", "]", ")", ")", "return", "(", "tpl", "[", "1", "]", ",", "vals", "[", "0", "]", "if", "vals", "else", "''", ")" ]
Parse a line contains shell variable definition. :param line: A string to parse, must not start with '#' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline("aaa=") ('aaa', '') >>> _parseline("aaa=bbb") ('aaa', 'bbb') >>> _parseline("aaa='bb b'") ('aaa', 'bb b') >>> _parseline('aaa="bb#b"') ('aaa', 'bb#b') >>> _parseline('aaa="bb\\"b"') ('aaa', 'bb"b') >>> _parseline("aaa=bbb # ccc") ('aaa', 'bbb')
[ "Parse", "a", "line", "contains", "shell", "variable", "definition", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/shellvars.py#L35-L64
2,792
ssato/python-anyconfig
src/anyconfig/backend/shellvars.py
load
def load(stream, container=dict): """ Load and parse a file or file-like object 'stream' provides simple shell variables' definitions. :param stream: A file or file like object :param container: Factory function to create a dict-like object to store properties :return: Dict-like object holding shell variables' definitions >>> from anyconfig.compat import StringIO as to_strm >>> load(to_strm('')) {} >>> load(to_strm("# ")) {} >>> load(to_strm("aaa=")) {'aaa': ''} >>> load(to_strm("aaa=bbb")) {'aaa': 'bbb'} >>> load(to_strm("aaa=bbb # ...")) {'aaa': 'bbb'} """ ret = container() for line in stream.readlines(): line = line.rstrip() if line is None or not line: continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Empty val in the line: %s", line) continue ret[key] = val return ret
python
def load(stream, container=dict): ret = container() for line in stream.readlines(): line = line.rstrip() if line is None or not line: continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Empty val in the line: %s", line) continue ret[key] = val return ret
[ "def", "load", "(", "stream", ",", "container", "=", "dict", ")", ":", "ret", "=", "container", "(", ")", "for", "line", "in", "stream", ".", "readlines", "(", ")", ":", "line", "=", "line", ".", "rstrip", "(", ")", "if", "line", "is", "None", "or", "not", "line", ":", "continue", "(", "key", ",", "val", ")", "=", "_parseline", "(", "line", ")", "if", "key", "is", "None", ":", "LOGGER", ".", "warning", "(", "\"Empty val in the line: %s\"", ",", "line", ")", "continue", "ret", "[", "key", "]", "=", "val", "return", "ret" ]
Load and parse a file or file-like object 'stream' provides simple shell variables' definitions. :param stream: A file or file like object :param container: Factory function to create a dict-like object to store properties :return: Dict-like object holding shell variables' definitions >>> from anyconfig.compat import StringIO as to_strm >>> load(to_strm('')) {} >>> load(to_strm("# ")) {} >>> load(to_strm("aaa=")) {'aaa': ''} >>> load(to_strm("aaa=bbb")) {'aaa': 'bbb'} >>> load(to_strm("aaa=bbb # ...")) {'aaa': 'bbb'}
[ "Load", "and", "parse", "a", "file", "or", "file", "-", "like", "object", "stream", "provides", "simple", "shell", "variables", "definitions", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/shellvars.py#L67-L103
2,793
ssato/python-anyconfig
src/anyconfig/backend/shellvars.py
Parser.dump_to_stream
def dump_to_stream(self, cnf, stream, **kwargs): """ Dump config 'cnf' to a file or file-like object 'stream'. :param cnf: Shell variables data to dump :param stream: Shell script file or file like object :param kwargs: backend-specific optional keyword parameters :: dict """ for key, val in anyconfig.compat.iteritems(cnf): stream.write("%s='%s'%s" % (key, val, os.linesep))
python
def dump_to_stream(self, cnf, stream, **kwargs): for key, val in anyconfig.compat.iteritems(cnf): stream.write("%s='%s'%s" % (key, val, os.linesep))
[ "def", "dump_to_stream", "(", "self", ",", "cnf", ",", "stream", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "val", "in", "anyconfig", ".", "compat", ".", "iteritems", "(", "cnf", ")", ":", "stream", ".", "write", "(", "\"%s='%s'%s\"", "%", "(", "key", ",", "val", ",", "os", ".", "linesep", ")", ")" ]
Dump config 'cnf' to a file or file-like object 'stream'. :param cnf: Shell variables data to dump :param stream: Shell script file or file like object :param kwargs: backend-specific optional keyword parameters :: dict
[ "Dump", "config", "cnf", "to", "a", "file", "or", "file", "-", "like", "object", "stream", "." ]
f2f4fb8d8e232aadea866c202e1dd7a5967e2877
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/shellvars.py#L128-L137
2,794
jsvine/spectra
spectra/__init__.py
cmyk
def cmyk(c, m, y, k): """ Create a spectra.Color object in the CMYK color space. :param float c: c coordinate. :param float m: m coordinate. :param float y: y coordinate. :param float k: k coordinate. :rtype: Color :returns: A spectra.Color object in the CMYK color space. """ return Color("cmyk", c, m, y, k)
python
def cmyk(c, m, y, k): return Color("cmyk", c, m, y, k)
[ "def", "cmyk", "(", "c", ",", "m", ",", "y", ",", "k", ")", ":", "return", "Color", "(", "\"cmyk\"", ",", "c", ",", "m", ",", "y", ",", "k", ")" ]
Create a spectra.Color object in the CMYK color space. :param float c: c coordinate. :param float m: m coordinate. :param float y: y coordinate. :param float k: k coordinate. :rtype: Color :returns: A spectra.Color object in the CMYK color space.
[ "Create", "a", "spectra", ".", "Color", "object", "in", "the", "CMYK", "color", "space", "." ]
2269a0ae9b5923154b15bd661fb81179608f7ec2
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/__init__.py#L63-L75
2,795
jsvine/spectra
spectra/grapefruit.py
Color.ColorWithHue
def ColorWithHue(self, hue): '''Create a new instance based on this one with a new hue. Parameters: :hue: The hue of the new color [0...360]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60) (1.0, 1.0, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60).hsl (60, 1, 0.5) ''' h, s, l = self.__hsl return Color((hue, s, l), 'hsl', self.__a, self.__wref)
python
def ColorWithHue(self, hue): '''Create a new instance based on this one with a new hue. Parameters: :hue: The hue of the new color [0...360]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60) (1.0, 1.0, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60).hsl (60, 1, 0.5) ''' h, s, l = self.__hsl return Color((hue, s, l), 'hsl', self.__a, self.__wref)
[ "def", "ColorWithHue", "(", "self", ",", "hue", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "return", "Color", "(", "(", "hue", ",", "s", ",", "l", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")" ]
Create a new instance based on this one with a new hue. Parameters: :hue: The hue of the new color [0...360]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60) (1.0, 1.0, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60).hsl (60, 1, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "this", "one", "with", "a", "new", "hue", "." ]
2269a0ae9b5923154b15bd661fb81179608f7ec2
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1604-L1621
2,796
jsvine/spectra
spectra/grapefruit.py
Color.ColorWithSaturation
def ColorWithSaturation(self, saturation): '''Create a new instance based on this one with a new saturation value. .. note:: The saturation is defined for the HSL mode. Parameters: :saturation: The saturation of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5) (0.75, 0.5, 0.25, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5).hsl (30, 0.5, 0.5) ''' h, s, l = self.__hsl return Color((h, saturation, l), 'hsl', self.__a, self.__wref)
python
def ColorWithSaturation(self, saturation): '''Create a new instance based on this one with a new saturation value. .. note:: The saturation is defined for the HSL mode. Parameters: :saturation: The saturation of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5) (0.75, 0.5, 0.25, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5).hsl (30, 0.5, 0.5) ''' h, s, l = self.__hsl return Color((h, saturation, l), 'hsl', self.__a, self.__wref)
[ "def", "ColorWithSaturation", "(", "self", ",", "saturation", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "return", "Color", "(", "(", "h", ",", "saturation", ",", "l", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")" ]
Create a new instance based on this one with a new saturation value. .. note:: The saturation is defined for the HSL mode. Parameters: :saturation: The saturation of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5) (0.75, 0.5, 0.25, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5).hsl (30, 0.5, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "this", "one", "with", "a", "new", "saturation", "value", "." ]
2269a0ae9b5923154b15bd661fb81179608f7ec2
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1623-L1644
2,797
jsvine/spectra
spectra/grapefruit.py
Color.ColorWithLightness
def ColorWithLightness(self, lightness): '''Create a new instance based on this one with a new lightness value. Parameters: :lightness: The lightness of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25) (0.5, 0.25, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25).hsl (30, 1, 0.25) ''' h, s, l = self.__hsl return Color((h, s, lightness), 'hsl', self.__a, self.__wref)
python
def ColorWithLightness(self, lightness): '''Create a new instance based on this one with a new lightness value. Parameters: :lightness: The lightness of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25) (0.5, 0.25, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25).hsl (30, 1, 0.25) ''' h, s, l = self.__hsl return Color((h, s, lightness), 'hsl', self.__a, self.__wref)
[ "def", "ColorWithLightness", "(", "self", ",", "lightness", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "return", "Color", "(", "(", "h", ",", "s", ",", "lightness", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")" ]
Create a new instance based on this one with a new lightness value. Parameters: :lightness: The lightness of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25) (0.5, 0.25, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25).hsl (30, 1, 0.25)
[ "Create", "a", "new", "instance", "based", "on", "this", "one", "with", "a", "new", "lightness", "value", "." ]
2269a0ae9b5923154b15bd661fb81179608f7ec2
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1646-L1663
2,798
jsvine/spectra
spectra/grapefruit.py
Color.LighterColor
def LighterColor(self, level): '''Create a new instance based on this one but lighter. Parameters: :level: The amount by which the color should be lightened to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25) (1.0, 0.75, 0.5, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25).hsl (30, 1, 0.75) ''' h, s, l = self.__hsl return Color((h, s, min(l + level, 1)), 'hsl', self.__a, self.__wref)
python
def LighterColor(self, level): '''Create a new instance based on this one but lighter. Parameters: :level: The amount by which the color should be lightened to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25) (1.0, 0.75, 0.5, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25).hsl (30, 1, 0.75) ''' h, s, l = self.__hsl return Color((h, s, min(l + level, 1)), 'hsl', self.__a, self.__wref)
[ "def", "LighterColor", "(", "self", ",", "level", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "return", "Color", "(", "(", "h", ",", "s", ",", "min", "(", "l", "+", "level", ",", "1", ")", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")" ]
Create a new instance based on this one but lighter. Parameters: :level: The amount by which the color should be lightened to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25) (1.0, 0.75, 0.5, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25).hsl (30, 1, 0.75)
[ "Create", "a", "new", "instance", "based", "on", "this", "one", "but", "lighter", "." ]
2269a0ae9b5923154b15bd661fb81179608f7ec2
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1685-L1703
2,799
jsvine/spectra
spectra/grapefruit.py
Color.Gradient
def Gradient(self, target, steps=100): '''Create a list with the gradient colors between this and the other color. Parameters: :target: The grapefruit.Color at the other end of the gradient. :steps: The number of gradients steps to create. Returns: A list of grapefruit.Color instances. >>> c1 = Color.NewFromRgb(1.0, 0.0, 0.0, alpha=1) >>> c2 = Color.NewFromRgb(0.0, 1.0, 0.0, alpha=0) >>> c1.Gradient(c2, 3) [(0.75, 0.25, 0.0, 0.75), (0.5, 0.5, 0.0, 0.5), (0.25, 0.75, 0.0, 0.25)] ''' gradient = [] rgba1 = self.__rgb + (self.__a,) rgba2 = target.__rgb + (target.__a,) steps += 1 for n in range(1, steps): d = 1.0*n/steps r = (rgba1[0]*(1-d)) + (rgba2[0]*d) g = (rgba1[1]*(1-d)) + (rgba2[1]*d) b = (rgba1[2]*(1-d)) + (rgba2[2]*d) a = (rgba1[3]*(1-d)) + (rgba2[3]*d) gradient.append(Color((r, g, b), 'rgb', a, self.__wref)) return gradient
python
def Gradient(self, target, steps=100): '''Create a list with the gradient colors between this and the other color. Parameters: :target: The grapefruit.Color at the other end of the gradient. :steps: The number of gradients steps to create. Returns: A list of grapefruit.Color instances. >>> c1 = Color.NewFromRgb(1.0, 0.0, 0.0, alpha=1) >>> c2 = Color.NewFromRgb(0.0, 1.0, 0.0, alpha=0) >>> c1.Gradient(c2, 3) [(0.75, 0.25, 0.0, 0.75), (0.5, 0.5, 0.0, 0.5), (0.25, 0.75, 0.0, 0.25)] ''' gradient = [] rgba1 = self.__rgb + (self.__a,) rgba2 = target.__rgb + (target.__a,) steps += 1 for n in range(1, steps): d = 1.0*n/steps r = (rgba1[0]*(1-d)) + (rgba2[0]*d) g = (rgba1[1]*(1-d)) + (rgba2[1]*d) b = (rgba1[2]*(1-d)) + (rgba2[2]*d) a = (rgba1[3]*(1-d)) + (rgba2[3]*d) gradient.append(Color((r, g, b), 'rgb', a, self.__wref)) return gradient
[ "def", "Gradient", "(", "self", ",", "target", ",", "steps", "=", "100", ")", ":", "gradient", "=", "[", "]", "rgba1", "=", "self", ".", "__rgb", "+", "(", "self", ".", "__a", ",", ")", "rgba2", "=", "target", ".", "__rgb", "+", "(", "target", ".", "__a", ",", ")", "steps", "+=", "1", "for", "n", "in", "range", "(", "1", ",", "steps", ")", ":", "d", "=", "1.0", "*", "n", "/", "steps", "r", "=", "(", "rgba1", "[", "0", "]", "*", "(", "1", "-", "d", ")", ")", "+", "(", "rgba2", "[", "0", "]", "*", "d", ")", "g", "=", "(", "rgba1", "[", "1", "]", "*", "(", "1", "-", "d", ")", ")", "+", "(", "rgba2", "[", "1", "]", "*", "d", ")", "b", "=", "(", "rgba1", "[", "2", "]", "*", "(", "1", "-", "d", ")", ")", "+", "(", "rgba2", "[", "2", "]", "*", "d", ")", "a", "=", "(", "rgba1", "[", "3", "]", "*", "(", "1", "-", "d", ")", ")", "+", "(", "rgba2", "[", "3", "]", "*", "d", ")", "gradient", ".", "append", "(", "Color", "(", "(", "r", ",", "g", ",", "b", ")", ",", "'rgb'", ",", "a", ",", "self", ".", "__wref", ")", ")", "return", "gradient" ]
Create a list with the gradient colors between this and the other color. Parameters: :target: The grapefruit.Color at the other end of the gradient. :steps: The number of gradients steps to create. Returns: A list of grapefruit.Color instances. >>> c1 = Color.NewFromRgb(1.0, 0.0, 0.0, alpha=1) >>> c2 = Color.NewFromRgb(0.0, 1.0, 0.0, alpha=0) >>> c1.Gradient(c2, 3) [(0.75, 0.25, 0.0, 0.75), (0.5, 0.5, 0.0, 0.5), (0.25, 0.75, 0.0, 0.25)]
[ "Create", "a", "list", "with", "the", "gradient", "colors", "between", "this", "and", "the", "other", "color", "." ]
2269a0ae9b5923154b15bd661fb81179608f7ec2
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1764-L1797