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 list | docstring stringlengths 3 17.3k | docstring_tokens list | 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 < le... | 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... | [
"def",
"extract_with_context",
"(",
"lst",
",",
"pred",
",",
"before_context",
",",
"after_context",
")",
":",
"rval",
"=",
"[",
"]",
"start",
"=",
"0",
"length",
"=",
"0",
"while",
"start",
"<",
"len",
"(",
"lst",
")",
":",
"usedfirst",
"=",
"False",
... | 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 ... | 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 ch... | [
"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 tr... | 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"... | 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 no... | 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(... | [
"def",
"extracthtmlurls",
"(",
"mesg",
")",
":",
"chunk",
"=",
"HTMLChunker",
"(",
")",
"chunk",
".",
"feed",
"(",
"mesg",
")",
"chunk",
".",
"close",
"(",
")",
"# above_context = 1",
"# below_context = 1",
"def",
"somechunkisurl",
"(",
"chunks",
")",
":",
... | 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 mess... | 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 s... | [
"def",
"decode_bytes",
"(",
"byt",
",",
"enc",
"=",
"'utf-8'",
")",
":",
"try",
":",
"strg",
"=",
"byt",
".",
"decode",
"(",
"enc",
")",
"except",
"UnicodeDecodeError",
"as",
"err",
":",
"strg",
"=",
"\"Unable to decode message:\\n{}\\n{}\"",
".",
"format",
... | 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... | 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.... | [
"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",
"# s... | 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... | 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()... | [
"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_chars... | 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",
")",
"<",
"... | 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"]
... | 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",
")",
"e... | 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 stri... | [
"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)
... | 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",
",",
... | 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):
... | 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
... | [
"def",
"handle_keys",
"(",
"self",
",",
"keys",
",",
"raw",
")",
":",
"for",
"j",
",",
"k",
"in",
"enumerate",
"(",
"keys",
")",
":",
"if",
"self",
".",
"search",
"is",
"True",
":",
"text",
"=",
"\"Search: {}\"",
".",
"format",
"(",
"self",
".",
... | 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... | 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._searc... | [
"def",
"unhandled",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"key",
"=",
"key",
"self",
".",
"size",
"=",
"self",
".",
"tui",
".",
"get_cols_rows",
"(",
")",
"if",
"self",
".",
"search",
"is",
"True",
":",
"if",
"self",
".",
"enter",
"is",... | 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 = \... | 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 = \
... | [
"def",
"_digits",
"(",
"self",
")",
":",
"self",
".",
"number",
"+=",
"self",
".",
"key",
"try",
":",
"if",
"self",
".",
"compact",
"is",
"False",
":",
"self",
".",
"top",
".",
"body",
".",
"focus_position",
"=",
"self",
".",
"items",
".",
"index",... | 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
... | 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):
i... | [
"def",
"_search",
"(",
"self",
")",
":",
"text",
"=",
"\"Search: {}\"",
".",
"format",
"(",
"self",
".",
"search_string",
")",
"footerwid",
"=",
"urwid",
".",
"AttrMap",
"(",
"urwid",
".",
"Text",
"(",
"text",
")",
",",
"'footer'",
")",
"self",
".",
... | 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",
"(",
"siz... | 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... | 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(b... | [
"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... | 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
... | 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.Divid... | [
"def",
"process_urls",
"(",
"self",
",",
"extractedurls",
",",
"dedupe",
",",
"shorten",
")",
":",
"cols",
",",
"_",
"=",
"urwid",
".",
"raw_display",
".",
"Screen",
"(",
")",
".",
"get_cols_rows",
"(",
")",
"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.getcw... | 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",
".",
... | 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... | 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_fil... | [
"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",
"(",
")"... | 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_fi... | 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,... | [
"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_... | 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'... | 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
... | [
"def",
"_send_register_payload",
"(",
"self",
",",
"websocket",
")",
":",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"HANDSHAKE_FILE_NAME",
")",
"data",
"=",
"codecs",
".",
"open",
"(... | 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:
lo... | 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 c... | [
"def",
"_register",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'register on %s'",
",",
"\"ws://{}:{}\"",
".",
"format",
"(",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
")",
"try",
":",
"websocket",
"=",
"yield",
"from",
"websockets",
"... | 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:... | 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 faile... | [
"def",
"_command",
"(",
"self",
",",
"msg",
")",
":",
"logger",
".",
"debug",
"(",
"'send command to %s'",
",",
"\"ws://{}:{}\"",
".",
"format",
"(",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
")",
"try",
":",
"websocket",
"=",
"yield",
"from",
... | 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://{}".f... | 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': paylo... | [
"def",
"command",
"(",
"self",
",",
"request_type",
",",
"uri",
",",
"payload",
")",
":",
"self",
".",
"command_count",
"+=",
"1",
"if",
"payload",
"is",
"None",
":",
"payload",
"=",
"{",
"}",
"message",
"=",
"{",
"'id'",
":",
"\"{}_{}\"",
".",
"form... | 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:
ico... | 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(ico... | [
"def",
"send_message",
"(",
"self",
",",
"message",
",",
"icon_path",
"=",
"None",
")",
":",
"icon_encoded_string",
"=",
"''",
"icon_extension",
"=",
"''",
"if",
"icon_path",
"is",
"not",
"None",
":",
"icon_extension",
"=",
"os",
".",
"path",
".",
"splitex... | 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",
"(",
... | 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 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",
... | 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",
"(... | 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",
"(",
"'... | 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... | 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 li... | 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(ele... | [
"def",
"elem_to_container",
"(",
"elem",
",",
"container",
"=",
"dict",
",",
"*",
"*",
"options",
")",
":",
"dic",
"=",
"container",
"(",
")",
"if",
"elem",
"is",
"None",
":",
"return",
"dic",
"elem",
".",
"tag",
"=",
"_tweak_ns",
"(",
"elem",
".",
... | 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 d... | [
"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
... | 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, conta... | [
"def",
"root_to_container",
"(",
"root",
",",
"container",
"=",
"dict",
",",
"nspaces",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"tree",
"=",
"container",
"(",
")",
"if",
"root",
"is",
"None",
":",
"return",
"tree",
"if",
"nspaces",
"is",
"no... | 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 node... | [
"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: ... | 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 attribut... | [
"def",
"container_to_etree",
"(",
"obj",
",",
"parent",
"=",
"None",
",",
"to_str",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"to_str",
"is",
"None",
":",
"to_str",
"=",
"_to_str_fn",
"(",
"*",
"*",
"options",
")",
"if",
"not",
"anyconfi... | 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 i... | [
"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(st... | 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",
"... | 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... | 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)
... | [
"def",
"_customized_loader",
"(",
"container",
",",
"loader",
"=",
"Loader",
",",
"mapping_tag",
"=",
"_MAPPING_TAG",
")",
":",
"def",
"construct_mapping",
"(",
"loader",
",",
"node",
",",
"deep",
"=",
"False",
")",
":",
"\"\"\"Construct python object from yaml ma... | 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... | 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",
")"... | 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" ... | [
"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):
... | 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):
... | [
"def",
"yml_load",
"(",
"stream",
",",
"container",
",",
"yml_fnc",
"=",
"yml_fnc",
",",
"*",
"*",
"options",
")",
":",
"if",
"options",
".",
"get",
"(",
"\"ac_safe\"",
",",
"False",
")",
":",
"options",
"=",
"{",
"}",
"# yaml.safe_load does not process Lo... | 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 ... | 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_di... | [
"def",
"yml_dump",
"(",
"data",
",",
"stream",
",",
"yml_fnc",
"=",
"yml_fnc",
",",
"*",
"*",
"options",
")",
":",
"_is_dict",
"=",
"anyconfig",
".",
"utils",
".",
"is_dict_like",
"(",
"data",
")",
"if",
"options",
".",
"get",
"(",
"\"ac_safe\"",
",",
... | 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 _s... | 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.... | 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... | [
"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)
{... | 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",
"... | 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': {'... | 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)... | [
"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",
")",
"]",
"... | 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 be... | [
"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)
>>> ... | 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'... | 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 upd... | [
"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 -> va... | 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],... | [
"def",
"_update_with_merge",
"(",
"self",
",",
"other",
",",
"key",
",",
"val",
"=",
"None",
",",
"merge_lists",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"if",
"val",
"is",
"None",
":",
"val",
"=",
"other",
"[",
"key",
"]",
"if",
"key",
... | 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) t... | [
"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... | 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",... | 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 _M... | 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"... | 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', '')
>... | 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",
"(",
... | 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',... | [
"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.... | 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",
".",
"starts... | 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 = ... | [
"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 sto... | 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.
... | [
"def",
"load",
"(",
"stream",
",",
"container",
"=",
"dict",
",",
"comment_markers",
"=",
"_COMMENT_MARKERS",
")",
":",
"ret",
"=",
"container",
"(",
")",
"prev",
"=",
"\"\"",
"for",
"line",
"in",
"stream",
".",
"readlines",
"(",
")",
":",
"line",
"=",... | 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)
:... | [
"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 a... | 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... | [
"def",
"render_s",
"(",
"tmpl_s",
",",
"ctx",
"=",
"None",
",",
"paths",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"if",
"paths",
"is",
"None",
":",
"paths",
"=",
"[",
"os",
".",
"curdir",
"]",
"env",
"=",
"tmpl_env",
"(",
"paths",
")",... | 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)
>>> re... | [
"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",
... | 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 ... | 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.w... | [
"def",
"query",
"(",
"data",
",",
"*",
"*",
"options",
")",
":",
"expression",
"=",
"options",
".",
"get",
"(",
"\"ac_query\"",
",",
"None",
")",
"if",
"expression",
"is",
"None",
"or",
"not",
"expression",
":",
"return",
"data",
"try",
":",
"pexp",
... | 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.
... | [
"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, ope... | 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(g... | [
"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_pa... | 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",... | 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'))
>>> asse... | 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... | [
"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",
","... | 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.Str... | [
"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):
... | 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
... | [
"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 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(b... | 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(fnc... | 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",
"(",
"a... | 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 rang... | [
"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 w... | 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",
... | 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 an... | [
"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
... | 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
... | [
"def",
"single_load",
"(",
"input_",
",",
"ac_parser",
"=",
"None",
",",
"ac_template",
"=",
"False",
",",
"ac_context",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"cnf",
"=",
"_single_load",
"(",
"input_",
",",
"ac_parser",
"=",
"ac_parser",
",",
... | 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 represent... | [
"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 ... | 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 ... | [
"def",
"multi_load",
"(",
"inputs",
",",
"ac_parser",
"=",
"None",
",",
"ac_template",
"=",
"False",
",",
"ac_context",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"marker",
"=",
"options",
".",
"setdefault",
"(",
"\"ac_marker\"",
",",
"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.P... | [
"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... | 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... | [
"def",
"load",
"(",
"path_specs",
",",
"ac_parser",
"=",
"None",
",",
"ac_dict",
"=",
"None",
",",
"ac_template",
"=",
"False",
",",
"ac_context",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"marker",
"=",
"options",
".",
"setdefault",
"(",
"\"ac_... | 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/\*... | [
"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",
".",... | 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.I... | 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",
... | 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... | [
"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... | 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, UnknownProcesso... | [
"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
... | 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:
r... | [
"def",
"parse_single",
"(",
"str_",
")",
":",
"if",
"str_",
"is",
"None",
":",
"return",
"''",
"str_",
"=",
"str_",
".",
"strip",
"(",
")",
"if",
"not",
"str_",
":",
"return",
"''",
"if",
"BOOL_PATTERN",
".",
"match",
"(",
"str_",
")",
"is",
"not",... | 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 ... | [
"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")
['... | 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, ... | [
"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 at... | 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)
... | [
"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",
... | 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 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.l... | 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:" + se... | [
"def",
"_show_psrs",
"(",
")",
":",
"sep",
"=",
"os",
".",
"linesep",
"types",
"=",
"\"Supported types: \"",
"+",
"\", \"",
".",
"join",
"(",
"API",
".",
"list_types",
"(",
")",
")",
"cids",
"=",
"\"IDs: \"",
"+",
"\", \"",
".",
"join",
"(",
"c",
"fo... | 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_le... | 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 = ... | [
"def",
"_parse_args",
"(",
"argv",
")",
":",
"parser",
"=",
"make_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"LOGGER",
".",
"setLevel",
"(",
"to_log_level",
"(",
"args",
".",
"loglevel",
")",
")",
"if",
"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 objec... | 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 _va... | [
"def",
"validate",
"(",
"data",
",",
"schema",
",",
"ac_schema_safe",
"=",
"True",
",",
"ac_schema_errors",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"JSONSCHEMA_IS_AVAIL",
":",
"return",
"(",
"True",
",",
"_NA_MSG",
")",
"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 sche... | [
"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_sch... | 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"] = le... | [
"def",
"array_to_schema",
"(",
"arr",
",",
"*",
"*",
"options",
")",
":",
"(",
"typemap",
",",
"strict",
")",
"=",
"_process_options",
"(",
"*",
"*",
"options",
")",
"arr",
"=",
"list",
"(",
"arr",
")",
"scm",
"=",
"dict",
"(",
"type",
"=",
"typema... | 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
... | [
"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(outdi... | 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",
"(",
"\... | 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 ... | 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... | [
"def",
"load_with_fn",
"(",
"load_fn",
",",
"content_or_strm",
",",
"container",
",",
"allow_primitives",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"ret",
"=",
"load_fn",
"(",
"content_or_strm",
",",
"*",
"*",
"options",
")",
"if",
"anyconfig",
"."... | 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 t... | [
"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: option... | 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"... | 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 st... | [
"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 = o... | 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.
... | [
"def",
"_container_factory",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"ac_dict",
"=",
"options",
".",
"get",
"(",
"\"ac_dict\"",
",",
"False",
")",
"_dicts",
"=",
"[",
"x",
"for",
"x",
"in",
"(",
"options",
".",
"get",
"(",
"o",
")",
"for",... | 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 ... | 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)
... | [
"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",
"... | 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
:re... | 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 ::... | 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/... | 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",
"(",... | 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... | [
"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
... | 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, **... | [
"def",
"dump",
"(",
"self",
",",
"cnf",
",",
"ioi",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"anyconfig",
".",
"utils",
".",
"filter_options",
"(",
"self",
".",
"_dump_opts",
",",
"kwargs",
")",
"if",
"anyconfig",
".",
"utils",
".",
"is_stre... | 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 saniti... | [
"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
... | 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
... | 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",
",",
"*",
"*"... | 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'
... | 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",
".",
"al... | 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'
:r... | 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",
".",
"allo... | 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 anyconf... | 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: ... | [
"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",
"(",... | 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
>>... | [
"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')
... | 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()
... | [
"def",
"_parseline",
"(",
"line",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^\\s*(export)?\\s*(\\S+)=(?:(?:\"",
"r\"(?:\\\"(.*[^\\\\])\\\")|(?:'(.*[^\\\\])')|\"",
"r\"(?:([^\\\"'#\\s]+)))?)\\s*#*\"",
",",
"line",
")",
"if",
"not",
"match",
":",
"LOGGER",
".",... | 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'")
(... | [
"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 ... | 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)
con... | [
"def",
"load",
"(",
"stream",
",",
"container",
"=",
"dict",
")",
":",
"ret",
"=",
"container",
"(",
")",
"for",
"line",
"in",
"stream",
".",
"readlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"line",
"is",
"None",
"o... | 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
>>> ... | [
"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
... | 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\"",
"%",... | 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.
"""
r... | 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(3... | 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(3... | [
"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
... | [
"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.
... | 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.
... | [
"def",
"ColorWithSaturation",
"(",
"self",
",",
"saturation",
")",
":",
"h",
",",
"s",
",",
"l",
"=",
"self",
".",
"__hsl",
"return",
"Color",
"(",
"(",
"h",
",",
"saturation",
",",
"l",
")",
",",
"'hsl'",
",",
"self",
".",
"__a",
",",
"self",
".... | 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).ColorWithSat... | [
"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,... | 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,... | [
"def",
"ColorWithLightness",
"(",
"self",
",",
"lightness",
")",
":",
"h",
",",
"s",
",",
"l",
"=",
"self",
".",
"__hsl",
"return",
"Color",
"(",
"(",
"h",
",",
"s",
",",
"lightness",
")",
",",
"'hsl'",
",",
"self",
".",
"__a",
",",
"self",
".",
... | 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,... | [
"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(... | 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(... | [
"def",
"LighterColor",
"(",
"self",
",",
"level",
")",
":",
"h",
",",
"s",
",",
"l",
"=",
"self",
".",
"__hsl",
"return",
"Color",
"(",
"(",
"h",
",",
"s",
",",
"min",
"(",
"l",
"+",
"level",
",",
"1",
")",
")",
",",
"'hsl'",
",",
"self",
"... | 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)
>>... | [
"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.C... | 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.C... | [
"def",
"Gradient",
"(",
"self",
",",
"target",
",",
"steps",
"=",
"100",
")",
":",
"gradient",
"=",
"[",
"]",
"rgba1",
"=",
"self",
".",
"__rgb",
"+",
"(",
"self",
".",
"__a",
",",
")",
"rgba2",
"=",
"target",
".",
"__rgb",
"+",
"(",
"target",
... | 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... | [
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.