docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Try to get the generated file. Args: text: The text that you want to generate.
def generate(self, text): if not text: raise Exception("No text to speak") if len(text) >= self.MAX_CHARS: raise Exception("Number of characters must be less than 2000") params = self.__params.copy() params["text"] = text self._data = requests.get(self.TTS_URL, params=params, stream=False).iter_content()
943,359
Save data in file. Args: path (optional): A path to save file. Defaults to "speech". File extension is optional. Absolute path is allowed. Returns: The path to the saved file.
def save(self, path="speech"): if self._data is None: raise Exception("There's nothing to save") extension = "." + self.__params["format"] if os.path.splitext(path)[1] != extension: path += extension with open(path, "wb") as f: for d in self._data: f.write(d) return path
943,360
Parse HTTP headers. Args: msg (str): HTTP message. Returns: (List[Tuple[str, str]): List of header tuples.
def parse_headers(cls, msg): return list(email.parser.Parser().parsestr(msg).items())
943,408
Send request to a given address via given transport. Args: transport (asyncio.DatagramTransport): Write transport to send the message on. addr (Tuple[str, int]): IP address and port pair to send the message to.
def sendto(self, transport, addr): msg = bytes(self) + b'\r\n' logger.debug("%s:%s < %s", *(addr + (self,))) transport.sendto(msg, addr)
943,414
Set up a unicode character. Arguments: unicodeHexValue -- an integer that should correspond to a Unicode code point. block -- the CharacterBlock this character belongs to. Raises: ValueError -- if unicodeHexValue is not a valid code point.
def __init__(self, unicodeHexValue, block): if unicodeHexValue < 0 or unicodeHexValue > 0x10FFFF: raise (ValueError, "numeric value outside Unicode range") self.unicodeHexValue = unicodeHexValue self.chr = chr(self.unicodeHexValue) self.name = unicodedata.name(self.chr) self.equivalents = {} self._block = block
943,485
Returns the set of codepoints contained in a given Namelist file. This is a replacement CodepointsInSubset and implements the "#$ include" header format. Args: namFilename: The path to the Namelist file. unique_glyphs: Optional, whether to only include glyphs unique to subset. Returns: A set containing the glyphs in the subset.
def codepointsInNamelist(namFilename, unique_glyphs=False, cache=None): key = 'charset' if not unique_glyphs else 'ownCharset' internals_dir = os.path.dirname(os.path.abspath(__file__)) target = os.path.join(internals_dir, namFilename) result = readNamelist(target, unique_glyphs, cache) return result[key]
944,863
Override the views class' supported formats for the decorated function. Arguments: formats -- A list of strings describing formats, e.g. ``['html', 'json']``.
def override_supported_formats(formats): def decorator(function): @wraps(function) def wrapper(self, *args, **kwargs): self.supported_formats = formats return function(self, *args, **kwargs) return wrapper return decorator
945,103
Find and return a serializer for the given format. Arguments: format -- A Format instance.
def find(format): try: serializer = SERIALIZERS[format] except KeyError: raise UnknownSerializer('No serializer found for %s' % format.acronym) return serializer
945,133
Given a list of boards, return :class:`basc_py4chan.Board` objects. Args: board_name_list (list): List of board names to get, eg: ['b', 'tg'] Returns: dict of :class:`basc_py4chan.Board`: Requested boards.
def get_boards(board_name_list, *args, **kwargs): if isinstance(board_name_list, basestring): board_name_list = board_name_list.split() return [Board(name, *args, **kwargs) for name in board_name_list]
945,531
Creates a :mod:`basc_py4chan.Board` object. Args: board_name (string): Name of the board, such as "tg" or "etc". https (bool): Whether to use a secure connection to 4chan. session: Existing requests.session object to use instead of our current one.
def __init__(self, board_name, https=False, session=None): self._board_name = board_name self._https = https self._protocol = 'https://' if https else 'http://' self._url = Url(board_name=board_name, https=self._https) self._requests_session = session or requests.session() self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__ self._thread_cache = {}
945,533
Get a thread from 4chan via 4chan API. Args: thread_id (int): Thread ID update_if_cached (bool): Whether the thread should be updated if it's already in our cache raise_404 (bool): Raise an Exception if thread has 404'd Returns: :class:`basc_py4chan.Thread`: Thread object
def get_thread(self, thread_id, update_if_cached=True, raise_404=False): # see if already cached cached_thread = self._thread_cache.get(thread_id) if cached_thread: if update_if_cached: cached_thread.update() return cached_thread res = self._requests_session.get( self._url.thread_api_url( thread_id = thread_id ) ) # check if thread exists if raise_404: res.raise_for_status() elif not res.ok: return None thread = Thread._from_request(self, res, thread_id) self._thread_cache[thread_id] = thread return thread
945,535
Check if a thread exists or has 404'd. Args: thread_id (int): Thread ID Returns: bool: Whether the given thread exists on this board.
def thread_exists(self, thread_id): return self._requests_session.head( self._url.thread_api_url( thread_id=thread_id ) ).ok
945,536
Download web pages or images from search result links. Args: dir_path (str): Path of directory to save downloads of :class:`api.results`.links
def download_links(self, dir_path): links = self.links if not path.exists(dir_path): makedirs(dir_path) for i, url in enumerate(links): if 'start' in self.cseargs: i += int(self.cseargs['start']) ext = self.cseargs['fileType'] ext = '.html' if ext == '' else '.' + ext file_name = self.cseargs['q'].replace(' ', '_') + '_' + str(i) + ext file_path = path.join(dir_path, file_name) r = requests.get(url, stream=True) if r.status_code == 200: with open(file_path, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f)
945,883
Get a list of values from the key value metadata attribute. Args: k (str): Key in :class:`api.results`.metadata v (str): Values from each item in the key of :class:`api.results`.metadata Returns: A list containing all the ``v`` values in the ``k`` key for the :class:`api.results`.metadata attribute.
def get_values(self, k, v): metadata = self.metadata values = [] if metadata != None: if k in metadata: for metav in metadata[k]: if v in metav: values.append(metav[v]) return values
945,884
Print a preview of the search results. Args: n (int): Maximum number of search results to preview k (str): Key in :class:`api.results`.metadata to preview kheader (str): Key in :class:`api.results`.metadata[``k``] to use as the header klink (str): Key in :class:`api.results`.metadata[``k``] to use as the link if image search kdescription (str): Key in :class:`api.results`.metadata[``k``] to use as the description
def preview(self, n=10, k='items', kheader='displayLink', klink='link', kdescription='snippet'): if 'searchType' in self.cseargs: searchType = self.cseargs['searchType'] else: searchType = None items = self.metadata[k] # (cse_print) Print results for i, kv in enumerate(items[:n]): if 'start' in self.cseargs: i += int(self.cseargs['start']) # (print_header) Print result header header = '\n[' + str(i) + '] ' + kv[kheader] print(header) print('=' * len(header)) # (print_image) Print result image file if searchType == 'image': link = '\n' + path.basename(kv[klink]) print(link) # (print_description) Print result snippet description = '\n' + kv[kdescription] print(description)
945,885
Saves a text file of the search result links. Saves a text file of the search result links, where each link is saved in a new line. An example is provided below:: http://www.google.ca http://www.gmail.com Args: file_path (str): Path to the text file to save links to.
def save_links(self, file_path): data = '\n'.join(self.links) with open(file_path, 'w') as out_file: out_file.write(data)
945,886
Saves a json file of the search result metadata. Saves a json file of the search result metadata from :class:`api.results`.metadata. Args: file_path (str): Path to the json file to save metadata to.
def save_metadata(self, file_path): data = self.metadata with open(file_path, 'w') as out_file: json.dump(data, out_file)
945,887
Fetch new posts from the server. Arguments: force (bool): Force a thread update, even if thread has 404'd. Returns: int: How many new posts have been fetched.
def update(self, force=False): # The thread has already 404'ed, this function shouldn't do anything anymore. if self.is_404 and not force: return 0 if self._last_modified: headers = {'If-Modified-Since': self._last_modified} else: headers = None # random connection errors, just return 0 and try again later try: res = self._board._requests_session.get(self._api_url, headers=headers) except: # try again later return 0 # 304 Not Modified, no new posts. if res.status_code == 304: return 0 # 404 Not Found, thread died. elif res.status_code == 404: self.is_404 = True # remove post from cache, because it's gone. self._board._thread_cache.pop(self.id, None) return 0 elif res.status_code == 200: # If we somehow 404'ed, we should put ourself back in the cache. if self.is_404: self.is_404 = False self._board._thread_cache[self.id] = self # Remove self.want_update = False self.omitted_images = 0 self.omitted_posts = 0 self._last_modified = res.headers['Last-Modified'] posts = res.json()['posts'] original_post_count = len(self.replies) self.topic = Post(self, posts[0]) if self.last_reply_id and not force: self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id) else: self.replies[:] = [Post(self, p) for p in posts[1:]] new_post_count = len(self.replies) post_count_delta = new_post_count - original_post_count if not post_count_delta: return 0 self.last_reply_id = self.replies[-1].post_number return post_count_delta else: res.raise_for_status()
946,136
Return the flux of Cas A given a frequency and the year of observation. Based on the formula given in Baars et al., 1977. Parameters: freq - Observation frequency in MHz. year - Year of observation. May be floating-point. Returns: s, flux in Jy.
def cas_a (freq_mhz, year): # The snu rule is right out of Baars et al. The dnu is corrected # for the frequency being measured in MHz, not GHz. snu = 10. ** (5.745 - 0.770 * np.log10 (freq_mhz)) # Jy dnu = 0.01 * (0.07 - 0.30 * np.log10 (freq_mhz)) # percent per yr. loss = (1 - dnu) ** (year - 1980.) return snu * loss
946,149
Lookup value for a PluginOption instance Args: po: PluginOption Returns: converted value
def get(self, po): name = po.name typ = po.typ default = po.default handler = getattr(self, '_get_{}'.format(typ), None) if handler is None: raise ValueError(typ) self.seen.add(name) # pylint: disable=not-callable if not self.parser.has_option(self.section, name): if default is REQUIRED: raise NameError(self.section, name) if isinstance(default, INHERIT_GLOBAL): return handler('global', name, default.default) # don't return default here, give the handler a chance to modify # the default, e.g. pw_uid with default='root' returns 0. return handler(self.section, name, default)
946,572
Get term objects Args: term, str: A term in the retina (optional) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: Max results per page (optional) Returns: list of Term Raises: CorticalioException: if the request was not successful
def getTerms(self, term=None, getFingerprint=None, startIndex=0, maxResults=10): return self._terms.getTerm(self._retina, term, getFingerprint, startIndex, maxResults)
947,024
Get the contexts for a given term Args: term, str: A term in the retina (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: Max results per page (optional) Returns: list of Context Raises: CorticalioException: if the request was not successful
def getContextsForTerm(self, term, getFingerprint=None, startIndex=0, maxResults=5): return self._terms.getContextsForTerm(self._retina, term, getFingerprint, startIndex, maxResults)
947,025
Get tokenized input text Args: body, str: The text to be tokenized (required) POStags, str: Specify desired POS types (optional) Returns: list of str Raises: CorticalioException: if the request was not successful
def getTokensForText(self, body, POStags=None): return self._text.getTokensForText(self._retina, body, POStags)
947,027
Get a list of slices of the text Args: body, str: The text to be evaluated (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: Max results per page (optional) Returns: list of Text Raises: CorticalioException: if the request was not successful
def getSlicesForText(self, body, getFingerprint=None, startIndex=0, maxResults=10): return self._text.getSlicesForText(self._retina, body, getFingerprint, startIndex, maxResults)
947,028
Bulk get Fingerprint for text. Args: strings, list(str): A list of texts to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: list of Fingerprint Raises: CorticalioException: if the request was not successful
def getFingerprintsForTexts(self, strings, sparsity=1.0): body = [{"text": s} for s in strings] return self._text.getRepresentationsForBulkText(self._retina, json.dumps(body), sparsity)
947,029
Resolve an expression Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: Fingerprint Raises: CorticalioException: if the request was not successful
def getFingerprintForExpression(self, body, sparsity=1.0): return self._expressions.resolveExpression(self._retina, body, sparsity)
947,030
Bulk resolution of expressions Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: list of Fingerprint Raises: CorticalioException: if the request was not successful
def getFingerprintsForExpressions(self, body, sparsity=1.0): return self._expressions.resolveBulkExpression(self._retina, body, sparsity)
947,033
Get a classifier filter (fingerprint) for positive and negative text samples Args: filterName, str: A unique name for the filter. (required) positiveExamples, list(str): The list of positive example texts. (required) negativeExamples, list(str): The list of negative example texts. (optional) Returns: CategoryFilter Raises: CorticalioException: if the request was not successful
def createCategoryFilter(self, filterName, positiveExamples, negativeExamples=[]): samples = {"positiveExamples": [{"text": s} for s in positiveExamples], "negativeExamples": [{"text": s} for s in negativeExamples]} body = json.dumps(samples) return self._classify.createCategoryFilter(self._retina, filterName, body)
947,039
Get the contexts for a given term Args: retina_name, str: The retina name (required) term, str: A term in the retina (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) start_index, int: The start-index for pagination (optional) (optional) max_results, int: Max results per page (optional) (optional) Returns: Array[Context]
def getContextsForTerm(self, retina_name, term, get_fingerprint=None, start_index=0, max_results=5): resourcePath = '/terms/contexts' method = 'GET' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['term'] = term queryParams['start_index'] = start_index queryParams['max_results'] = max_results queryParams['get_fingerprint'] = get_fingerprint response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return [context.Context(**r) for r in response.json()]
947,040
get filter for classifier Args: filter_name, str: A unique name for the filter. (required) body, FilterTrainingObject: The list of positive and negative (optional) example items. (required) retina_name, str: The retina name (required) Returns: CategoryFilter
def createCategoryFilter(self, retina_name, filter_name, body, ): resourcePath = '/classify/create_category_filter' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['filter_name'] = filter_name postData = body response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return category_filter.CategoryFilter(**response.json())
947,042
Get a list of keywords from the text Args: retina_name, str: The retina name (required) body, str: The text to be evaluated (required) Returns: Array[str]
def getKeywordsForText(self, retina_name, body, ): resourcePath = '/text/keywords' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name postData = body response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return response.json()
947,055
Get a list of slices of the text Args: retina_name, str: The retina name (required) body, str: The text to be evaluated (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) start_index, int: The start-index for pagination (optional) (optional) max_results, int: Max results per page (optional) (optional) Returns: Array[Text]
def getSlicesForText(self, retina_name, body, get_fingerprint=None, start_index=0, max_results=10): resourcePath = '/text/slices' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['start_index'] = start_index queryParams['max_results'] = max_results queryParams['get_fingerprint'] = get_fingerprint postData = body response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return [text.Text(**r) for r in response.json()]
947,056
Detect the language of a text Args: body, str: Your input text (UTF-8) (required) Returns: LanguageRest
def getLanguage(self, body, ): resourcePath = '/text/detect_language' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None postData = body response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return language_rest.LanguageRest(**response.json())
947,057
Bulk compare Args: retina_name, str: The retina name (required) body, ExpressionOperation: Bulk comparison of elements 2 by 2 (required) Returns: Array[Metric]
def compareBulk(self, retina_name, body): resourcePath = '/compare/bulk' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name postData = body response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return [metric.Metric(**r) for r in response.json()]
947,083
Information about retinas Args: retina_name, str: The retina name (optional) (optional) Returns: Array[Retina]
def getRetinas(self, retina_name=None): resourcePath = '/retinas' method = 'GET' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return [retina.Retina(**r) for r in response.json()]
947,084
Get the similar terms for a given text or fingerprint Args: textOrFingerprint, str OR list of integers Returns: list of str: the 20 most similar terms Raises: CorticalioException: if the request was not successful
def getSimilarTerms(self, textOrFingerprint): expression = self._createDictionary(textOrFingerprint) terms = self._fullClient.getSimilarTermsForExpression(json.dumps(expression), maxResults=20) return [t.term for t in terms]
947,110
Get the semantic fingerprint of the input text. Args: text, str: The text to be evaluated Returns: list of str: the positions of the semantic fingerprint Raises: CorticalioException: if the request was not successful
def getFingerprint(self, text): fp = self._fullClient.getFingerprintForText(text) return fp.positions
947,111
Returns the semantic similarity of texts or fingerprints. Each argument can be eiter a text or a fingerprint. Args: textOrFingerprint1, str OR list of integers textOrFingerprint2, str OR list of integers Returns: float: the semantic similarity in the range [0;1] Raises: CorticalioException: if the request was not successful
def compare(self, textOrFingerprint1, textOrFingerprint2): compareList = [self._createDictionary(textOrFingerprint1), self._createDictionary(textOrFingerprint2)] metric = self._fullClient.compare(json.dumps(compareList)) return metric.cosineSimilarity
947,112
Creates a filter fingerprint. Args: positiveExamples, list(str): The list of positive example texts. Returns: list of int: the positions representing the filter representing the texts Raises: CorticalioException: if the request was not successful
def createCategoryFilter(self, positiveExamples): categoryFilter = self._fullClient.createCategoryFilter("CategoryFilter", positiveExamples) return categoryFilter.positions
947,113
Resolve an expression Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON formatted encoded to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: Fingerprint
def resolveExpression(self, retina_name, body, sparsity=1.0): resourcePath = '/expressions' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['sparsity'] = sparsity postData = body response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams) return fingerprint.Fingerprint(**response.json())
947,134
Get top exchanges by 24 hour trading volume for the currency pair. Args: fsym: FROM symbol. tsym: TO symbol. limit: Number of results. Default value returns top 5 exchanges. Returns: Function returns a list containing a dictionary for each result: [{'exchange': ..., 'fromSymbol': ..., 'toSymbole': ..., 'volume24h': ..., 'volume24hTo': ...}, {...}, ...] The list is ordered based on the volume of the FROM currency starting with the highest value.
def get_top_exchanges(fsym, tsym, limit=5): # load data url = build_url('exchanges', fsym=fsym, tsym=tsym, limit=limit) data = load_data(url) # price_data = data['Data'] # return [{'exchange': p['exchange'], # 'volume24hto': p['volume24hTo']} for p in price_data] return data['Data']
947,136
Get top coins by 24 hour trading volume value in the requested currency. Args: tsym: TO symbol. limit: Number of results. Default value returns top 20 coins. Returns: Function returns a list containing a dictionary for each result: [{'SUPPLY': ..., 'SYMBOL': ..., 'VOLUME24HOURTO': ...}, {...}, ...] The list is ordered based on the volume of the TO currency starting with the highest value.
def get_top_coins(tsym, limit=20): # load data url = build_url('volumes', tsym=tsym, limit=limit) data = load_data(url) return data['Data']
947,137
Get top trading pairs by 24 hour aggregated volume for a currency. Args: fsym: FROM symbol. limit: Number of results. Default value returns top 5 pairs. Returns: Function returns a list containing a dictionary for each result: [{'exchange': ..., 'fromSymbol': ..., 'toSymbol': ..., 'volume24h': ..., 'volume24hTo': ...}, {...}, ...] The list is ordered based on the volume of the FROM currency starting with the highest value.
def get_top_pairs(fsym, limit=5): # load data url = build_url('pairs', fsym=fsym, limit=limit) data = load_data(url) return data['Data']
947,138
Load configuration values from the specified source. Args: source: as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items.
def load(self, source, as_defaults=False): if isinstance(source, six.string_types): source = os.path.expanduser(source) with open(source, encoding='utf-8') as f: self._rw.load_config_from_file(self._config, f, as_defaults=as_defaults) elif isinstance(source, (list, tuple)): for s in source: with open(s, encoding='utf-8') as f: self._rw.load_config_from_file(self._config, f, as_defaults=as_defaults) else: self._rw.load_config_from_file(self._config, source, as_defaults=as_defaults)
947,395
Load configuration values from the specified source string. Args: config_str: as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items.
def loads(self, config_str, as_defaults=False): self._rw.load_config_from_string(self._config, config_str, as_defaults=as_defaults)
947,396
Write configuration values to the specified destination. Args: destination: with_defaults (bool): if ``True``, values of items with no custom values will be included in the output if they have a default value set.
def dump(self, destination, with_defaults=False): if isinstance(destination, six.string_types): with open(destination, 'w', encoding='utf-8') as f: self._rw.dump_config_to_file(self._config, f, with_defaults=with_defaults) else: self._rw.dump_config_to_file(self._config, destination, with_defaults=with_defaults)
947,397
Generate a string representing all the configuration values. Args: with_defaults (bool): if ``True``, values of items with no custom values will be included in the output if they have a default value set.
def dumps(self, with_defaults=False): return self._rw.dump_config_to_string(self._config, with_defaults=with_defaults)
947,398
The recommended way of retrieving an item by key when extending configmanager's behaviour. Attribute and dictionary key access is configurable and may not always return items (see PlainConfig for example), whereas this method will always return the corresponding Item as long as NOT_FOUND hook callbacks don't break this convention. Args: *key Returns: item (:class:`.Item`):
def get_item(self, *key): item = self._get_item_or_section(key) if not item.is_item: raise RuntimeError('{} is a section, not an item'.format(key)) return item
947,427
Import config values from a dictionary. When ``as_defaults`` is set to ``True``, the values imported will be set as defaults. This can be used to declare the sections and items of configuration. Values of sections and items in ``dictionary`` can be dictionaries as well as instances of :class:`.Item` and :class:`.Config`. Args: dictionary: as_defaults: if ``True``, the imported values will be set as defaults.
def load_values(self, dictionary, as_defaults=False, flat=False): if flat: # Deflatten the dictionary and then pass on to the normal case. separator = self.settings.str_path_separator flat_dictionary = dictionary dictionary = collections.OrderedDict() for k, v in flat_dictionary.items(): k_parts = k.split(separator) c = dictionary for i, kp in enumerate(k_parts): if i >= len(k_parts) - 1: c[kp] = v else: if kp not in c: c[kp] = collections.OrderedDict() c = c[kp] for name, value in dictionary.items(): if name not in self: if as_defaults: if isinstance(value, dict): self[name] = self.create_section() self[name].load_values(value, as_defaults=as_defaults) else: self[name] = self.create_item(name, default=value) else: # Skip unknown names if not interpreting dictionary as defaults pass continue resolution = self._get_item_or_section(name, handle_not_found=False) if is_config_item(resolution): if as_defaults: resolution.default = value else: resolution.value = value else: resolution.load_values(value, as_defaults=as_defaults)
947,442
Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server.
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password)
947,658
Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique.
def create_primary_zone(self, account_name, zone_name): zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
947,659
Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload.
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files)
947,660
Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret.
def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
947,661
Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret.
def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
947,662
Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server.
def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data))
947,665
Simplifies OperatorTrace expressions over tensor-product spaces by turning it into iterated partial traces. Args: H (ProductSpace): The full space. A (Operator): Returns: Operator: Iterative partial trace expression
def decompose_space(H, A): return OperatorTrace.create( OperatorTrace.create(A, over_space=H.operands[-1]), over_space=ProductSpace.create(*H.operands[:-1]))
947,781
Wrapper for :class:`.Feedback`, defaulting to last channel Args: circuit (Circuit): The circuit that undergoes self-feedback out_port (int): The output port index, default = None --> last port in_port (int): The input port index, default = None --> last port Returns: Circuit: The circuit with applied feedback operation.
def FB(circuit, *, out_port=None, in_port=None): if out_port is None: out_port = circuit.cdim - 1 if in_port is None: in_port = circuit.cdim - 1 return Feedback.create(circuit, out_port=out_port, in_port=in_port)
947,811
Create a :class:`CPermutation` that extracts channel `k` Return a permutation circuit that maps the k-th (zero-based) input to the last output, while preserving the relative order of all other channels. Args: k (int): Extracted channel index cdim (int): The circuit dimension (number of channels) Returns: Circuit: Permutation circuit
def extract_channel(k, cdim): n = cdim perm = tuple(list(range(k)) + [n - 1] + list(range(k, n - 1))) return CPermutation.create(perm)
947,812
Prepare the adiabatic elimination on an SLH object Args: slh: The SLH object to take the limit for k: The scaling parameter $k \rightarrow \infty$. The default is a positive symbol 'k' Returns: tuple: The objects ``Y, A, B, F, G, N`` necessary to compute the limiting system.
def prepare_adiabatic_limit(slh, k=None): if k is None: k = symbols('k', positive=True) Ld = slh.L.dag() LdL = (Ld * slh.L)[0, 0] K = (-LdL / 2 + I * slh.H).expand().simplify_scalar() N = slh.S.dag() B, A, Y = K.series_expand(k, 0, 2) G, F = Ld.series_expand(k, 0, 1) return Y, A, B, F, G, N
947,817
Compute the limiting SLH model for the adiabatic approximation Args: YABFGN: The tuple (Y, A, B, F, G, N) as returned by prepare_adiabatic_limit. Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0. P0: The projector onto the null-space of Y. Returns: SLH: Limiting SLH model
def eval_adiabatic_limit(YABFGN, Ytilde, P0): Y, A, B, F, G, N = YABFGN Klim = (P0 * (B - A * Ytilde * A) * P0).expand().simplify_scalar() Hlim = ((Klim - Klim.dag())/2/I).expand().simplify_scalar() Ldlim = (P0 * (G - A * Ytilde * F) * P0).expand().simplify_scalar() dN = identity_matrix(N.shape[0]) + F.H * Ytilde * F Nlim = (P0 * N * dN * P0).expand().simplify_scalar() return SLH(Nlim.dag(), Ldlim.dag(), Hlim.dag())
947,818
Return the index a channel has within the subblock it belongs to I.e., only for reducible circuits, this gives a result different from the argument itself. Args: channel_index (int): The index of the external channel Raises: ValueError: for an invalid `channel_index`
def index_in_block(self, channel_index: int) -> int: if channel_index < 0 or channel_index >= self.cdim: raise ValueError() struct = self.block_structure if len(struct) == 1: return channel_index, 0 i = 1 while sum(struct[:i]) <= channel_index and i < self.cdim: i += 1 block_index = i - 1 index_in_block = channel_index - sum(struct[:block_index]) return index_in_block, block_index
947,821
Render the circuit expression and store the result in a file Args: fname (str): Path to an image file to store the result in. Returns: str: The path to the image file
def render(self, fname=''): import qnet.visualization.circuit_pyx as circuit_visualization from tempfile import gettempdir from time import time, sleep if not fname: tmp_dir = gettempdir() fname = os.path.join(tmp_dir, "tmp_{}.png".format(hash(time))) if circuit_visualization.draw_circuit(self, fname): done = False for k in range(20): if os.path.exists(fname): done = True break else: sleep(.5) if done: return fname raise CannotVisualize()
947,826
Series product with another :class:`SLH` object Args: other (SLH): An upstream SLH circuit. Returns: SLH: The combined system.
def series_with_slh(self, other): new_S = self.S * other.S new_L = self.S * other.L + self.L def ImAdjoint(m): return (m.H - m) * (I / 2) delta = ImAdjoint(self.L.adjoint() * self.S * other.L) if isinstance(delta, Matrix): new_H = self.H + other.H + delta[0, 0] else: assert delta == 0 new_H = self.H + other.H return SLH(new_S, new_L, new_H)
947,833
Compute the symbolic Liouvillian acting on a state rho If no rho is given, an OperatorSymbol is created in its place. This correspnds to the RHS of the master equation in which an average is taken over the external noise degrees of freedom. Args: rho (Operator): A symbolic density matrix operator Returns: Operator: The RHS of the master equation.
def symbolic_master_equation(self, rho=None): L, H = self.L, self.H if rho is None: rho = OperatorSymbol('rho', hs=self.space) return (-I * (H * rho - rho * H) + sum(Lk * rho * adjoint(Lk) - (adjoint(Lk) * Lk * rho + rho * adjoint(Lk) * Lk) / 2 for Lk in L.matrix.ravel()))
947,840
Compute the symbolic Heisenberg equations of motion of a system operator X. If no X is given, an OperatorSymbol is created in its place. If no noises are given, this correspnds to the ensemble-averaged Heisenberg equation of motion. Args: X (Operator): A system operator noises (Operator): A vector of noise inputs Returns: Operator: The RHS of the Heisenberg equations of motion of X.
def symbolic_heisenberg_eom( self, X=None, noises=None, expand_simplify=True): L, H = self.L, self.H if X is None: X = OperatorSymbol('X', hs=(L.space | H.space)) summands = [I * (H * X - X * H), ] for Lk in L.matrix.ravel(): summands.append(adjoint(Lk) * X * Lk) summands.append(-(adjoint(Lk) * Lk * X + X * adjoint(Lk) * Lk) / 2) if noises is not None: if not isinstance(noises, Matrix): noises = Matrix(noises) LambdaT = (noises.adjoint().transpose() * noises.transpose()).transpose() assert noises.shape == L.shape S = self.S summands.append((adjoint(noises) * S.adjoint() * (X * L - L * X)) .expand()[0, 0]) summand = (((L.adjoint() * X - X * L.adjoint()) * S * noises) .expand()[0, 0]) summands.append(summand) if len(S.space & X.space): comm = (S.adjoint() * X * S - X) summands.append((comm * LambdaT).expand().trace()) ret = OperatorPlus.create(*summands) if expand_simplify: ret = ret.expand().simplify_scalar() return ret
947,841
Compute the series product with another channel permutation circuit Args: other (CPermutation): Returns: Circuit: The composite permutation circuit (could also be the identity circuit for n channels)
def series_with_permutation(self, other): combined_permutation = tuple([self.permutation[p] for p in other.permutation]) return CPermutation.create(combined_permutation)
947,847
Differentiate by scalar parameter `sym`. Args: sym: What to differentiate by. n: How often to differentiate expand_simplify: Whether to simplify the result. Returns: The n-th derivative.
def diff(self, sym: Symbol, n: int = 1, expand_simplify: bool = True): if not isinstance(sym, sympy.Basic): raise TypeError("%s needs to be a Sympy symbol" % sym) if sym.free_symbols.issubset(self.free_symbols): # QuantumDerivative.create delegates internally to _diff (the # explicit non-trivial derivative). Using `create` gives us free # caching deriv = QuantumDerivative.create(self, derivs={sym: n}, vals=None) if not deriv.is_zero and expand_simplify: deriv = deriv.expand().simplify_scalar() return deriv else: # the "issubset" of free symbols is a sufficient, but not a # necessary condition; if `sym` is non-atomic, determining whether # `self` depends on `sym` is not completely trivial (you'd have to # substitute with a Dummy) return self.__class__._zero
947,925
Substitute sub-expressions both on the lhs and rhs Args: var_map (dict): Dictionary with entries of the form ``{expr: substitution}``
def substitute(self, var_map, cont=False, tag=None): return self.apply(substitute, var_map=var_map, cont=cont, tag=tag)
948,013
Filter to get CodeMirror CSS bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_css_bundle }} Arguments: field (djangocodemirror.fields.CodeMirrorField): A form field. Raises: CodeMirrorFieldBundleError: Raised if Codemirror configuration from field does not have a bundle name. Returns: string: Bundle name to load with webassets.
def codemirror_field_css_bundle(field): manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(field) try: bundle_name = manifesto.css_bundle_names()[0] except IndexError: msg = ("Given field with configuration name '{}' does not have a " "Javascript bundle name") raise CodeMirrorFieldBundleError(msg.format(field.config_name)) return bundle_name
948,197
Given a Field or BoundField, return widget instance. Todo: Raise an exception if given field object does not have a widget. Arguments: field (Field or BoundField): A field instance. Returns: django.forms.widgets.Widget: Retrieved widget from given field.
def resolve_widget(self, field): # When filter is used within template we have to reach the field # instance through the BoundField. if hasattr(field, 'field'): widget = field.field.widget # When used out of template, we have a direct field instance else: widget = field.widget return widget
948,200
Register config name from field widgets Arguments: *args: Fields that contains widget :class:`djangocodemirror.widget.CodeMirrorWidget`. Returns: list: List of registered config names from fields.
def register_from_fields(self, *args): names = [] for field in args: widget = self.resolve_widget(field) self.register(widget.config_name) if widget.config_name not in names: names.append(widget.config_name) return names
948,201
Render HTML tag for a given path. Arguments: path (string): Relative path from static directory. tag_template (string): Template string for HTML tag. Returns: string: HTML tag with url from given path.
def render_asset_html(self, path, tag_template): url = os.path.join(settings.STATIC_URL, path) return tag_template.format(url=url)
948,202
Initialize the algebra system Args: default_hs_cls (str): The name of the :class:`.LocalSpace` subclass that should be used when implicitly creating Hilbert spaces, e.g. in :class:`.OperatorSymbol`
def init_algebra(*, default_hs_cls='LocalSpace'): from qnet.algebra.core.hilbert_space_algebra import LocalSpace from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression default_hs_cls = getattr(importlib.import_module('qnet'), default_hs_cls) if issubclass(default_hs_cls, LocalSpace): QuantumExpression._default_hs_cls = default_hs_cls else: raise TypeError("default_hs_cls must be a subclass of LocalSpace")
948,222
Register configuration for an editor instance. Arguments: name (string): Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Raises: UnknowConfigError: If given config name does not exist in ``settings.CODEMIRROR_SETTINGS``. Returns: dict: Registred config dict.
def register(self, name): if name not in settings.CODEMIRROR_SETTINGS: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_SETTINGS'.") raise UnknowConfigError(msg.format(name)) parameters = copy.deepcopy(self.default_internal_config) parameters.update(copy.deepcopy( settings.CODEMIRROR_SETTINGS[name] )) # Add asset bundles name if 'css_bundle_name' not in parameters: css_template_name = settings.CODEMIRROR_BUNDLE_CSS_NAME parameters['css_bundle_name'] = css_template_name.format( settings_name=name ) if 'js_bundle_name' not in parameters: js_template_name = settings.CODEMIRROR_BUNDLE_JS_NAME parameters['js_bundle_name'] = js_template_name.format( settings_name=name ) self.registry[name] = parameters return parameters
948,223
Register many configuration names. Arguments: *args: Config names as strings. Returns: list: List of registered configs.
def register_many(self, *args): params = [] for name in args: params.append(self.register(name)) return params
948,224
From given mode name, return mode file path from ``settings.CODEMIRROR_MODES`` map. Arguments: name (string): Mode name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_MODES``. Returns: string: Mode file path.
def resolve_mode(self, name): if name not in settings.CODEMIRROR_MODES: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_MODES'.") raise UnknowModeError(msg.format(name)) return settings.CODEMIRROR_MODES.get(name)
948,225
From given theme name, return theme file path from ``settings.CODEMIRROR_THEMES`` map. Arguments: name (string): Theme name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_THEMES``. Returns: string: Theme file path.
def resolve_theme(self, name): if name not in settings.CODEMIRROR_THEMES: msg = ("Given theme name '{}' does not exists in " "'settings.CODEMIRROR_THEMES'.") raise UnknowThemeError(msg.format(name)) return settings.CODEMIRROR_THEMES.get(name)
948,226
Return a registred configuration for given config name. Arguments: name (string): A registred config name. Raises: NotRegisteredError: If given config name does not exist in registry. Returns: dict: Configuration.
def get_config(self, name): if name not in self.registry: msg = "Given config name '{}' is not registered." raise NotRegisteredError(msg.format(name)) return copy.deepcopy(self.registry[name])
948,228
Return CodeMirror parameters for given configuration name. This is a reduced configuration from internal parameters. Arguments: name (string): Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Returns: dict: Parameters.
def get_codemirror_parameters(self, name): config = self.get_config(name) return {k: config[k] for k in config if k not in self._internal_only}
948,229
Commutator of `A` and `B` If ``B != None``, return the commutator :math:`[A,B]`, otherwise return the super-operator :math:`[A,\cdot]`. The super-operator :math:`[A,\cdot]` maps any other operator ``B`` to the commutator :math:`[A, B] = A B - B A`. Args: A: The first operator to form the commutator of. B: The second operator to form the commutator of, or None. Returns: SuperOperator: The linear superoperator :math:`[A,\cdot]`
def commutator(A, B=None): if B: return A * B - B * A return SPre(A) - SPost(A)
948,233
If ``B != None``, return the anti-commutator :math:`\{A,B\}`, otherwise return the super-operator :math:`\{A,\cdot\}`. The super-operator :math:`\{A,\cdot\}` maps any other operator ``B`` to the anti-commutator :math:`\{A, B\} = A B + B A`. Args: A: The first operator to form all anti-commutators of. B: The second operator to form the anti-commutator of, or None. Returns: SuperOperator: The linear superoperator :math:`[A,\cdot]`
def anti_commutator(A, B=None): if B: return A * B + B * A return SPre(A) + SPost(A)
948,234
r"""Generate the operator matrix with quadrants .. math:: \begin{pmatrix} A B \\ C D \end{pmatrix} Args: A (Matrix): Matrix of shape ``(n, m)`` B (Matrix): Matrix of shape ``(n, k)`` C (Matrix): Matrix of shape ``(l, m)`` D (Matrix): Matrix of shape ``(l, k)`` Returns: Matrix: The combined block matrix ``[[A, B], [C, D]]``.
def block_matrix(A, B, C, D): r return vstackm((hstackm((A, B)), hstackm((C, D))))
948,258
Expand the matrix expression as a truncated power series in a scalar parameter. Args: param: Expansion parameter. about (.Scalar): Point about which to expand. order: Maximum order of expansion >= 0 Returns: tuple of length (order+1), where the entries are the expansion coefficients.
def series_expand(self, param: Symbol, about, order: int): s = self.shape emats = zip(*[o.series_expand(param, about, order) for o in self.matrix.ravel()]) return tuple((Matrix(np_array(em).reshape(s)) for em in emats))
948,276
Recursively match `expr` with the given `expr_or_pattern` Args: expr_or_pattern: either a direct expression (equal to `expr` for a successful match), or an instance of :class:`Pattern`. expr: the expression to be matched
def match_pattern(expr_or_pattern: object, expr: object) -> MatchDict: try: # first try expr_or_pattern as a Pattern return expr_or_pattern.match(expr) except AttributeError: # expr_or_pattern is an expr, not a Pattern if expr_or_pattern == expr: return MatchDict() # success else: res = MatchDict() res.success = False res.reason = "Expressions '%s' and '%s' are not the same" % ( repr(expr_or_pattern), repr(expr)) return res
948,298
Return an instantiated Expression as ``cls.create(*self.args, **self.kwargs)`` Args: cls (class): The class of the instantiated expression. If not given, ``self.cls`` will be used.
def instantiate(self, cls=None): if cls is None: cls = self.cls if cls is None: raise TypeError("cls must a class") return cls.create(*self.args, **self.kwargs)
948,317
Build CodeMirror HTML script tag which contains CodeMirror init. Arguments: inputid (string): Input id. Returns: string: HTML for field CodeMirror instance.
def codemirror_script(self, inputid): varname = "{}_codemirror".format(inputid) html = self.get_codemirror_field_js() opts = self.codemirror_config() return html.format(varname=varname, inputid=inputid, settings=json.dumps(opts, sort_keys=True))
948,494
Pull out a permutation from the Feedback of a SeriesProduct with itself. Args: lhs (CPermutation): The permutation circuit rest (tuple): The other SeriesProduct operands out_port (int): The feedback output port index in_port (int): The feedback input port index Returns: Circuit: The simplified circuit
def _pull_out_perm_lhs(lhs, rest, out_port, in_port): out_inv, lhs_red = lhs._factor_lhs(out_port) return lhs_red << Feedback.create(SeriesProduct.create(*rest), out_port=out_inv, in_port=in_port)
948,512
In a self-Feedback of a series product, where the left-most operand is reducible, pull all non-trivial blocks outside of the feedback. Args: lhs (Circuit): The reducible circuit rest (tuple): The other SeriesProduct operands out_port (int): The feedback output port index in_port (int): The feedback input port index Returns: Circuit: The simplified circuit
def _pull_out_unaffected_blocks_lhs(lhs, rest, out_port, in_port): _, block_index = lhs.index_in_block(out_port) bs = lhs.block_structure nbefore, nblock, nafter = (sum(bs[:block_index]), bs[block_index], sum(bs[block_index + 1:])) before, block, after = lhs.get_blocks((nbefore, nblock, nafter)) if before != cid(nbefore) or after != cid(nafter): outer_lhs = before + cid(nblock - 1) + after inner_lhs = cid(nbefore) + block + cid(nafter) return outer_lhs << Feedback.create( SeriesProduct.create(inner_lhs, *rest), out_port=out_port, in_port=in_port) elif block == cid(nblock): outer_lhs = before + cid(nblock - 1) + after return outer_lhs << Feedback.create( SeriesProduct.create(*rest), out_port=out_port, in_port=in_port) raise CannotSimplify()
948,513
Substitute symbols or (sub-)expressions with the given replacements and re-evalute the result Args: expr: The expression in which to perform the substitution var_map (dict): The substitution dictionary.
def substitute(expr, var_map): try: if isinstance(expr, SympyBasic): sympy_var_map = { k: v for (k, v) in var_map.items() if isinstance(k, SympyBasic)} return expr.subs(sympy_var_map) else: return expr.substitute(var_map) except AttributeError: if expr in var_map: return var_map[expr] return expr
948,547
Print algebraic rules used by :class:`create` Print a summary of the algebraic rules with the given names, or all rules if not names a given. Args: names (str): Names of rules to show attr (None or str): Name of the class attribute from which to get the rules. Cf. :meth:`add_rule`. Raises: AttributeError: If invalid `attr`
def show_rules(cls, *names, attr=None): from qnet.printing import srepr try: if attr is None: attr = cls._rules_attr() rules = getattr(cls, attr) except TypeError: rules = {} for (name, rule) in rules.items(): if len(names) > 0 and name not in names: continue pat, repl = rule print(name) print(" PATTERN:") print(textwrap.indent( textwrap.dedent(srepr(pat, indented=True)), prefix=" "*8)) print(" REPLACEMENT:") print(textwrap.indent( textwrap.dedent(inspect.getsource(repl).rstrip()), prefix=" "*8))
948,554
Delete algebraic rules used by :meth:`create` Remove the rules with the given `names`, or all rules if no names are given Args: names (str): Names of rules to delete attr (None or str): Name of the class attribute from which to delete the rules. Cf. :meth:`add_rule`. Raises: KeyError: If any rules in `names` does not exist AttributeError: If invalid `attr`
def del_rules(cls, *names, attr=None): if attr is None: attr = cls._rules_attr() if len(names) == 0: getattr(cls, attr) # raise AttributeError if wrong attr setattr(cls, attr, OrderedDict()) else: for name in names: del getattr(cls, attr)[name]
948,555
Iterable of rule names used by :meth:`create` Args: attr (None or str): Name of the class attribute to which to get the names. If None, one of ``'_rules'``, ``'_binary_rules'`` is automatically chosen
def rules(cls, attr=None): try: if attr is None: attr = cls._rules_attr() return getattr(cls, attr).keys() except TypeError: return ()
948,556
Substitute sub-expressions Args: var_map (dict): Dictionary with entries of the form ``{expr: substitution}``
def substitute(self, var_map): if self in var_map: return var_map[self] return self._substitute(var_map)
948,560
Remove all the registered observers for the given event name. Arguments: event (str): event name to remove.
def remove(self, event=None): observers = self._pool.get(event) if observers: self._pool[event] = []
948,895
Overload a given callable object to be used with ``|`` operator overloading. This is especially used for composing a pipeline of transformation over a single data set. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine function is not provided. Returns: function: decorated function
def overload(fn): if not isfunction(fn): raise TypeError('paco: fn must be a callable object') spec = getargspec(fn) args = spec.args if not spec.varargs and (len(args) < 2 or args[1] != 'iterable'): raise ValueError('paco: invalid function signature or arity') @functools.wraps(fn) def decorator(*args, **kw): # Check function arity if len(args) < 2: return PipeOverloader(fn, args, kw) # Otherwise, behave like a normal wrapper return fn(*args, **kw) return decorator
948,957
Helper function to consume a synchronous or asynchronous generator. Arguments: generator (generator|asyncgenerator): generator to consume. Returns: list
def consume(generator): # pragma: no cover # If synchronous generator, just consume and return as list if hasattr(generator, '__next__'): return list(generator) if not PY_35: raise RuntimeError( 'paco: asynchronous iterator protocol not supported') # If asynchronous generator, consume it generator protocol manually buf = [] while True: try: buf.append((yield from generator.__anext__())) except StopAsyncIteration: # noqa break return buf
948,970
Returns `True` if the given value is a function or method object. Arguments: x (mixed): value to check. Returns: bool
def isfunc(x): return any([ inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) ])
948,972
Asserts if a given values are a coroutine function. Arguments: **kw (mixed): value to check if it is an iterable. Raises: TypeError: if assertion fails.
def assert_corofunction(**kw): for name, value in kw.items(): if not asyncio.iscoroutinefunction(value): raise TypeError( 'paco: {} must be a coroutine function'.format(name))
948,973
Asserts if a given values implements a valid iterable interface. Arguments: **kw (mixed): value to check if it is an iterable. Raises: TypeError: if assertion fails.
def assert_iter(**kw): for name, value in kw.items(): if not isiter(value): raise TypeError( 'paco: {} must be an iterable object'.format(name))
948,974
Decorator wrapper that consumes sync/async generators provided as interable input argument. This function is only intended to be used internally. Arguments: coro (coroutinefunction): function to decorate Raises: TypeError: if function or coroutine function is not provided. Returns: function: decorated function.
def generator_consumer(coro): # pragma: no cover if not asyncio.iscoroutinefunction(coro): raise TypeError('paco: coro must be a coroutine function') @functools.wraps(coro) @asyncio.coroutine def wrapper(*args, **kw): if len(args) > 1 and isgenerator(args[1]): args = list(args) args[1] = (yield from consume(args[1]) if hasattr(args[1], '__anext__') else list(args[1])) args = tuple(args) return (yield from coro(*args, **kw)) return wrapper
949,095