_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 < len(lst) and length < before_context + 1 \ and not pred(lst[start + length]): length += 1 # Slide to the next match. while start + length < len(lst) and not pred(lst[start + length]): start += 1 # If there was no next match, abort here (it's easier # to do this than to try to detect this case later). if start + length == len(lst): break # Now extend repeatedly until we can't find anything. while start + length < len(lst) and pred(lst[start + length]): extendlength = 1 # Read in the 'after' context and see if it holds a URL. while extendlength < after_context + 1 and start + length + \ extendlength < len(lst) and \ not pred(lst[start + length + extendlength]): extendlength += 1 length += extendlength if start + length < len(lst) and not pred(lst[start + length]): # Didn't find a matching line, so we either # hit the end or extended to after_context + 1.. # # Now read in possible 'before' context # from the next URL; if we don't find one, # we discard the readahead. extendlength = 1 while extendlength < before_context and start + length + \ extendlength < len(lst) and \ not pred(lst[start + length + extendlength]): extendlength += 1 if start + length + extendlength < len(lst) and \ pred(lst[start + length + extendlength]): length += extendlength if length > 0 and start + length <= len(lst): if start == 0: usedfirst = True if start + length == len(lst): usedlast = True rval.append((lst[start:start + length], usedfirst, usedlast)) start += length length = 0 return rval
python
{ "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 # a URL are the only lines containing URLs. linechunks = [parse_text_urls(l) for l in lines] return extract_with_context(linechunks, lambda chunk: len(chunk) > 1 or (len(chunk) == 1 and chunk[0].url is not None), 1, 1)
python
{ "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 not None: return True return False return extract_with_context(chunk.rval, somechunkisurl, 1, 1)
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 message:\n{}\n{}".format(str(byt), err) except (AttributeError, UnicodeEncodeError): # If byt is already a string, just return it return byt return strg
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-ascii characters, # such as 8bit or binary, as these are encoded using raw-unicode-escape which # seems to prevent subsequent utf-8 decoding. cte = str(msg.get('content-transfer-encoding', '')).lower() decode = cte not in ("8bit", "7bit", "binary") res = msg.get_payload(decode=decode) return decode_bytes(res, enc)
python
{ "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": decoded = decode_msg(msg, enc) for chunk in extracturls(decoded): urlidx += 1 yield chunk elif msg.get_content_type() == "text/html": decoded = decode_msg(msg, enc) for chunk in extracthtmlurls(decoded): urlidx += 1 yield chunk
python
{ "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"] for search="mo", text="string more string" and attr="default" """ if search: pat = re.compile("({})".format(re.escape(search)), re.IGNORECASE) else: return text final = pat.split(text) final = [(attr, i) if i.lower() == search.lower() else i for i in final] return final
python
{ "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) self.loop.run()
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() elif self.help_menu is True: self._help_menu() return [] if k == 'up': # Works around bug where the up arrow goes higher than the top list # item and unintentionally triggers context and palette switches. # Remaps 'up' to 'k' keys[j] = 'k' if k == 'home': # Remap 'home' to 'g'. Works around small bug where 'home' takes the cursor # above the top list item. keys[j] = 'g' # filter backspace out before the widget, it has a weird interaction return [i for i in keys if i != 'backspace']
python
{ "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: self.search = False self.enter = False return if not self.urls and key not in "Qq": return # No other actions are useful with no URLs if self.help_menu is False: try: self.keys[key]() except KeyError: pass
python
{ "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 = \ self.items.index(self.items[max(int(self.number) - 1, 0)]) except IndexError: self.number = self.number[:-1] self.top.keypress(self.size, "") # Trick urwid into redisplaying the cursor if self.number: self._footer_start_thread("Selection: {}".format(self.number), 1)
python
{ "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(): grp[idx].set_text(splittext(item.text, self.search_string, 'search')) done = True if done is True: search_items.extend(grp) self.items = search_items self.top.body = urwid.ListBox(self.items) if self.items: self.top.body.focus_position = 2 if self.compact is False else 0 # Trick urwid into redisplaying the cursor self.top.keypress(self.tui.get_cols_rows(), "") self.no_matches = False else: self.no_matches = True footerwid = urwid.AttrMap(urwid.Text(text + " No Matches"), 'footer') self.top.footer = footerwid
python
{ "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'] except KeyError: pass else: del os.environ['BROWSER'] webbrowser.register(browser, None, webbrowser.GenericBrowser(browser)) try_idx = webbrowser._tryorder.index(browser) webbrowser._tryorder.insert(0, webbrowser._tryorder.pop(try_idx)) def browse(*args): # double ()() to ensure self.search evaluated at runtime, not when # browse() is _created_. [0] is self.search, [1] is self.enter # self.enter prevents opening URL when in search mode if self._get_search()[0]() is True: if self._get_search()[1]() is True: self.search = False self.enter = False elif not self.run: webbrowser.open(url) elif self.run and self.pipe: process = Popen(shlex.split(self.run), stdout=PIPE, stdin=PIPE) process.communicate(input=url.encode(sys.getdefaultencoding())) else: Popen(self.run.format(url), shell=True).communicate() size = self.tui.get_cols_rows() self.draw_screen(size) return browse
python
{ "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) \ or dedupe is False: urls.append(chunk.url) groupurls.append(chunk.url) # Collect all immediately adjacent # chunks with the same URL. tmpmarkup = [] if chunk.markup: tmpmarkup.append(('msgtext', chunk.markup)) while i < len(chunks) and \ chunks[i].url == chunk.url: if chunks[i].markup: tmpmarkup.append(chunks[i].markup) i += 1 url_idx = urls.index(chunk.url) + 1 if dedupe is True else len(urls) markup += [tmpmarkup or '<URL>', ('urlref:number:braces', ' ['), ('urlref:number', repr(url_idx)), ('urlref:number:braces', ']')] markup += '\n' if not usedlast: markup += [('msgtext:ellipses', '...\n\n')] items.append(urwid.Text(markup)) i = len(urls) - len(groupurls) for url in groupurls: i += 1 markup = [(6, urwid.Text([('urlref:number:braces', '['), ('urlref:number', repr(i)), ('urlref:number:braces', ']'), ' '])), urwid.AttrMap(urwid.Button(shorten_url(url, cols, shorten), self.mkbrowseto(url), user_data=url), 'urlref:url', 'url:sel')] items.append(urwid.Columns(markup)) return items, urls
python
{ "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.getcwd(), KEY_FILE_NAME)
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() if raw_data: key_dict = json.loads(raw_data) logger.debug('getting client_key for %s from %s', self.ip, key_file_path); if self.ip in key_dict: self.client_key = key_dict[self.ip]
python
{ "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: raw_data = f.read() key_dict = {} if raw_data: key_dict = json.loads(raw_data) key_dict[self.ip] = self.client_key f.write(json.dumps(key_dict))
python
{ "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 \ response['payload']['pairingType'] == 'PROMPT': raw_response = yield from websocket.recv() response = json.loads(raw_response) if response['type'] == 'registered': self.client_key = response['payload']['client-key'] self.save_key_file()
python
{ "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 logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) finally: logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
python
{ "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: logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) if not self.client_key: raise PyLGTVPairException("Unable to pair") yield from websocket.send(json.dumps(msg)) if msg['type'] == 'request': raw_response = yield from websocket.recv() self.last_response = json.loads(raw_response) finally: logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
python
{ "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: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(asyncio.wait_for(self._command(message), self.timeout_connect, loop=loop)) finally: loop.close()
python
{ "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') self.request(EP_SHOW_MESSAGE, { 'message': message, 'iconData': icon_encoded_string, 'iconExtension': icon_extension })
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 like the followings, these nodes are attached to the parent node directly for later convenience. - There is only text element - There are only children elements each has unique keys among all :param elem: ET Element object or None :param container: callble to make a container object :param options: Keyword options - nspaces: A namespaces dict, {uri: prefix} or None - attrs, text, children: Tags for special nodes to keep XML info - merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation. """ dic = container() if elem is None: return dic elem.tag = _tweak_ns(elem.tag, **options) # {ns}tag -> ns_prefix:tag subdic = dic[elem.tag] = container() options["container"] = container if elem.text: _process_elem_text(elem, dic, subdic, **options) if elem.attrib: _process_elem_attrs(elem, dic, subdic, **options) if len(elem): _process_children_elems(elem, dic, subdic, **options) elif not elem.text and not elem.attrib: # ex. <tag/>. dic[elem.tag] = None return dic
python
{ "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 if nspaces is not None: for uri, prefix in nspaces.items(): root.attrib["xmlns:" + prefix if prefix else "xmlns"] = uri return elem_to_container(root, container=container, nspaces=nspaces, **_complement_tag_options(options))
python
{ "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) (attrs, text, children) = operator.itemgetter(*_ATC)(options) for key, val in anyconfig.compat.iteritems(obj): if key == attrs: _elem_set_attrs(val, parent, to_str) elif key == text: parent.text = to_str(val) elif key == children: for celem in _elem_from_descendants(val, **options): parent.append(celem) else: parent = _get_or_update_parent(key, val, to_str, parent=parent, **options) return ET.ElementTree(parent)
python
{ "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(stream, encoding="unicode", xml_declaration=True)
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, node.start_mark) mapping = container() for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: eargs = ("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) raise yaml.constructor.ConstructorError(*eargs) value = loader.construct_object(value_node, deep=deep) mapping[key] = value return mapping tag = "tag:yaml.org,2002:python/unicode" def construct_ustr(loader, node): """Unicode string constructor""" return loader.construct_scalar(node) try: loader.add_constructor(tag, construct_ustr) except NameError: pass if type(container) != dict: loader.add_constructor(mapping_tag, construct_mapping) return loader
python
{ "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 options: keyword args may contain "ac_safe" to load/dump safely """ key = "ac_safe" fnc = getattr(yaml, r"safe_" + fname if options.get(key) else fname) return fnc(*args, **common.filter_from_options(key, options))
python
{ "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) if maybe_container and callable(maybe_container): container = maybe_container options["Loader"] = _customized_loader(container) ret = yml_fnc("load", stream, **common.filter_from_options("ac_dict", options)) if ret is None: return container() return ret
python
{ "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)) options["Dumper"] = _customized_dumper(maybe_container) if _is_dict: # Type information and the order of items are lost on dump currently. data = anyconfig.dicts.convert_to(data, ac_dict=dict) options = common.filter_from_options("ac_dict", options) return yml_fnc("dump", data, stream, **options)
python
{ "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 >>> assert _split_path('/a/b/c') == _split_path('a.b.c') == ['a', 'b', 'c'] >>> assert _split_path('abc') == ['abc'] """ if not path: return [] for sep in seps: if sep in path: if path == sep: # Special case, '/' or '.' only. return [''] return [x for x in path.split(sep) if x] return [path]
python
{ "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) {'a': {'b': {'c': 1}}} """ ret = None for key in reversed(_split_path(path, seps)): ret = {key: val if ret is None else ret.copy()} return ret
python
{ "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...') """ items = [_jsnp_unescape(p) for p in _split_path(path, seps)] if not items: return (dic, '') try: if len(items) == 1: return (dic[items[0]], '') prnt = functools.reduce(operator.getitem, items[:-1], dic) arr = anyconfig.utils.is_list_like(prnt) and idx_reg.match(items[-1]) return (prnt[int(items[-1])], '') if arr else (prnt[items[-1]], '') except (TypeError, KeyError, IndexError) as exc: return (None, str(exc))
python
{ "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) >>> d['a']['b']['d'] 3 """ merge(dic, mk_nested_dic(path, val, seps), ac_merge=MS_DICTS)
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' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated """ self[key] = other[key] if val is None else val
python
{ "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: value to update self[key] :param merge_lists: Merge not only dicts but also lists. For example, [1, 2, 3], [3, 4] ==> [1, 2, 3, 4] [1, 2, 2], [2, 4] ==> [1, 2, 2, 4] :return: None but 'self' will be updated """ if val is None: val = other[key] if key in self: val0 = self[key] # Original value if anyconfig.utils.is_dict_like(val0): # It needs recursive updates. merge(self[key], val, merge_lists=merge_lists, **options) elif merge_lists and _are_list_like(val, val0): _merge_list(self, key, val) else: _merge_other(self, key, val) else: self[key] = val
python
{ "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 self alternatively :return: None but 'self' will be updated """ _update_with_merge(self, other, key, val=val, merge_lists=True, **options)
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 _MERGE_FNS[strategy] except KeyError: if callable(strategy): return strategy raise ValueError("Wrong merge strategy: %r" % strategy)
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') >>> _parseline("calendar.japanese.type: LocalGregorianCalendar") ('calendar.japanese.type', 'LocalGregorianCalendar') """ pair = re.split(r"(?:\s+)?(?:(?<!\\)[=:])", line.strip(), 1) key = pair[0].rstrip() if len(pair) < 2: LOGGER.warning("Invalid line found: %s", line) return (key or None, '') return (key, pair[1].strip())
python
{ "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 True >>> _pre_process_line("! " + s0) is None True >>> _pre_process_line(s0 + "# comment") 'calendar.japanese.type: LocalGregorianCalendar# comment' """ if not line: return None if any(c in line for c in comment_markers): if line.startswith(comment_markers): return None return line
python
{ "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)) {'calendar.japanese.type': 'LocalGregorianCalendar'} >>> load(to_strm(s0 + "# ...")) {'calendar.japanese.type': 'LocalGregorianCalendar# ...'} >>> s1 = r"key=a\\:b" >>> load(to_strm(s1)) {'key': 'a:b'} >>> s2 = '''application/postscript: \\ ... x=Postscript File;y=.eps,.ps ... ''' >>> load(to_strm(s2)) {'application/postscript': 'x=Postscript File;y=.eps,.ps'} """ ret = container() prev = "" for line in stream.readlines(): line = _pre_process_line(prev + line.strip().rstrip(), comment_markers) # I don't think later case may happen but just in case. if line is None or not line: continue prev = "" # re-initialize for later use. if line.endswith("\\"): prev += line.rstrip(" \\") continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Failed to parse the line: %s", line) continue ret[key] = unescape(val) return ret
python
{ "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"' """ if paths is None: paths = [os.curdir] env = tmpl_env(paths) if env is None: return tmpl_s if filters is not None: env.filters.update(filters) if ctx is None: ctx = {} return tmpl_env(paths).from_string(tmpl_s).render(**ctx)
python
{ "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 represents JMESPath expression. :return: Maybe queried result data, primitive (int, str, ...) or dict """ expression = options.get("ac_query", None) if expression is None or not expression: return data try: pexp = jmespath.compile(expression) return pexp.search(data) except ValueError as exc: # jmespath.exceptions.*Error inherit from it. LOGGER.warning("Failed to compile or search: exp=%s, exc=%r", expression, exc) except (NameError, AttributeError): LOGGER.warning("Filter module (jmespath) is not available. " "Do nothing.") return data
python
{ "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)) >>> [(key, tuple(grp)) for key, grp in res] [(-1, (('b', -1),)), (1, (('a', 1), ('c', 1)))] """ return itertools.groupby(sorted(itr, key=key_fn), key=key_fn)
python
{ "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_paths) and all(is_path(p) or is_ioinfo(p) for p in maybe_paths)))
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: ... """ if not is_file_stream(strm): raise ValueError("Given object does not look a file/file-like " "object: %r" % strm) path = getattr(strm, "name", None) if path is not None: try: return normpath(path) except (TypeError, ValueError): pass return None
python
{ "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): return obj.suffix[1:] elif is_file_stream(obj): try: path = get_path_from_stream(obj) except ValueError: return None elif is_ioinfo(obj): path = obj.path else: return None if path: return get_file_extension(path) return None
python
{ "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(bbb=2)) {} """ return dict((k, options[k]) for k in keys if k in options)
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() @functools.wraps(fnc) def wrapped(*args, **kwargs): """Decorated one""" key = repr(args) + repr(kwargs) if key not in cache: cache[key] = fnc(*args, **kwargs) return cache[key] return wrapped
python
{ "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. :return: A file object or None on any errors :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ psr = find(path, forced_type=ac_parser) if mode is not None and mode.startswith('w'): return psr.wopen(path, **options) return psr.ropen(path, **options)
python
{ "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` of :class:`anyconfig.backend.base.Parser` for more implementation details. - ac_ordered: True if you want to keep resuls ordered. Please note that order of items may be lost depends on the selected backend. - ac_schema: JSON schema file path to validate given config file - ac_query: JMESPath expression to query data - Common backend options: - ac_ignore_missing: Ignore and just return empty result if given file 'input\_' does not exist actually. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ cnf = _single_load(input_, ac_parser=ac_parser, ac_template=ac_template, ac_context=ac_context, **options) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
python
{ "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: - ac_dict, ac_ordered, ac_schema and ac_query are the options common in :func:`single_load`, :func:`multi_load`, :func:`load`: and :func:`loads`. See the descriptions of them in :func:`single_load`. - Options specific to this function and :func:`load`: - ac_merge (merge): Specify strategy of how to merge results loaded from multiple configuration files. See the doc of :mod:`anyconfig.dicts` for more details of strategies. The default is anyconfig.dicts.MS_DICTS. - ac_marker (marker): Globbing marker to detect paths patterns. - Common backend options: - ignore_missing: Ignore and just return empty result if given file 'path' does not exist. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) options["ac_schema"] = None # Avoid to load schema more than twice. paths = anyconfig.utils.expand_paths(inputs, marker=marker) if anyconfig.utils.are_same_file_types(paths): ac_parser = find(paths[0], forced_type=ac_parser) cnf = ac_context for path in paths: opts = options.copy() cups = _single_load(path, ac_parser=ac_parser, ac_template=ac_template, ac_context=cnf, **opts) if cups: if cnf is None: cnf = cups else: merge(cnf, cups, **options) if cnf is None: return anyconfig.dicts.convert_to({}, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
python
{ "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 :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) if anyconfig.utils.is_path_like_object(path_specs, marker): return single_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options) if not anyconfig.utils.is_paths(path_specs, marker): raise ValueError("Possible invalid input %r" % path_specs) return multi_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options)
python
{ "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: Backend specific optional arguments, e.g. {"indent": 2} for JSON loader/dumper backend :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ ioi = anyconfig.ioinfo.make(out) psr = find(ioi, forced_type=ac_parser) LOGGER.info("Dumping: %s", ioi.path) psr.dump(data, ioi, **options)
python
{ "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 the given data :raises: ValueError, UnknownProcessorTypeError """ psr = find(None, forced_type=ac_parser) return psr.dumps(data, **options)
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: return '' str_ = str_.strip() if not str_: return '' if BOOL_PATTERN.match(str_) is not None: return bool(str_) if INT_PATTERN.match(str_) is not None: return int(str_) if STR_PATTERN.match(str_) is not None: return str_[1:-1] return str_
python
{ "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") ['a', 'b'] >>> parse_list("1,2") [1, 2] >>> parse_list("a,b,") ['a', 'b'] """ return [parse_single(x) for x in str_.split(sep) if x]
python
{ "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 avs_sep not in rel or rel.endswith(avs_sep): continue (_attr, _values) = parse_list(rel, avs_sep) if vs_sep in str(_values): _values = parse_list(_values, vs_sep) if _values: yield (_attr, _values)
python
{ "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.list_by_extension()] exts = "File extensions:" + sep + sep.join(x_vs_ps) _exit_with_output(sep.join([types, exts, cids]))
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: cnf = os.environ.copy() _output_result(cnf, args.output, args.otype or "json", None, None) sys.exit(0) else: parser.print_usage() sys.exit(1) if args.validate and args.schema is None: _exit_with_output("--validate option requires --scheme option", 1) return args
python
{ "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. - ac_schema_errors: Lazily yield each of the validation errors and returns all of them if validation fails. :return: (True if validation succeeded else False, error message[s]) """ if not JSONSCHEMA_IS_AVAIL: return (True, _NA_MSG) options = anyconfig.utils.filter_options(("cls", ), options) if ac_schema_errors: return _validate_all(data, schema, **options) return _validate(data, schema, ac_schema_safe, **options)
python
{ "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 """ (typemap, strict) = _process_options(**options) arr = list(arr) scm = dict(type=typemap[list], items=gen_schema(arr[0] if arr else "str", **options)) if strict: nitems = len(arr) scm["minItems"] = nitems scm["uniqueItems"] = len(set(arr)) == nitems return scm
python
{ "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(outdir)
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 mapping types such like JSON parser :param options: keyword options passed to 'load_fn' :return: container object holding data """ ret = load_fn(content_or_strm, **options) if anyconfig.utils.is_dict_like(ret): return container() if (ret is None or not ret) else container(ret) return ret if allow_primitives else container(ret)
python
{ "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 :return: String represents data if stream is None or None """ if stream is None: return dump_fn(data, **options) return dump_fn(data, stream, **options)
python
{ "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 # Higher priority than ac_ordered. if _dicts and callable(_dicts[0]): return _dicts[0] if self.ordered() and options.get("ac_ordered", False): return anyconfig.compat.OrderedDict return dict
python
{ "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 self.dict_options(): options.setdefault(opt, container) return anyconfig.utils.filter_options(self._load_opts, options)
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 :return: Dict-like object holding config parameters """ _not_implemented(self, content, container, **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 :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters """ _not_implemented(self, stream, container, **kwargs)
python
{ "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/ :func:`anyconfig.utils.filter_options` later to filter out options not in _load_opts. :return: dict or dict-like object holding configurations """ container = self._container_factory(**options) if not content or content is None: return container() options = self._load_options(container, **options) return self.load_from_string(content, container, **options)
python
{ "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. """ kwargs = anyconfig.utils.filter_options(self._dump_opts, kwargs) if anyconfig.utils.is_stream_ioinfo(ioi): self.dump_to_stream(cnf, ioi.src, **kwargs) else: ensure_outdir_exists(ioi.path) self.dump_to_path(cnf, ioi.path, **kwargs)
python
{ "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 :return: Dict-like object holding config parameters """ return self.load_from_string(stream.read(), container, **kwargs)
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 config parameters """ return self.load_from_stream(anyconfig.compat.StringIO(content), container, **kwargs)
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 """ return load_with_fn(self._load_from_string_fn, content, container, allow_primitives=self.allow_primitives(), **options)
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 """ return load_with_fn(self._load_from_stream_fn, stream, container, allow_primitives=self.allow_primitives(), **options)
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: return IOI_NONE if anyconfig.utils.is_path(obj): return IOI_PATH_STR if anyconfig.utils.is_path_obj(obj): return IOI_PATH_OBJ if anyconfig.utils.is_file_stream(obj): return IOI_STREAM raise ValueError("Unknown I/O type object: %r" % obj)
python
{ "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"(?:\"(.*[^\\])\")|(?:'(.*[^\\])')|" r"(?:([^\"'#\s]+)))?)\s*#*", line) if not match: LOGGER.warning("Invalid line found: %s", line) return (None, None) tpl = match.groups() vals = list(itertools.dropwhile(lambda x: x is None, tpl[2:])) return (tpl[1], vals[0] if vals else '')
python
{ "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'} """ ret = container() for line in stream.readlines(): line = line.rstrip() if line is None or not line: continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Empty val in the line: %s", line) continue ret[key] = val return ret
python
{ "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 """ for key, val in anyconfig.compat.iteritems(cnf): stream.write("%s='%s'%s" % (key, val, os.linesep))
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. """ return Color("cmyk", c, m, y, k)
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(30, 1, 0.5).ColorWithHue(60).hsl (60, 1, 0.5) ''' h, s, l = self.__hsl return Color((hue, s, l), 'hsl', self.__a, self.__wref)
python
{ "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, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5).hsl (30, 0.5, 0.5) ''' h, s, l = self.__hsl return Color((h, saturation, l), 'hsl', self.__a, self.__wref)
python
{ "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, 0.25, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25).hsl (30, 1, 0.25) ''' h, s, l = self.__hsl return Color((h, s, lightness), 'hsl', self.__a, self.__wref)
python
{ "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) >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25).hsl (30, 1, 0.75) ''' h, s, l = self.__hsl return Color((h, s, min(l + level, 1)), 'hsl', self.__a, self.__wref)
python
{ "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 for n in range(1, steps): d = 1.0*n/steps r = (rgba1[0]*(1-d)) + (rgba2[0]*d) g = (rgba1[1]*(1-d)) + (rgba2[1]*d) b = (rgba1[2]*(1-d)) + (rgba2[2]*d) a = (rgba1[3]*(1-d)) + (rgba2[3]*d) gradient.append(Color((r, g, b), 'rgb', a, self.__wref)) return gradient
python
{ "resource": "" }