_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q2700 | extract_with_context | train | 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 | {
"resource": ""
} |
q2701 | extracturls | train | 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 | {
"resource": ""
} |
q2702 | extracthtmlurls | train | 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 | {
"resource": ""
} |
q2703 | decode_bytes | train | 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 | {
"resource": ""
} |
q2704 | decode_msg | train | 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 | {
"resource": ""
} |
q2705 | msgurls | train | 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 | {
"resource": ""
} |
q2706 | shorten_url | train | 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 | {
"resource": ""
} |
q2707 | splittext | train | 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 | {
"resource": ""
} |
q2708 | URLChooser.main | train | 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 | {
"resource": ""
} |
q2709 | URLChooser.handle_keys | train | 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 | {
"resource": ""
} |
q2710 | URLChooser.unhandled | train | 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 | {
"resource": ""
} |
q2711 | URLChooser._digits | train | 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 | {
"resource": ""
} |
q2712 | URLChooser._search | train | 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 | {
"resource": ""
} |
q2713 | URLChooser.draw_screen | train | 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 | {
"resource": ""
} |
q2714 | URLChooser.mkbrowseto | train | 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 | {
"resource": ""
} |
q2715 | URLChooser.process_urls | train | 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 | {
"resource": ""
} |
q2716 | WebOsClient._get_key_file_path | train | 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 | {
"resource": ""
} |
q2717 | WebOsClient.load_key_file | train | 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 | {
"resource": ""
} |
q2718 | WebOsClient.save_key_file | train | 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 | {
"resource": ""
} |
q2719 | WebOsClient._send_register_payload | train | 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 | {
"resource": ""
} |
q2720 | WebOsClient._register | train | 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 | {
"resource": ""
} |
q2721 | WebOsClient.register | train | def register(self):
"""Pair client with tv."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self._register()) | python | {
"resource": ""
} |
q2722 | WebOsClient._command | train | 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 | {
"resource": ""
} |
q2723 | WebOsClient.command | train | 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 | {
"resource": ""
} |
q2724 | WebOsClient.send_message | train | 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 | {
"resource": ""
} |
q2725 | WebOsClient.get_apps | train | 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 | {
"resource": ""
} |
q2726 | WebOsClient.get_current_app | train | 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 | {
"resource": ""
} |
q2727 | WebOsClient.get_services | train | 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 | {
"resource": ""
} |
q2728 | WebOsClient.get_software_info | train | 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 | {
"resource": ""
} |
q2729 | WebOsClient.get_inputs | train | 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 | {
"resource": ""
} |
q2730 | WebOsClient.get_audio_status | train | 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 | {
"resource": ""
} |
q2731 | WebOsClient.get_volume | train | 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 | {
"resource": ""
} |
q2732 | WebOsClient.get_channels | train | 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 | {
"resource": ""
} |
q2733 | WebOsClient.get_current_channel | train | 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 | {
"resource": ""
} |
q2734 | WebOsClient.get_channel_info | train | 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 | {
"resource": ""
} |
q2735 | elem_to_container | train | 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 | {
"resource": ""
} |
q2736 | root_to_container | train | 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 | {
"resource": ""
} |
q2737 | container_to_etree | train | 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 | {
"resource": ""
} |
q2738 | etree_write | train | 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 | {
"resource": ""
} |
q2739 | _customized_loader | train | 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 | {
"resource": ""
} |
q2740 | yml_fnc | train | 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 | {
"resource": ""
} |
q2741 | yml_load | train | 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 | {
"resource": ""
} |
q2742 | yml_dump | train | 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 | {
"resource": ""
} |
q2743 | _split_path | train | 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 | {
"resource": ""
} |
q2744 | mk_nested_dic | train | 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 | {
"resource": ""
} |
q2745 | get | train | 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 | {
"resource": ""
} |
q2746 | set_ | train | 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 | {
"resource": ""
} |
q2747 | _update_with_replace | train | 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 | {
"resource": ""
} |
q2748 | _update_with_merge | train | 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 | {
"resource": ""
} |
q2749 | _update_with_merge_lists | train | 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 | {
"resource": ""
} |
q2750 | _get_update_fn | train | 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 | {
"resource": ""
} |
q2751 | _parseline | train | 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 | {
"resource": ""
} |
q2752 | _pre_process_line | train | 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 | {
"resource": ""
} |
q2753 | load | train | 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 | {
"resource": ""
} |
q2754 | render_s | train | 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 | {
"resource": ""
} |
q2755 | _to_s | train | 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 | {
"resource": ""
} |
q2756 | query | train | 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 | {
"resource": ""
} |
q2757 | groupby | train | 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 | {
"resource": ""
} |
q2758 | is_paths | train | 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 | {
"resource": ""
} |
q2759 | get_path_from_stream | train | 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 | {
"resource": ""
} |
q2760 | _try_to_get_extension | train | 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 | {
"resource": ""
} |
q2761 | filter_options | train | 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 | {
"resource": ""
} |
q2762 | memoize | train | 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 | {
"resource": ""
} |
q2763 | open | train | 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 | {
"resource": ""
} |
q2764 | single_load | train | 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 | {
"resource": ""
} |
q2765 | multi_load | train | 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 | {
"resource": ""
} |
q2766 | load | train | 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 | {
"resource": ""
} |
q2767 | dump | train | 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 | {
"resource": ""
} |
q2768 | dumps | train | 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 | {
"resource": ""
} |
q2769 | parse_single | train | 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 | {
"resource": ""
} |
q2770 | parse_list | train | 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 | {
"resource": ""
} |
q2771 | attr_val_itr | train | 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 | {
"resource": ""
} |
q2772 | _exit_with_output | train | 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 | {
"resource": ""
} |
q2773 | _show_psrs | train | 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 | {
"resource": ""
} |
q2774 | _parse_args | train | 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 | {
"resource": ""
} |
q2775 | validate | train | 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 | {
"resource": ""
} |
q2776 | array_to_schema | train | 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 | {
"resource": ""
} |
q2777 | ensure_outdir_exists | train | 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 | {
"resource": ""
} |
q2778 | load_with_fn | train | 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 | {
"resource": ""
} |
q2779 | dump_with_fn | train | 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 | {
"resource": ""
} |
q2780 | LoaderMixin._container_factory | train | 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 | {
"resource": ""
} |
q2781 | LoaderMixin._load_options | train | 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 | {
"resource": ""
} |
q2782 | LoaderMixin.load_from_string | train | 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 | {
"resource": ""
} |
q2783 | LoaderMixin.load_from_stream | train | 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 | {
"resource": ""
} |
q2784 | LoaderMixin.loads | train | 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 | {
"resource": ""
} |
q2785 | DumperMixin.dump | train | 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 | {
"resource": ""
} |
q2786 | FromStringLoaderMixin.load_from_stream | train | 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 | {
"resource": ""
} |
q2787 | FromStreamLoaderMixin.load_from_string | train | 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 | {
"resource": ""
} |
q2788 | StringStreamFnParser.load_from_string | train | 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 | {
"resource": ""
} |
q2789 | StringStreamFnParser.load_from_stream | train | 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 | {
"resource": ""
} |
q2790 | guess_io_type | train | 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 | {
"resource": ""
} |
q2791 | _parseline | train | 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 | {
"resource": ""
} |
q2792 | load | train | 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 | {
"resource": ""
} |
q2793 | Parser.dump_to_stream | train | 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 | {
"resource": ""
} |
q2794 | cmyk | train | 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 | {
"resource": ""
} |
q2795 | Color.ColorWithHue | train | 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 | {
"resource": ""
} |
q2796 | Color.ColorWithSaturation | train | 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 | {
"resource": ""
} |
q2797 | Color.ColorWithLightness | train | 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 | {
"resource": ""
} |
q2798 | Color.LighterColor | train | 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 | {
"resource": ""
} |
q2799 | Color.Gradient | train | 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 | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.