text
stringlengths
18
773k
def resource_filename_mod_entry_point(module_name, entry_point): """ If a given package declares a namespace and also provide submodules nested at that namespace level, and for whatever reason that module is needed, Python's import mechanism will not have a path associated with that module. However...
def modgen( module, entry_point, modpath='pkg_resources', globber='root', fext=JS_EXT, registry=_utils): """ JavaScript styled module location listing generator. Arguments: module The Python module to start fetching from. entry_point This is the original en...
def register(util_type, registry=_utils): """ Crude, local registration decorator for a crude local registry of all utilities local to this module. """ def marker(f): mark = util_type + '_' if not f.__name__.startswith(mark): raise TypeError( 'not registe...
def modpath_all(module, entry_point): """ Provides the raw __path__. Incompatible with PEP 302-based import hooks and incompatible with zip_safe packages. Deprecated. Will be removed by calmjs-4.0. """ module_paths = getattr(module, '__path__', []) if not module_paths: logger.war...
def modpath_last(module, entry_point): """ Provides the raw __path__. Incompatible with PEP 302-based import hooks and incompatible with zip_safe packages. Deprecated. Will be removed by calmjs-4.0. """ module_paths = modpath_all(module, entry_point) if len(module_paths) > 1: log...
def modpath_pkg_resources(module, entry_point): """ Goes through pkg_resources for compliance with various PEPs. This one accepts a module as argument. """ result = [] try: path = resource_filename_mod_entry_point(module.__name__, entry_point) except ImportError: logger.war...
def mapper(module, entry_point, modpath='pkg_resources', globber='root', modname='es6', fext=JS_EXT, registry=_utils): """ General mapper Loads components from the micro registry. """ modname_f = modname if callable(modname) else _utils['modname'][modname] return { ...
def mapper_python(module, entry_point, globber='root', fext=JS_EXT): """ Default mapper using python style globber Finds the latest path declared for the module at hand and extract a list of importable JS modules using the es6 module import format. """ return mapper( module, entry_poin...
def _printable_id_code(self): """ Returns the code in a printable form, filling with zeros if needed. :return: the ID code in a printable form """ code = str(self.id_code) while len(code) < self._code_size: code = '0' + code return code
def _printable_id_code(self): """ Returns the code in a printable form, separating it into groups of three characters using a point between them. :return: the ID code in a printable form """ code = super(ISWCCode, self)._printable_id_code() code1 = code[:3] ...
def write(self, s): """ Standard write, for standard sources part of the original file. """ lines = s.splitlines(True) for line in lines: self.current_mapping.append( (self.generated_col, self.index, self.row, self.col_last)) self.stream.w...
def discard(self, s): """ Discard from original file. """ lines = s.splitlines(True) for line in lines: if line[-1] not in '\r\n': if not self.warn: logger.warning( 'partial line discard UNSUPPORTED; source ...
def write_padding(self, s): """ Write string that are not part of the original file. """ lines = s.splitlines(True) for line in lines: self.stream.write(line) if line[-1] in '\r\n': self._newline() else: # this ...
def format_currency(number, currency, format, locale=babel.numbers.LC_NUMERIC, force_frac=None, format_type='standard'): """Same as ``babel.numbers.format_currency``, but has ``force_frac`` argument instead of ``currency_digits``. If the ``force_frac`` argument is given, the argument is...
def run(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() if not c.unihan.is_bootstrapped: # download and install Unihan to db c.unihan.bootstrap(unihan_options) c.unihan.add_plugin( 'cihai.d...
def reflect_db(self): """ No-op to reflect db info. This is available as a method so the database can be reflected outside initialization (such bootstrapping unihan during CLI usage). """ self.metadata.reflect(views=True, extend_existing=True) self.base = automap...
def parse(s, element=Element, atomicstring=lambda s: s): """ Translates from ASCIIMathML (an easy to type and highly readable way to represent math formulas) into MathML (a w3c standard directly displayable by some web browsers). The function `parse()` generates a tree of elements: >>> import asciimathml ...
def trace_parser(p): """ Decorator for tracing the parser. Use it to decorate functions with signature: string -> (string, nodes) and a trace of the progress made by the parser will be printed to stderr. Currently parse_exprs(), parse_expr() and parse_m() have the right signature. """ ...
def remove_symbol_from_dist(dist, index): ''' prob is a ndarray representing a probability distribution. index is a number between 0 and and the number of symbols ( len(prob)-1 ) return the probability distribution if the element at 'index' was no longer available ''' if type(dist) is not Distri...
def change_response(x, prob, index): ''' change every response in x that matches 'index' by randomly sampling from prob ''' #pdb.set_trace() N = (x==index).sum() #x[x==index]=9 x[x==index] = dist.sample(N)
def toy_example(): """ Make a toy example where x is uniformly distributed with N bits and y follows x but with symbol dependent noise. x=0 -> y=0 x=1 -> y=1 + e x=2 -> y=2 + 2*e ... x=n -> y=n + n*e where by n*e I am saying that the noise grows """ #pdb.set_trace() N=4 ...
def differentiate_mi(x, y): ''' for each symbol in x, change x such that there are no more of such symbols (replacing by a random distribution with the same proba of all other symbols) and compute mi(new_x, y) ''' #pdb.set_trace() dist = Distribution(discrete.symbols_to_prob(x)) diff = ...
def sample(self, *args): ''' generate a random number in [0,1) and return the index into self.prob such that self.prob[index] <= random_number but self.prob[index+1] > random_number implementation note: the problem is identical to finding the index into self.cumsum where the ran...
def default_log_template(self, record): """Return the prefix for the log message. Template for Formatter. :param: record: :py:class:`logging.LogRecord` object. this is passed in from inside the :py:meth:`logging.Formatter.format` record. """ reset = Style.RESET_ALL levelname = [ LEVEL...
def merge_dict(base, additional): """ Combine two dictionary-like objects. Notes ----- Code from https://github.com/pypa/warehouse Copyright 2013 Donald Stufft Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the Licens...
def expand_config(d, dirs): """ Expand configuration XDG variables, environmental variables, and tildes. Parameters ---------- d : dict config information dirs : appdirs.AppDirs XDG application mapping Notes ----- *Environmentable variables* are expanded via :py:fun...
def bootstrap_unihan(metadata, options={}): """Download, extract and import unihan to database.""" options = merge_dict(UNIHAN_ETL_DEFAULT_OPTIONS.copy(), options) p = unihan.Packager(options) p.download() data = p.export() table = create_unihan_table(UNIHAN_FIELDS, metadata) metadata.creat...
def is_bootstrapped(metadata): """Return True if cihai is correctly bootstrapped.""" fields = UNIHAN_FIELDS + DEFAULT_COLUMNS if TABLE_NAME in metadata.tables.keys(): table = metadata.tables[TABLE_NAME] if set(fields) == set(c.name for c in table.columns): return True el...
def create_unihan_table(columns, metadata): """Create table and return :class:`sqlalchemy.Table`. Parameters ---------- columns : list columns for table, e.g. ``['kDefinition', 'kCantonese']`` metadata : :class:`sqlalchemy.schema.MetaData` Instance of sqlalchemy metadata Retur...
def get_address(pk, main_net=True, prefix=None): """ compute the nem-py address from the public one """ if isinstance(pk, str): pk = unhexlify(pk.encode()) assert len(pk) == 32, 'PK is 32bytes {}'.format(len(pk)) k = keccak_256(pk).digest() ripe = RIPEMD160.new(k).digest() if prefix is N...
def lookup_char(self, char): """Return character information from datasets. Parameters ---------- char : str character / string to lookup Returns ------- :class:`sqlalchemy.orm.query.Query` : list of matches """ Unihan = s...
def reverse_char(self, hints): """Return QuerySet of objects from SQLAlchemy of results. Parameters ---------- hints: list of str strings to lookup Returns ------- :class:`sqlalchemy.orm.query.Query` : reverse matches """ ...
def with_fields(self, *fields): """Returns list of characters with information for certain fields. Parameters ---------- *fields : list of str fields for which information should be available Returns ------- :class:`sqlalchemy.orm.query.Query` : ...
def entropy(data=None, prob=None, method='nearest-neighbors', bins=None, errorVal=1e-5, units='bits'): ''' given a probability distribution (prob) or an interable of symbols (data) compute and return its continuous entropy. inputs: ------ data: samples by dimensions ndarray p...
def mi(x, y, bins_x=None, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits'): ''' compute and return the mutual information between x and y inputs: ------- x, y: numpy arrays of shape samples x dimension method: 'nearest-neighbors', 'gaussian', or 'bin' ...
def cond_entropy(x, y, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits'): ''' compute the conditional entropy H(X|Y). method: 'nearest-neighbors', 'gaussian', or 'bin' if 'bin' need to provide bins_y, and bins_xy units: 'bits' or 'nats' ''' HXY = entr...
def entropy(data=None, prob=None, tol=1e-5): ''' given a probability distribution (prob) or an interable of symbols (data) compute and return its entropy inputs: ------ data: iterable of symbols prob: iterable with probabilities tol: if prob is given, 'e...
def symbols_to_prob(symbols): ''' Return a dict mapping symbols to probability. input: ----- symbols: iterable of hashable items works well if symbols is a zip of iterables ''' myCounter = Counter(symbols) N = float(len(list(symbols))) # symbols might be...
def combine_symbols(*args): ''' Combine different symbols into a 'super'-symbol args can be an iterable of iterables that support hashing see example for 2D ndarray input usage: 1) combine two symbols, each a number into just one symbol x = numpy.random.randint(0,4,1000) y...
def mi(x, y): ''' compute and return the mutual information between x and y inputs: ------- x, y: iterables of hashable items output: ------- mi: float Notes: ------ if you are trying to mix several symbols together as in mi(x, (y0,y1,...)), try ...
def cond_mi(x, y, z): ''' compute and return the mutual information between x and y given z, I(x, y | z) inputs: ------- x, y, z: iterables with discrete symbols output: ------- mi: float implementation notes: --------------------- I(x, y | z) = H(x | z) ...
def mi_chain_rule(X, y): ''' Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule. Inputs: ------- X: iterable of iterables. You should be able to compute [mi(x, y) for x in X] y: iterable of symbols ...
def KL_divergence(P,Q): ''' Compute the KL divergence between distributions P and Q P and Q should be dictionaries linking symbols to probabilities. the keys to P and Q should be the same. ''' assert(P.keys()==Q.keys()) distance = 0 for k in P.keys(): distance += P[k] *...
def bin(x, bins, maxX=None, minX=None): ''' bin signal x using 'binsN' bin. If minX, maxX are None, they default to the full range of the signal. If they are not None, everything above maxX gets assigned to binsN-1 and everything below minX gets assigned to 0, this is effectively the same as clippin...
def linkcode_resolve(domain, info): # NOQA: C901 """ Determine the URL corresponding to Python object Notes ----- From https://github.com/numpy/numpy/blob/v1.15.1/doc/source/conf.py, 7c49cfa on Jul 31. License BSD-3. https://github.com/numpy/numpy/blob/v1.15.1/LICENSE.txt """ if domain...
def inv(z): """$= z^{-1} \mod q$, for z != 0""" # Adapted from curve25519_athlon.c in djb's Curve25519. z = qdiv(z) z2 = z * z % PRIME # 2 z9 = pow2(z2, 2) * z % PRIME # 9 z11 = z9 * z2 % PRIME # 11 z2_5_0 = (z11*z11) % PRIME * z9 % PRIME # 31 == 2^5 - 2^0 z2_10_0 = pow2(z2_5_0, 5) *...
def scalarmult_B(e): """ Implements scalarmult(B, e) more efficiently. """ # scalarmult(B, l) is the identity e %= L P = IDENT for i in range(253): if e & 1: P = edwards_add(P=P, Q=Bpow[i]) e //= 2 assert e == 0, e return P
def recover(y): """ given a value y, recover the preimage x """ p = (y*y - 1) * inverse(D*y*y + 1) x = powmod(p, (PRIME+3) // 8, PRIME) if (x*x - p) % PRIME != 0: i = powmod(2, (PRIME-1) // 4, PRIME) x = (x*i) % PRIME if x % 2 != 0: x = PRIME - x return x
def __rubberband(y, sr, **kwargs): '''Execute rubberband Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 sampling rate of y **kwargs keyword arguments to rubberband Returns ------- y...
def time_stretch(y, sr, rate, rbargs=None): '''Apply a time stretch of `rate` to an audio time series. This uses the `tempo` form for rubberband, so the higher the rate, the faster the playback. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either sing...
def timemap_stretch(y, sr, time_map, rbargs=None): '''Apply a timemap stretch to an audio time series. A timemap stretch allows non-linear time-stretching by mapping source to target sample frame numbers for fixed time points within the audio data. This uses the `time` and `timemap` form for rubberban...
def pitch_shift(y, sr, n_steps, rbargs=None): '''Apply a pitch shift to an audio time series. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` n_steps : float Shift by `n_step...
def kuten_to_gb2312(kuten): """ Convert GB kuten / quwei form (94 zones * 94 points) to GB2312-1980 / ISO-2022-CN hex (internal representation) """ zone, point = int(kuten[:2]), int(kuten[2:]) hi, lo = hexd(zone + 0x20), hexd(point + 0x20) gb2312 = "%s%s" % (hi, lo) assert isinstance(g...
def gb2312_to_euc(gb2312hex): """ Convert GB2312-1980 hex (internal representation) to EUC-CN hex (the "external encoding") """ hi, lo = int(gb2312hex[:2], 16), int(gb2312hex[2:], 16) hi, lo = hexd(hi + 0x80), hexd(lo + 0x80) euc = "%s%s" % (hi, lo) assert isinstance(euc, bytes) ret...
def euc_to_python(hexstr): """ Convert a EUC-CN (GB2312) hex to a Python unicode string. """ hi = hexstr[0:2] lo = hexstr[2:4] gb_enc = b'\\x' + hi + b'\\x' + lo return gb_enc.decode("gb2312")
def euc_to_utf8(euchex): """ Convert EUC hex (e.g. "d2bb") to UTF8 hex (e.g. "e4 b8 80"). """ utf8 = euc_to_python(euchex).encode("utf-8") uf8 = utf8.decode('unicode_escape') uf8 = uf8.encode('latin1') uf8 = uf8.decode('euc-jp') return uf8
def ucn_to_unicode(ucn): """ Convert a Unicode Universal Character Number (e.g. "U+4E00" or "4E00") to Python unicode (u'\\u4e00') """ if isinstance(ucn, string_types): ucn = ucn.strip("U+") if len(ucn) > int(4): char = b'\U' + format(int(ucn, 16), '08x').encode('latin1')...
def euc_to_unicode(hexstr): """ Return EUC-CN (GB2312) hex to a Python unicode. Parameters ---------- hexstr : bytes Returns ------- unicode : Python unicode e.g. ``u'\\u4e00'`` / '一'. Examples -------- >>> u'\u4e00'.encode('gb2312').decode('utf-8') u'\u04bb'...
def python_to_ucn(uni_char, as_bytes=False): """ Return UCN character from Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding Unicode UCN ('U+4E00'). """ ucn = uni_char.encode('unicode_escape').decode('latin1') ucn = text_type(ucn...
def python_to_euc(uni_char, as_bytes=False): """ Return EUC character from a Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding EUC hex ('d2bb'). """ euc = repr(uni_char.encode("gb2312"))[1:-1].replace("\\x", "").strip("'") if as...
def ucnstring_to_unicode(ucn_string): """Return ucnstring as Unicode.""" ucn_string = ucnstring_to_python(ucn_string).decode('utf-8') assert isinstance(ucn_string, text_type) return ucn_string
def ucnstring_to_python(ucn_string): """ Return string with Unicode UCN (e.g. "U+4E00") to native Python Unicode (u'\\u4e00'). """ res = re.findall("U\+[0-9a-fA-F]*", ucn_string) for r in res: ucn_string = ucn_string.replace(text_type(r), text_type(ucn_to_unicode(r))) ucn_string = u...
def parse_var(var): """ Returns a tuple consisting of a string and a tag, or None, if none is specified. """ bits = var.split("<", 1) if len(bits) < 2: tag = None else: tag = bits[1] return ucn_to_unicode(bits[0]), tag
def from_file(cls, config_path=None, *args, **kwargs): """ Create a Cihai instance from a JSON or YAML config. Parameters ---------- config_path : str, optional path to custom config file Returns ------- :class:`Cihai` : applicati...
def _process_locale(self, locale): """Return True if this locale should be processed.""" if locale.lower().startswith('en'): return False return (locale in self.enabled_locales or self.reverse_locale_map.get(locale.lower(), None) in self.enabled_loc...
def desk_locale(self, locale): """Return the Desk-style locale for locale.""" locale = locale.lower().replace('-', '_') return self.vendor_locale_map.get(locale, locale)
def push(self): """Push topics to Transifex.""" tx = Tx(self.tx_project_slug) # asssemble the template catalog template = babel.messages.catalog.Catalog() for topic in self.desk.topics(): if topic.show_in_portal: template.add(topic.name) # s...
def pull(self): """Pull topics from Transifex.""" topic_stats = txlib.api.statistics.Statistics.get( project_slug=self.tx_project_slug, resource_slug=self.TOPIC_STRINGS_SLUG, ) translated = {} # for each language for locale in self.enabled_local...
def make_resource_document(self, title, content, tags=[],): """Return a single HTML document containing the title and content.""" assert "<html>" not in content assert "<body>" not in content return """ <html> <head><title>%(title)s</title></head> <body> ...
def parse_resource_document(self, content): """Return a dict with the keys title, content, tags for content.""" content = content.strip() if not content.startswith('<html>'): # this is not a full HTML doc, probably content w/o title, tags, etc return dict(body=content) ...
def push(self): """Push tutorials to Transifex.""" tx = Tx(self.tx_project_slug) if self.options.resources: articles = [ self.desk.articles().by_id(r.strip()) for r in self.options.resources.split(',') ] else: articles...
def get_project(self, locale, source_language_code=DEFAULT_SOURCE_LANGUAGE, **kwargs): """ Gets or creates the Transifex project for the current project prefix and locale :param locale: A locale to which content is to be translated :type locale: string :param source_language_cod...
def translation_exists(self, slug, lang): """Return True if the translation exists for this slug.""" try: return translations.Translation.get( project_slug=self.get_project_slug(lang), slug=slug, lang=lang, ) except (NotFo...
def list_resources(self, lang): """Return a sequence of resources for a given lang. Each Resource is a dict containing the slug, name, i18n_type, source_language_code and the category. """ return registry.registry.http_handler.get( '/api/2/project/%s/resources/' % (...
def resources(self, lang, slug): """Generate a list of Resources in the Project. Yields dicts from the Tx API, with keys including the slug, name, i18n_type, source_language_code, and category. """ resource = resources.Resource.get( project_slug=self.get_project_sl...
def resource_exists(self, slug, locale, project_slug=None): """Return True if a Resource with the given slug exists in locale.""" try: resource = resources.Resource.get( project_slug=project_slug or self.get_project_slug(locale), slug=slug, ) ...
def session_request(session, url, **kwargs): """Do HTTP/S request and return response as a string.""" try: response = session(url, **kwargs) response.raise_for_status() return response.text except requests.exceptions.HTTPError as errh: _LOGGER.debug("%s, %s", response, err...
def get_event_list(config): """Get a dict of supported events from device.""" eventinstances = session_request( config.session.post, device_event_url.format( proto=config.web_proto, host=config.host, port=config.port), auth=config.session.auth, headers=headers, data=request_xml) ...
def _prepare_event(eventinstances): """Converts event instances to a relevant dictionary.""" import xml.etree.ElementTree as ET def parse_event(events): """Find all events inside of an topicset list. MessageInstance signals that subsequent children will contain source and data desc...
def url(self): """Represent device base url.""" return URL.format(http=self.web_proto, host=self.host, port=self.port)
def process_raw(self, raw: dict) -> None: """Pre-process raw dict. Prepare parameters to work with APIItems. """ raw_ports = {} for param in raw: port_index = REGEX_PORT_INDEX.search(param).group(0) if port_index not in raw_ports: raw_po...
def name(self) -> str: """Return name relevant to direction.""" if self.direction == DIRECTION_IN: return self.raw.get('Input.Name', '') return self.raw.get('Output.Name', '')
def action(self, action): r"""Activate or deactivate an output. Use the <wait> option to activate/deactivate the port for a limited period of time. <Port ID> = Port name. Default: Name from Output.Name <a> = Action character. /=active, \=inactive <wait> = Delay befor...
def initialize_params(self, preload_data=True) -> None: """Load device parameters and initialize parameter management. Preload data can be disabled to selectively load params afterwards. """ params = '' if preload_data: params = self.request('get', param_url) ...
def initialize_ports(self) -> None: """Load IO port parameters for device.""" if not self.params: self.initialize_params(preload_data=False) self.params.update_ports() self.ports = Ports(self.params, self.request)
def initialize_users(self) -> None: """Load device user data and initialize user management.""" users = self.request('get', pwdgrp_url) self.users = Users(users, self.request)
def request(self, method, path, **kwargs): """Prepare HTTP request.""" if method == 'get': session_method = self.config.session.get elif method == 'post': session_method = self.config.session.post else: raise AxisException url = self.config....
def new_event(self, event_data: str) -> None: """New event to process.""" event = self.parse_event_xml(event_data) if EVENT_OPERATION in event: self.manage_event(event)
def parse_event_xml(self, event_data) -> dict: """Parse metadata xml.""" event = {} event_xml = event_data.decode() message = MESSAGE.search(event_xml) if not message: return {} event[EVENT_OPERATION] = message.group(EVENT_OPERATION) topic = TOPIC.s...
def manage_event(self, event) -> None: """Received new metadata. Operation initialized means new event, also happens if reconnecting. Operation changed updates existing events state. """ name = EVENT_NAME.format( topic=event[EVENT_TOPIC], source=event.get(EVENT_SOURC...
def state(self, state: str) -> None: """Update state of event.""" self._state = state for callback in self._callbacks: callback()
def remove_callback(self, callback) -> None: """Remove callback.""" if callback in self._callbacks: self._callbacks.remove(callback)
def enable_events(self, event_callback=None) -> None: """Enable events for stream.""" self.event = EventManager(event_callback) self.stream.event = self.event
def update_brand(self) -> None: """Update brand group of parameters.""" self.update(path=URL_GET + GROUP.format(group=BRAND))
def update_ports(self) -> None: """Update port groups of parameters.""" self.update(path=URL_GET + GROUP.format(group=INPUT)) self.update(path=URL_GET + GROUP.format(group=IOPORT)) self.update(path=URL_GET + GROUP.format(group=OUTPUT))
def ports(self) -> dict: """Create a smaller dictionary containing all ports.""" return { param: self[param].raw for param in self if param.startswith(IOPORT) }
def update_properties(self) -> None: """Update properties group of parameters.""" self.update(path=URL_GET + GROUP.format(group=PROPERTIES))
def process_raw(self, raw: str) -> None: """Pre-process raw string. Prepare parameters to work with APIItems. """ raw_params = dict(group.split('=', 1) for group in raw.splitlines()) super().process_raw(raw_params)
def create(self, user: str, *, pwd: str, sgrp: str, comment: str=None) -> None: """Create new user.""" data = { 'action': 'add', 'user': user, 'pwd': pwd, 'grp': 'users', 'sgrp': sgrp } if comment: da...
def delete(self, user: str) -> None: """Remove user.""" data = { 'action': 'remove', 'user': user } self._request('post', URL, data=data)