_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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 < len(lst) and length < before_context + 1 \ and not pred(lst[start + length]): length += 1 # Slide to the next match. while start + length < len(lst) and not pred(lst[start + length]): start += 1 # If there was no next match, abort here (it's easier # to do this than to try to detect this case later). if start + length == len(lst): break # Now extend repeatedly until we can't find anything. while start + length < len(lst) and pred(lst[start + length]): extendlength = 1 # Read in the 'after' context and see if it holds a URL. while extendlength < after_context + 1 and start + length + \ extendlength < len(lst) and \ not pred(lst[start + length + extendlength]): extendlength += 1 length += extendlength if start + length < len(lst) and not pred(lst[start + length]): # Didn't find a matching line, so we either # hit the end or extended to after_context + 1.. # # Now read in possible 'before' context # from the next URL; if we don't find one, # we discard the readahead.
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 lines of context above to provide. # above_context = 1 # The number of lines of context below to provide. # below_context = 1 # Plan here is to first transform lines into the form # [line_fragments] where each fragment is a chunk as # seen by parse_text_urls. Note that this means that # lines with more than one entry or one entry that's
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:
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:
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
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_multipart(): for part in msg.get_payload(): for chunk in msgurls(part, urlidx): urlidx += 1 yield chunk elif msg.get_content_type() == "text/plain":
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
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"] for search="mo", text="string more string" and attr="default" """
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,
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): if self.search is True: text = "Search: {}".format(self.search_string) if k == 'enter': # Catch 'enter' key to prevent opening URL in mkbrowseto self.enter = True if not self.items: self.search = False self.enter = False if self.search_string: footer = 'search' else: footer = 'default' text = "" footerwid = urwid.AttrMap(urwid.Text(text), footer) self.top.footer = footerwid elif k in self.activate_keys: self.search_string += k self._search() elif k == 'backspace': self.search_string = self.search_string[:-1] self._search() elif k in self.activate_keys and \ self.urls and \ self.search is False and \ self.help_menu is False: self._open_url()
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.isprintable(): self.search_string += key self._search() elif self.enter is True and not self.search_string:
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:
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 for idx, item in enumerate(grp): if isinstance(item, urwid.Columns): for col_idx, col in enumerate(item.contents): if isinstance(col[0], urwid.decoration.AttrMap): grp[idx][col_idx].set_label(splittext(col[0].base_widget.label, self.search_string, '')) if self.search_string.lower() in col[0].base_widget.label.lower(): grp[idx][col_idx].set_label(splittext(col[0].base_widget.label, self.search_string, 'search')) done = True elif isinstance(item, urwid.Text): grp[idx].set_text(splittext(item.text, self.search_string, '')) if self.search_string.lower() in item.text.lower():
python
{ "resource": "" }
q2713
URLChooser.draw_screen
train
def draw_screen(self, size): """Render curses screen """
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'] except KeyError: pass else: del os.environ['BROWSER'] webbrowser.register(browser, None, webbrowser.GenericBrowser(browser)) try_idx = webbrowser._tryorder.index(browser) webbrowser._tryorder.insert(0, webbrowser._tryorder.pop(try_idx)) def browse(*args): # double ()() to ensure self.search evaluated at runtime, not when # browse() is _created_. [0] is self.search, [1] is self.enter # self.enter prevents opening URL when in search mode if self._get_search()[0]() is True: if self._get_search()[1]() is True: self.search = False
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 urls - List of all URLs """ cols, _ = urwid.raw_display.Screen().get_cols_rows() items = [] urls = [] first = True for group, usedfirst, usedlast in extractedurls: if first: first = False items.append(urwid.Divider(div_char='-', top=1, bottom=1)) if dedupe is True: # If no unique URLs exist, then skip the group completely if not [chunk for chunks in group for chunk in chunks if chunk.url is not None and chunk.url not in urls]: continue groupurls = [] markup = [] if not usedfirst: markup.append(('msgtext:ellipses', '...\n')) for chunks in group: i = 0 while i < len(chunks): chunk = chunks[i] i += 1 if chunk.url is None: markup.append(('msgtext', chunk.markup)) else: if (dedupe is True and chunk.url not in urls) \
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),
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 from %s', key_file_path); if os.path.isfile(key_file_path): with open(key_file_path, 'r') as f: raw_data = f.read()
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_file_path); with open(key_file_path, 'w+') as f:
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']['client-key'] = self.client_key yield from websocket.send(json.dumps(handshake)) raw_response = yield from websocket.recv() response = json.loads(raw_response) if response['type'] == 'response' and \
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: logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False
python
{ "resource": "" }
q2721
WebOsClient.register
train
def register(self): """Pair client with tv.""" loop = asyncio.new_event_loop()
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: logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) if not self.client_key:
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://{}".format(uri), 'payload': payload, } self.last_response = None try:
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: icon_encoded_string = base64.b64encode(icon_file.read()).decode('ascii')
python
{ "resource": "" }
q2725
WebOsClient.get_apps
train
def get_apps(self): """Return all apps.""" self.request(EP_GET_APPS) return
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
python
{ "resource": "" }
q2727
WebOsClient.get_services
train
def get_services(self): """Get all services.""" self.request(EP_GET_SERVICES) return
python
{ "resource": "" }
q2728
WebOsClient.get_software_info
train
def get_software_info(self): """Return the current software status."""
python
{ "resource": "" }
q2729
WebOsClient.get_inputs
train
def get_inputs(self): """Get all inputs.""" self.request(EP_GET_INPUTS) return
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
python
{ "resource": "" }
q2731
WebOsClient.get_volume
train
def get_volume(self): """Get the current volume.""" self.request(EP_GET_VOLUME) return
python
{ "resource": "" }
q2732
WebOsClient.get_channels
train
def get_channels(self): """Get all tv channels.""" self.request(EP_GET_TV_CHANNELS) return
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
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
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 like the followings, these nodes are attached to the parent node directly for later convenience. - There is only text element - There are only children elements each has unique keys among all :param elem: ET Element object or None :param container: callble to make a container object :param options: Keyword options - nspaces: A namespaces dict, {uri: prefix} or None - attrs, text, children: Tags for special nodes to keep XML info - merge_attrs: Merge attributes and mix with children nodes, and the
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 :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ tree = container() if root is None: return tree
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: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ if to_str is None: to_str = _to_str_fn(**options) if not anyconfig.utils.is_dict_like(obj): if parent is not None and obj: parent.text = to_str(obj) # Parent is a leaf text node. return parent # All attributes and text should be set already. options = _complement_tag_options(options)
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:
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 internally """ def construct_mapping(loader, node, deep=False): """Construct python object from yaml mapping node, based on :meth:`yaml.BaseConstructor.construct_mapping` in PyYAML (MIT). """ loader.flatten_mapping(node) if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructorError(None, None, msg,
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`
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): options = {} # yaml.safe_load does not process Loader opts. elif not options.get("Loader"): maybe_container = options.get("ac_dict", 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 = {} elif not options.get("Dumper", False) and _is_dict: # TODO: Any other way to get its constructor? maybe_container = options.get("ac_dict", type(data))
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 _split_path('/') == [''] # JSON Pointer spec expects this. >>> for p in ('/a', '.a', 'a', 'a.'): ... assert _split_path(p) == ['a'], p
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
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': {'c': 0, 'd': [1, 2]}}, '': 3} >>> assert get(d, '/') == (3, '') # key becomes '' (empty string). >>> assert get(d, "/a/b/c") == (0, '') >>> sorted(get(d, "a.b")[0].items()) [('c', 0), ('d', [1, 2])] >>> (get(d, "a.b.d"), get(d, "/a/b/d/1")) (([1, 2], ''), (2, '')) >>> get(d, "a.b.key_not_exist") # doctest: +ELLIPSIS (None, "'...'") >>> get(d, "/a/b/d/2") (None, 'list index out of range') >>> get(d, "/a/b/d/-") # doctest: +ELLIPSIS (None, 'list indices must be integers...')
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
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'.
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 -> vary depends on 'merge_lists'. see its description. :param other: a dict[-like] object or a list of (key, value) tuples :param key: key of mapping object to update :param val:
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'
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
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', '') >>> _parseline(" aaa:") ('aaa', '') >>> _parseline("aaa") ('aaa', '') >>> _parseline("url = http://localhost") ('url', 'http://localhost')
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.g. '#' (hash) >>> _pre_process_line('') is None True >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> _pre_process_line("# " + s0) is None
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 store properties :param comment_markers: Comment markers, e.g. '#' (hash) :return: Dict-like object holding properties >>> to_strm = anyconfig.compat.StringIO >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> load(to_strm('')) {} >>> load(to_strm("# " + s0)) {} >>> load(to_strm("! " + s0)) {} >>> load(to_strm("calendar.japanese.type:")) {'calendar.japanese.type': ''} >>> load(to_strm(s0))
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 add into template engine :return: Compiled result (str) >>> render_s("aaa") == "aaa" True >>> s = render_s('a = {{ a }}, b = "{{ b }}"', {'a': 1, 'b': 'bbb'}) >>> if SUPPORTED: ... assert s == 'a = 1, b = "bbb"' """
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' """
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 represents JMESPath expression. :return: Maybe queried result data, primitive (int, str, ...) or dict """ expression = options.get("ac_query", None) if expression is None or not expression: return data try: pexp = jmespath.compile(expression) return pexp.search(data) except ValueError
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, operator.itemgetter(1))
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
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')) >>> assert get_path_from_stream(anyconfig.compat.StringIO()) is None >>> get_path_from_stream(__file__) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...
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):
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))
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(fnc2() == ret2 for i in range(imax)) """ cache = dict()
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 will be changed to 'rb' or 'wb' if selected backend, xml and configobj for example, for given config file prefer that. :param options: Optional keyword arguments passed to the internal file opening APIs of each backends such like 'buffering' optional parameter passed to builtin 'open' function.
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 one. :param input\_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments such as: - Options common in :func:`single_load`, :func:`multi_load`, :func:`load` and :func:`loads`: - ac_dict: callable (function or class) to make mapping objects from loaded data if the selected backend can customize that such as JSON which supports that with 'object_pairs_hook' option, or None. If this option was not given or None, dict or :class:`collections.OrderedDict` will be used to make result as mapping object depends on if ac_ordered (see below) is True and selected backend can keep the order of items loaded. See also :meth:`_container_factory`
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 first argument 'inputs' may be a list of a file paths or a glob pattern specifying them or a pathlib.Path object represents file[s] or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. About glob patterns, for example, is, if a.yml, b.yml and c.yml are in the dir /etc/foo/conf.d/, the followings give same results:: multi_load(["/etc/foo/conf.d/a.yml", "/etc/foo/conf.d/b.yml", "/etc/foo/conf.d/c.yml", ]) multi_load("/etc/foo/conf.d/*.yml") :param inputs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from :param ac_parser: Forced parser type or parser object :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Mapping object presents context to instantiate template :param options: Optional keyword arguments:
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 represents some inputs. :param path_specs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. :param ac_parser: Forced parser type or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` and :func:`multi_load` :return: Mapping object or any query result might be primitive objects
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.IOInfo' object represents output to dump some data to. :param ac_parser: Forced parser type or parser object :param options:
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`
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 >>> parse_single("a string") 'a string' >>> parse_single('"a string"') 'a string' >>> parse_single("'a string'") 'a string' >>> parse_single("0.1") '0.1' >>> parse_single(" a string contains extra whitespaces ") 'a string contains extra whitespaces' """ if str_ is None:
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]
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 attributes """ for rel in parse_list(str_, as_sep): if
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 """
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))
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_level(args.loglevel)) if args.inputs: if '-' in args.inputs: args.inputs = sys.stdin else: if args.list: _show_psrs() elif args.env:
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 object) to validate :param schema: Schema object (a dict or a dict-like object) instantiated from schema JSON file or schema JSON string :param options: Other keyword options such as: - ac_schema_safe: Exception (jsonschema.ValidationError or jsonschema.SchemaError or others) will be thrown during validation process due to any validation or related errors. However, these will be catched by default, and will be re-raised if 'ac_safe' is False.
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_schema_typemap: Type to JSON schema type mappings :return: Another mapping objects represents JSON schema of items """
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)
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 a container object :param allow_primitives: True if the parser.load* may return objects of primitive data types other than
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: optional keyword parameters
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 = 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 #
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.
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:
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
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 :param kwargs: optional keyword parameters to be sanitized :: dict :raises IOError, OSError, AttributeError: When dump failed.
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
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 :return: Dict-like object holding
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' :return: container object holding the configuration data
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' :return: container object holding the configuration data
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 anyconfig.compat import pathlib >>> if pathlib is not None: ... assert guess_io_type(pathlib.Path(apath)) == IOI_PATH_OBJ >>> assert guess_io_type(open(__file__)) == IOI_STREAM >>> guess_io_type(1) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ... """ if obj is None:
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') >>> _parseline("aaa='bb b'") ('aaa', 'bb b') >>> _parseline('aaa="bb#b"') ('aaa', 'bb#b') >>> _parseline('aaa="bb\\"b"') ('aaa', 'bb"b') >>> _parseline("aaa=bbb # ccc") ('aaa', 'bbb') """ match = re.match(r"^\s*(export)?\s*(\S+)=(?:(?:" r"(?:\"(.*[^\\])\")|(?:'(.*[^\\])')|"
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 holding shell variables' definitions >>> from anyconfig.compat import StringIO as to_strm >>> load(to_strm('')) {} >>> load(to_strm("# ")) {} >>> load(to_strm("aaa=")) {'aaa': ''} >>> load(to_strm("aaa=bbb")) {'aaa': 'bbb'} >>> load(to_strm("aaa=bbb # ...")) {'aaa': 'bbb'} """
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
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
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,
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. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5) (0.75, 0.5, 0.25,
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:
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(0.25) (1.0, 0.75, 0.5, 1.0)
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.Color instances. >>> c1 = Color.NewFromRgb(1.0, 0.0, 0.0, alpha=1) >>> c2 = Color.NewFromRgb(0.0, 1.0, 0.0, alpha=0) >>> c1.Gradient(c2, 3) [(0.75, 0.25, 0.0, 0.75), (0.5, 0.5, 0.0, 0.5), (0.25, 0.75, 0.0, 0.25)] ''' gradient = [] rgba1 = self.__rgb + (self.__a,) rgba2 = target.__rgb + (target.__a,) steps += 1
python
{ "resource": "" }