text
stringlengths
81
112k
Convert csv to dict :param delimiter: :param fields: :return: def csv_to_map(fields, delimiter=','): """ Convert csv to dict :param delimiter: :param fields: :return: """ def _csv_to_list(csv_input): """ Util function to overcome the use of files by in-memory ...
Convert dict to csv :param fields: :return: def map_to_csv(fields, delimiter=","): """ Convert dict to csv :param fields: :return: """ def _list_to_csv(l): """ Util function to overcome the use of files by in-memory io buffer :param l: :return: ...
Make a function compatible with xarray.DataArray. This function is intended to be used as a decorator like:: >>> @dc.xarrayfunc >>> def func(array): ... # do something ... return newarray >>> >>> result = func(array) Args: func (function): Funct...
Make a function compatible with multicore chunk processing. This function is intended to be used as a decorator like:: >>> @dc.chunk('array') >>> def func(array): ... # do something ... return newarray >>> >>> result = func(array, timechunk=10) or you c...
A dictionary of values that don't label any axes (point-like). def scalarcoords(self): """A dictionary of values that don't label any axes (point-like).""" return {k: v.values for k, v in self.coords.items() if v.dims==()}
Setup. def setup(self): """Setup.""" extensions = [] extension_configs = {} for item in self.config['markdown_extensions']: if isinstance(item, str): extensions.append(item) else: k, v = list(item.items())[0] exten...
Filter markdown. def _filter(self, text): """Filter markdown.""" self.markdown.reset() return self.markdown.convert(text)
Format seconds in a more human readable way. It supports units down to nanoseconds. :param s: Float of seconds to format :return: String second representation, like 12.4 us def format_sec(s): """ Format seconds in a more human readable way. It supports units down to nanoseconds. :param s:...
kwargs expected: 'who': kwargs.get('who') 'why': kwargs.get('why') 'uri': kwargs.get('uri') 'ip_addresses': kwargs.get('ip_addresses', {}) 'label': kwargs.get('label') 'agent_id': kwargs.get('agent_id') 'metadata': kwargs.get('extra', {...
Create a GTFS feed from the files in the directory SOURCE_PATH. See the project README for a description of the required source files. Save the feed to the file or directory TARGET_PATH. If the target path ends in '.zip', then write the feed as a zip archive. Otherwise assume the path is a direc...
Calculate power spectrum density of data. Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). ax (matplotlib.axes): Axis you want to plot on. doplot (bool): Plot ho...
Calculate Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. Returns: vk (np.ndarray): Frequency. allanvar (np.ndarray): Allan variance. def allan_variance(data, dt, tmax=10): """Calculate Allan vari...
Discover a list of collections under the given ``path``. If ``depth`` is "0", only the actual object under ``path`` is returned. If ``depth`` is anything but "0", it is considered as "1" and direct children are included in the result. The ``path`` is relative. The roo...
Encoded as quoted-string (see RFC 2616). def etag(self): """Encoded as quoted-string (see RFC 2616).""" if self.is_fake: return entry = None for entry in self.journal.list(): pass return entry.uid if entry is not None else hashlib.sha256(b"").hexdigest(...
Create a collection. If the collection already exists and neither ``collection`` nor ``props`` are set, this method shouldn't do anything. Otherwise the existing collection must be replaced. ``collection`` is a list of vobject components. ``props`` are metadata values for the ...
Get the current sync token and changed items for synchronization. ``old_token`` an old sync token which is used as the base of the delta update. If sync token is missing, all items are returned. ValueError is raised for invalid or old tokens. def sync(self, old_token=None): """Get the ...
List collection items. def list(self): """List collection items.""" if self.is_fake: return for item in self.collection.list(): yield item.uid + self.content_suffix
Fetch a single item. def get(self, href): """Fetch a single item.""" if self.is_fake: return uid = _trim_suffix(href, ('.ics', '.ical', '.vcf')) etesync_item = self.collection.get(uid) if etesync_item is None: return None try: item =...
Upload a new or replace an existing item. def upload(self, href, vobject_item): """Upload a new or replace an existing item.""" if self.is_fake: return content = vobject_item.serialize() try: item = self.get(href) etesync_item = item.etesync_item ...
Delete an item. When ``href`` is ``None``, delete the collection. def delete(self, href=None): """Delete an item. When ``href`` is ``None``, delete the collection. """ if self.is_fake: return if href is None: self.collection.delete() ...
Get metadata value for collection. def get_meta(self, key=None): """Get metadata value for collection.""" if self.is_fake: return {} if key == "tag": return self.tag elif key is None: ret = {} for key in self.journal.info.keys(): ...
Set metadata values for collection. def set_meta(self, _props): """Set metadata values for collection.""" if self.is_fake: return props = {} for key, value in _props.items(): key, value = self.meta_mappings.map_set(key, value) props[key] = value ...
Set metadata values for collection. ``props`` a dict with values for properties. def set_meta_all(self, props): """Set metadata values for collection. ``props`` a dict with values for properties. """ delta_props = self.get_meta() for key in delta_props.keys(): ...
Get the HTTP-datetime of when the collection was modified. def last_modified(self): """Get the HTTP-datetime of when the collection was modified.""" # FIXME: Make this sensible last_modified = time.strftime( "%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time())) ...
Get the unicode string representing the whole collection. def serialize(self): """Get the unicode string representing the whole collection.""" import datetime items = [] time_begin = datetime.datetime.now() for href in self.list(): items.append(self.get(href).item) ...
Set a context manager to lock the whole storage. ``mode`` must either be "r" for shared access or "w" for exclusive access. ``user`` is the name of the logged in user or empty. def acquire_lock(cls, mode, user=None): """Set a context manager to lock the whole storage. ``mode`...
Validate options. def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'charset_size': if v not in (1, 2, 4): raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v)) elif k ==...
Match string type. def match_string(self, stype): """Match string type.""" return not (stype - self.string_types) or bool(stype & self.wild_string_types)
Get encoding name. def get_encoding_name(self, name): """Get encoding name.""" name = codecs.lookup( filters.PYTHON_ENCODING_NAMES.get(name, name).lower() ).name if name.startswith(('utf-32', 'utf-16')): name = name[:6] if CURRENT_ENDIAN == BIG_ENDI...
Setup. def setup(self): """Setup.""" self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] self.prefix = self.config['prefix'] self.generic_mode = self.config['generic_mode'] sel...
Evaluate block comments. def evaluate_block(self, groups): """Evaluate block comments.""" if self.blocks: self.block_comments.append([groups['block'][2:-2], self.line_num, self.current_encoding])
Evaluate inline comments at the tail of source code. def evaluate_inline_tail(self, groups): """Evaluate inline comments at the tail of source code.""" if self.lines: self.line_comments.append([groups['line'][2:].replace('\\\n', ''), self.line_num, self.current_encoding])
Evaluate inline comments on their own lines. def evaluate_inline(self, groups): """Evaluate inline comments on their own lines.""" # Consecutive lines with only comments with same leading whitespace # will be captured as a single block. if self.lines: if ( s...
Evaluate Unicode. def evaluate_unicode(self, value): """Evaluate Unicode.""" if value.startswith('u8'): length = 1 value = value[3:-1] encoding = 'utf-8' elif value.startswith('u'): length = 2 value = value[2:-1] encoding ...
Evaluate normal string. def evaluate_normal(self, value): """Evaluate normal string.""" if value.startswith('L'): size = self.wide_charset_size encoding = self.wide_exec_charset value = value[2:-1] pack = BYTE_STORE[size | CURRENT_ENDIAN] else: ...
Evaluate strings. def evaluate_strings(self, groups): """Evaluate strings.""" if self.strings: encoding = self.current_encoding if self.generic_mode: # Generic assumes no escapes rules. self.quoted_strings.append([groups['strings'][1:-1], self.li...
Search for comments. def evaluate(self, m): """Search for comments.""" g = m.groupdict() if g["strings"]: self.evaluate_strings(g) self.line_num += g['strings'].count('\n') elif g["code"]: self.line_num += g["code"].count('\n') else: ...
Extend the source text list with the gathered text data. def extend_src_text(self, content, context, text_list, category): """Extend the source text list with the gathered text data.""" prefix = self.prefix + '-' if self.prefix else '' for comment, line, encoding in text_list: con...
Find content. def find_content(self, text): """Find content.""" if self.trigraphs: text = RE_TRIGRAPHS.sub(self.process_trigraphs, text) for m in self.pattern.finditer(self.norm_nl(text)): self.evaluate(m)
Create a cube as an instance of xarray.DataArray with Decode accessor. Args: data (numpy.ndarray): 3D (x x y x channel) array. xcoords (dict, optional): Dictionary of arrays that label x axis. ycoords (dict, optional): Dictionary of arrays that label y axis. chcoords (dict, optional...
Covert a decode cube to a decode array. Args: cube (decode.cube): Decode cube to be cast. template (decode.array): Decode array whose shape the cube is cast on. Returns: decode array (decode.array): Decode array. Notes: This functions is under development. def fromcube(cu...
Convert a decode array to decode cube. Args: array (decode.array): Decode array which will be converted. kwargs (optional): Other arguments. xarr (list or numpy.ndarray): Grid array of x direction. yarr (list or numpy.ndarray): Grid array of y direction. gx (floa...
Make a continuum array. Args: cube (decode.cube): Decode cube which will be averaged over channels. kwargs (optional): Other arguments. inchs (list): Included channel kidids. exchs (list): Excluded channel kidids. Returns: decode cube (decode.cube): Decode cube ...
Verify encoding is okay. def _verify_encoding(self, enc): """Verify encoding is okay.""" enc = PYTHON_ENCODING_NAMES.get(enc, enc) try: codecs.getencoder(enc) encoding = enc except LookupError: encoding = None return encoding
Check for UTF8, UTF16, and UTF32 BOMs. def has_bom(self, f): """Check for UTF8, UTF16, and UTF32 BOMs.""" content = f.read(4) encoding = None m = RE_UTF_BOM.match(content) if m is not None: if m.group(1): encoding = 'utf-8-sig' elif m.gro...
Return an encoding that will ignore the BOM. def _utf_strip_bom(self, encoding): """Return an encoding that will ignore the BOM.""" if encoding is None: pass elif encoding.lower() == 'utf-8': encoding = 'utf-8-sig' elif encoding.lower().startswith('utf-16'): ...
Guess by checking BOM, and checking `_special_encode_check`, and using memory map. def _detect_buffer_encoding(self, f): """Guess by checking BOM, and checking `_special_encode_check`, and using memory map.""" encoding = None with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_...
Analyze the file. def _analyze_file(self, f): """Analyze the file.""" f.seek(0) # Check for BOMs if self.CHECK_BOM: encoding = self.has_bom(f) f.seek(0) else: util.warn_deprecated( "'CHECK_BOM' attribute is deprecated. " ...
Detect encoding. def _detect_encoding(self, source_file): """Detect encoding.""" encoding = self._guess(source_file) # If we didn't explicitly detect an encoding, assume default. if encoding is None: encoding = self.default_encoding return encoding
Run on as first in chain. def _run_first(self, source_file): """Run on as first in chain.""" self.reset() self.current_encoding = self.default_encoding encoding = None try: encoding = self._detect_encoding(source_file) content = self.filter(source_file, ...
Guess the encoding and decode the content of the file. def _guess(self, filename): """Guess the encoding and decode the content of the file.""" encoding = None file_size = os.path.getsize(filename) # If the file is really big, lets just call it binary. # We don't have time to ...
Execute filter. def sfilter(self, source): """Execute filter.""" return [SourceText(source.text, source.context, source.encoding, 'text')]
u"""Will ask a question and keeps prompting until answered. Args: question (str): Question to ask end user default (str): Default answer if user just press enter at prompt answer (str): Used for testing Returns: (bool) Meaning: True - Answer is yes ...
u"""Ask user a question and confirm answer Args: question (str): Question to ask user default (str): Default answer if no input from user required (str): Require user to input answer answer (str): Used for testing is_answer_correct (str): Used for testing def get_corre...
Main. def main(): """Main.""" parser = argparse.ArgumentParser(prog='spellcheck', description='Spell checking tool.') # Flag arguments parser.add_argument('--version', action='version', version=('%(prog)s ' + __version__)) parser.add_argument('--debug', action='store_true', default=False, help=arg...
Run. def run(config, **kwargs): """Run.""" names = kwargs.get('names', []) groups = kwargs.get('groups', []) binary = kwargs.get('binary', '') spellchecker = kwargs.get('spellchecker', '') verbose = kwargs.get('verbose', 0) sources = kwargs.get('sources', []) debug = kwargs.get('debug'...
Raise a `DeprecationWarning` when wrapped function/method is called. Borrowed from https://stackoverflow.com/a/48632082/866026 def deprecated(message): # pragma: no cover """ Raise a `DeprecationWarning` when wrapped function/method is called. Borrowed from https://stackoverflow.com/a/48632082/86602...
Get a command process. def get_process(cmd): """Get a command process.""" if sys.platform.startswith('win'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen( cmd, startupinfo=startupinfo, ...
Get the output from the process. def get_process_output(process, encoding=None): """Get the output from the process.""" output = process.communicate() returncode = process.returncode if not encoding: try: encoding = sys.stdout.encoding except Exception: encodin...
Call with arguments. def call(cmd, input_file=None, input_text=None, encoding=None): """Call with arguments.""" process = get_process(cmd) if input_file is not None: with open(input_file, 'rb') as f: process.stdin.write(f.read()) if input_text is not None: process.stdin.wr...
Call spell checker with arguments. def call_spellchecker(cmd, input_text=None, encoding=None): """Call spell checker with arguments.""" process = get_process(cmd) # A buffer has been provided if input_text is not None: for line in input_text.splitlines(): # Hunspell truncates line...
Generate a random python attribute name. def random_name_gen(size=6): """Generate a random python attribute name.""" return ''.join( [random.choice(string.ascii_uppercase)] + [random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)] ) if size > 0 else ''
Wrap PyYaml's loader so we can extend it to suit our needs. Load all strings as Unicode: http://stackoverflow.com/a/2967461/3609487. def yaml_load(source, loader=yaml.Loader): """ Wrap PyYaml's loader so we can extend it to suit our needs. Load all strings as Unicode: http://stackoverflow.com/a/29674...
Read configuration. def read_config(file_name): """Read configuration.""" config = {} for name in (['.pyspelling.yml', '.spelling.yml'] if not file_name else [file_name]): if os.path.exists(name): if not file_name and name == '.spelling.yml': warn_deprecated( ...
Account repr change for timedelta in Python 3.7 and above in docstrings. This is needed to make some doctests pass on Python 3.7 and above. This change was introduced by `bpo-30302 <https://bugs.python.org/issue30302>`_ def fix_timedelta_repr(func): """ Account repr change for timedelta in Python 3.7 ...
Check if url is available and returns given tag type :param url: url to content relative to base url :param anchor: anchor type to return :param print_warn: if True print warn when url is unavailable def _get_tag(self, url, tag, print_warn=True): """Check if url is available and returns...
Include resources in pages def include_codemirror(self): """Include resources in pages""" contents = [] # base js = self._get_tag('codemirror.js', 'script') css = self._get_tag('codemirror.css', 'stylesheet') if js and css: contents.append(js) con...
Register CodeMirror as a Flask extension :param app: Flask instance def init_app(self, app): """Register CodeMirror as a Flask extension :param app: Flask instance """ if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['codemirror'] = CodeM...
Dump the class data in the format of a .netrc file. def format(self): """Dump the class data in the format of a .netrc file.""" self._netrc.hosts = dedictify_machines(self.machines) rep = "" for host in self._netrc.hosts.keys(): attrs = self._netrc.hosts[host] re...
Convert a Public Address String to a ScriptHash (Address) String. :param address: The Public address to convert. :type address: str :return: String containing the converted ScriptHash. def neo_get_scripthash_from_address(address): """ Convert a Public Address String to a ScriptHash (Address) Strin...
Preprocess reST file to support Sphinx like include directive. Includes are relative to the current working directory. def rst_preprocess(file): """ Preprocess reST file to support Sphinx like include directive. Includes are relative to the current working directory. """ with open(file) as fp:...
Converts a number to a big endian hexstring of a suitable size, optionally little endian :param {number} number :param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2. :param {boolean} little_endian - Encode the hex in little endian form :return {string} def ...
Converts a number to a variable length Int. Used for array length header :param: {number} num - The number :return: {string} hexstring of the variable Int. def num2varint(num): """ Converts a number to a variable length Int. Used for array length header :param: {number} num - The number :retu...
Perform GET request def get(self, path, params=None): """Perform GET request""" r = requests.get(url=self.url + path, params=params, timeout=self.timeout) r.raise_for_status() return r.json()
Perform POST request def post(self, path, data=None, json_data=None, params=None): """Perform POST request""" r = requests.post(url=self.url + path, data=data, json=json_data, params=params, timeout=self.timeout) try: r.raise_for_status() except requests.exceptions.HTTPError...
Validate options. def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'mode' and v not in MODE: raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
Setup. def setup(self): """Setup.""" self.user_break_tags = set(self.config['break_tags']) self.comments = self.config.get('comments', True) is True self.attributes = set(self.config['attributes']) self.type = self.config['mode'] if self.type not in MODE: se...
Special HTML encoding check. def header_check(self, content): """Special HTML encoding check.""" encode = None # Look for meta charset m = RE_HTML_ENCODE.search(content) if m: enc = m.group(1).decode('ascii') try: codecs.getencoder(enc)...
Check if tag is an element we should break on. def is_break_tag(self, el): """Check if tag is an element we should break on.""" name = sv.util.lower(el.name) if self.type != 'xhtml' else el.name return name in self.break_tags or name in self.user_break_tags
Get classes. def get_classes(self, el): """Get classes.""" if self.type != 'xhtml': return el.attrs.get('class', []) else: return [c for c in el.attrs.get('class', '').strip().split(' ') if c]
Construct an selector for context. def construct_selector(self, el, attr=''): """Construct an selector for context.""" selector = deque() ancestor = el while ancestor and ancestor.parent: if ancestor is not el: selector.appendleft(ancestor.name) ...
Setup. def setup(self): """Setup.""" self.additional_context = '' self.comments = False self.attributes = [] self.parser = 'xml' self.type = None self.filepattern = '' self.ignores = None self.captures = None
Check if has BOM. def has_bom(self, filestream): """Check if has BOM.""" content = filestream.read(4) if content == b'PK\x03\x04': # Zip file found. # Return `BINARY_ENCODE` as content is binary type, # but don't return None which means we don't know what we...
Determine file type. def determine_file_type(self, z): """Determine file type.""" content = z.read('[Content_Types].xml') with io.BytesIO(content) as b: encoding = self._analyze_file(b) if encoding is None: encoding = 'utf-8' b.seek(0) ...
Apply soft break. def soft_break(self, el, text): """Apply soft break.""" # Break word documents by paragraphs. if self.type == 'docx' and el.namespace == self.namespaces['w'] and el.name == 'p': text.append('\n') # Break slides by paragraphs. if self.type == 'pptx'...
Get context. def get_context(self, filename): """Get context.""" if self.type == 'pptx': context = '{}: '.format(RE_SLIDE.search(filename).group(1)) elif self.type == 'docx': context = '{}: '.format(RE_DOCS.match(filename).group(1)) else: context = '...
Parse XML file. def filter(self, source_file, encoding): # noqa A001 """Parse XML file.""" sources = [] for content, filename, enc in self.get_content(source_file): self.additional_context = self.get_context(filename) sources.extend(self._filter(content, source_file, e...
Filter. def sfilter(self, source): """Filter.""" sources = [] for content, filename, enc in self.get_content(io.BytesIO(source.text.encode(source.encoding))): self.additional_context = self.get_context(filename) sources.extend(self._filter(content, source.context, enc))...
Read the data files at the given directory path (string or Path object) and build a ProtoFeed from them. Validate the resulting ProtoFeed. If invalid, raise a ``ValueError`` specifying the errors. Otherwise, return the resulting ProtoFeed. The data files needed to build a ProtoFeed are - ``fre...
Return a copy of this ProtoFeed, that is, a feed with all the same attributes. def copy(self): """ Return a copy of this ProtoFeed, that is, a feed with all the same attributes. """ other = ProtoFeed() for key in cs.PROTOFEED_ATTRS: value = getattr(se...
Return a class which is a jsontree, but with a supplied attribute name mapping. The mapping argument can be a mapping object (dict, jsontree, etc.) or it can be a callable which takes a single argument (the attribute name), and returns a new name. This is useful in situations where you have a jsont...
Clone an object by first searializing out and then loading it back in. def clone(root, jsontreecls=jsontree, datetimeencoder=_datetimeencoder, datetimedecoder=_datetimedecoder): """Clone an object by first searializing out and then loading it back in. """ return json.loads(json.dumps(root, cls=JS...
JSON load from file function that defaults the loading class to be JSONTreeDecoder def load(fp, encoding=None, cls=JSONTreeDecoder, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kargs): """JSON load from file function that defaults the load...
JSON load from string function that defaults the loading class to be JSONTreeDecoder def loads(s, encoding=None, cls=JSONTreeDecoder, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kargs): """JSON load from string function that defaults the ...
Setup. def setup(self): """Setup.""" self.comments = self.config['comments'] self.docstrings = self.config['docstrings'] self.strings = self.config['strings'] self.group_comments = self.config['group_comments'] self.string_types, self.wild_string_types = self.eval_strin...
Validate options. def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'string_types': if RE_VALID_STRING_TYPES.match(v) is None: raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name_...
Special Python encoding check. def header_check(self, content): """Special Python encoding check.""" encode = None m = RE_PY_ENCODE.match(content) if m: if m.group(1): encode = m.group(1).decode('ascii') elif m.group(2): encode =...
Evaluate string type. def eval_string_type(self, text, is_string=False): """Evaluate string type.""" stype = set() wstype = set() for m in RE_ITER_STRING_TYPES.finditer(text): value = m.group(0) if value == '*': wstype.add('u') w...
Replace escapes. def replace_unicode(self, m): """Replace escapes.""" groups = m.groupdict() esc = m.group(0) if groups.get('fesc'): value = m.group(0) elif groups.get('format'): value = ' ' elif groups.get('special'): value = BACK_SL...
Replace escapes. def replace_bytes(self, m): """Replace escapes.""" esc = m.group(0) value = esc if m.group('special'): value = BACK_SLASH_TRANSLATION[esc] elif m.group('char'): try: value = chr(int(esc[2:], 16)) except Except...