INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Count cycles in the series.
def count_cycles(series, ndigits=None, left=False, right=False): """Count cycles in the series. Parameters ---------- series : iterable sequence of numbers ndigits : int, optional Round cycle magnitudes to the given number of digits before counting. left: bool, optional If True,...
Recipe to render a given FST node.
def render(node, strict=False): """Recipe to render a given FST node. The FST is composed of branch nodes which are either lists or dicts and of leaf nodes which are strings. Branch nodes can have other list, dict or leaf nodes as childs. To render a string, simply output it. To render a list, ren...
FST node located at the given path
def path_to_node(tree, path): """FST node located at the given path""" if path is None: return None node = tree for key in path: node = child_by_key(node, key) return node
Determine if we re on the targetted node.
def before_constant(self, constant, key): """Determine if we're on the targetted node. If the targetted column is reached, `stop` and `path_found` are set. If the targetted line is passed, only `stop` is set. This prevents unnecessary tree travelling when the targetted column is...
Returns prefix for a given multicodec
def get_prefix(multicodec): """ Returns prefix for a given multicodec :param str multicodec: multicodec codec name :return: the prefix for the given multicodec :rtype: byte :raises ValueError: if an invalid multicodec name is provided """ try: prefix = varint.encode(NAME_TABLE[m...
Adds multicodec prefix to the given bytes input
def add_prefix(multicodec, bytes_): """ Adds multicodec prefix to the given bytes input :param str multicodec: multicodec to use for prefixing :param bytes bytes_: data to prefix :return: prefixed byte data :rtype: bytes """ prefix = get_prefix(multicodec) return b''.join([prefix, b...
Removes prefix from a prefixed data
def remove_prefix(bytes_): """ Removes prefix from a prefixed data :param bytes bytes_: multicodec prefixed data bytes :return: prefix removed data bytes :rtype: bytes """ prefix_int = extract_prefix(bytes_) prefix = varint.encode(prefix_int) return bytes_[len(prefix):]
Gets the codec used for prefix the multicodec prefixed data
def get_codec(bytes_): """ Gets the codec used for prefix the multicodec prefixed data :param bytes bytes_: multicodec prefixed data bytes :return: name of the multicodec used to prefix :rtype: str """ prefix = extract_prefix(bytes_) try: return CODE_TABLE[prefix] except Key...
Archives the provided URL using archive. is
def capture( target_url, user_agent="archiveis (https://github.com/pastpages/archiveis)", proxies={} ): """ Archives the provided URL using archive.is Returns the URL where the capture is stored. """ # Put together the URL that will save our request domain = "http://archive.vn" ...
Archives the provided URL using archive. is.
def cli(url, user_agent): """ Archives the provided URL using archive.is. """ kwargs = {} if user_agent: kwargs['user_agent'] = user_agent archive_url = capture(url, **kwargs) click.echo(archive_url)
Get the logo for a channel
def get_channel_image(self, channel, img_size=300, skip_cache=False): """Get the logo for a channel""" from bs4 import BeautifulSoup from wikipedia.exceptions import PageError import re import wikipedia wikipedia.set_lang('fr') if not channel: _LOGGER...
modes: 0 - > simple press 1 - > long press 2 - > release after long press
def press_key(self, key, mode=0): ''' modes: 0 -> simple press 1 -> long press 2 -> release after long press ''' if isinstance(key, str): assert key in KEYS, 'No such key: {}'.format(key) key = KEYS[key] _LOGGER.info('Pr...
Write your forwards methods here.
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for translation in orm['people.PersonTranslation'].objects.all(): if translation.language in ['en', 'de']: translation.ro...
Write your forwards methods here.
def forwards(self, orm): "Write your forwards methods here." for translation in orm['people.PersonTranslation'].objects.all(): translation.person.roman_first_name = translation.roman_first_name translation.person.roman_last_name = translation.roman_last_name translati...
Parse block node. args: scope ( Scope ): Current scope raises: SyntaxError returns: self
def parse(self, scope): """Parse block node. args: scope (Scope): Current scope raises: SyntaxError returns: self """ if not self.parsed: scope.push() self.name, inner = self.tokens scope.current = se...
Raw block name args: clean ( bool ): clean name returns: str
def raw(self, clean=False): """Raw block name args: clean (bool): clean name returns: str """ try: return self.tokens[0].raw(clean) except (AttributeError, TypeError): pass
Format block ( CSS ) args: fills ( dict ): Fill elements returns: str ( CSS )
def fmt(self, fills): """Format block (CSS) args: fills (dict): Fill elements returns: str (CSS) """ f = "%(identifier)s%(ws)s{%(nl)s%(proplist)s}%(eb)s" out = [] name = self.name.fmt(fills) if self.parsed and any( p...
Return a full copy of self returns: Block object
def copy(self): """ Return a full copy of self returns: Block object """ name, inner = self.tokens if inner: inner = [u.copy() if u else u for u in inner] if name: name = name.copy() return Block([name, inner], 0)
Copy block contents ( properties inner blocks ). Renames inner block from current scope. Used for mixins. args: scope ( Scope ): Current scope returns: list ( block contents )
def copy_inner(self, scope): """Copy block contents (properties, inner blocks). Renames inner block from current scope. Used for mixins. args: scope (Scope): Current scope returns: list (block contents) """ if self.tokens[1]: to...
Parse node args: scope ( Scope ): current scope raises: SyntaxError returns: self
def parse(self, scope): """Parse node args: scope (Scope): current scope raises: SyntaxError returns: self """ self.parsed = list(utility.flatten(self.tokens)) if self.parsed[0] == '@import': if len(self.parsed) > 4:...
Parse function. We search for mixins first within current scope then fallback to global scope. The special scope. deferred is used when local scope mixins are called within parent mixins. If nothing is found we fallback to block - mixin as lessc. js allows calls to blocks and mixins to be inter - changable. clx: This m...
def parse(self, scope, error=False, depth=0): """ Parse function. We search for mixins first within current scope then fallback to global scope. The special scope.deferred is used when local scope mixins are called within parent mixins. If nothing is found we fallback to ...
Compile all *. less files in directory Args: inpath ( str ): Path to compile outpath ( str ): Output directory args ( object ): Argparse Object scope ( Scope ): Scope object or None
def ldirectory(inpath, outpath, args, scope): """Compile all *.less files in directory Args: inpath (str): Path to compile outpath (str): Output directory args (object): Argparse Object scope (Scope): Scope object or None """ yacctab = 'yacctab' if args.debug else None ...
Run compiler
def run(): """Run compiler """ aparse = argparse.ArgumentParser( description='LessCss Compiler', epilog='<< jtm@robot.is @_o >>') aparse.add_argument( '-v', '--version', action='version', version=VERSION_STR) aparse.add_argument( '-I', '--include', action="sto...
Parse node. args: scope ( Scope ): Current scope raises: SyntaxError returns: self
def parse(self, scope): """Parse node. args: scope (Scope): Current scope raises: SyntaxError returns: self """ self.keyframe, = [ e[0] if isinstance(e, tuple) else e for e in self.tokens if str(e).strip() ...
r ;
def t_mediaquery_t_semicolon(self, t): r';' # This can happen only as part of a CSS import statement. The # "mediaquery" state is reused there. Ordinary media queries always # end at '{', i.e. when a block is opened. t.lexer.pop_state() # state mediaquery # We have to po...
r
def t_less_variable(self, t): r'@@?[\w-]+|@\{[^@\}]+\}' v = t.value.lower() if v in reserved.tokens: t.type = reserved.tokens[v] if t.type == "css_media": t.lexer.push_state("mediaquery") elif t.type == "css_import": t.lexer.pus...
r ~ |~ \
def t_t_eopen(self, t): r'~"|~\'' if t.value[1] == '"': t.lexer.push_state('escapequotes') elif t.value[1] == '\'': t.lexer.push_state('escapeapostrophe') return t
r [ ^
def t_css_string(self, t): r'"[^"@]*"|\'[^\'@]*\'' t.lexer.lineno += t.value.count('\n') return t
r | \
def t_t_isopen(self, t): r'"|\'' if t.value[0] == '"': t.lexer.push_state('istringquotes') elif t.value[0] == '\'': t.lexer.push_state('istringapostrophe') return t
r [ ^ \
def t_istringapostrophe_css_string(self, t): r'[^\'@]+' t.lexer.lineno += t.value.count('\n') return t
r [ ^
def t_istringquotes_css_string(self, t): r'[^"@]+' t.lexer.lineno += t.value.count('\n') return t
Lex file.
def file(self, filename): """ Lex file. """ with open(filename) as f: self.lexer.input(f.read()) return self
Load lexer with content from file which can be a path or a file like object.
def input(self, file): """ Load lexer with content from `file` which can be a path or a file like object. """ if isinstance(file, string_types): with open(file) as f: self.lexer.input(f.read()) else: self.lexer.input(file.read())
Token function. Contains 2 hacks: 1. Injects ; into blocks where the last property leaves out the ; 2. Strips out whitespace from nonsignificant locations to ease parsing.
def token(self): """ Token function. Contains 2 hacks: 1. Injects ';' into blocks where the last property leaves out the ; 2. Strips out whitespace from nonsignificant locations to ease parsing. """ if self.next_: t = ...
Parse node. Block identifiers are stored as strings with spaces replaced with ? args: scope ( Scope ): Current scope raises: SyntaxError returns: self
def parse(self, scope): """Parse node. Block identifiers are stored as strings with spaces replaced with ? args: scope (Scope): Current scope raises: SyntaxError returns: self """ names = [] name = [] self._subp ...
Find root of identifier from scope args: scope ( Scope ): current scope names ( list ): identifier name list ( separated identifiers ) returns: list
def root(self, scope, names): """Find root of identifier, from scope args: scope (Scope): current scope names (list): identifier name list (, separated identifiers) returns: list """ parent = scope.scopename if parent: paren...
Raw identifier. args: clean ( bool ): clean name returns: str
def raw(self, clean=False): """Raw identifier. args: clean (bool): clean name returns: str """ if clean: return ''.join(''.join(p) for p in self.parsed).replace('?', ' ') return '%'.join('%'.join(p) for p in self.parsed).strip().strip('...
Return copy of self Returns: Identifier object
def copy(self): """ Return copy of self Returns: Identifier object """ tokens = ([t for t in self.tokens] if isinstance(self.tokens, list) else self.tokens) return Identifier(tokens, 0)
Format identifier args: fills ( dict ): replacements returns: str ( CSS )
def fmt(self, fills): """Format identifier args: fills (dict): replacements returns: str (CSS) """ name = ',$$'.join(''.join(p).strip() for p in self.parsed) name = re.sub('\?(.)\?', '%(ws)s\\1%(ws)s', name) % fills return name.replace('$$'...
Add block element to scope Args: block ( Block ): Block object
def add_block(self, block): """Add block element to scope Args: block (Block): Block object """ self[-1]['__blocks__'].append(block) self[-1]['__names__'].append(block.raw())
Remove block element from scope Args: block ( Block ): Block object
def remove_block(self, block, index="-1"): """Remove block element from scope Args: block (Block): Block object """ self[index]["__blocks__"].remove(block) self[index]["__names__"].remove(block.raw())
Add mixin to scope Args: mixin ( Mixin ): Mixin object
def add_mixin(self, mixin): """Add mixin to scope Args: mixin (Mixin): Mixin object """ raw = mixin.tokens[0][0].raw() if raw in self._mixins: self._mixins[raw].append(mixin) else: self._mixins[raw] = [mixin]
Search for variable by name. Searches scope top down Args: name ( string ): Search term Returns: Variable object OR False
def variables(self, name): """Search for variable by name. Searches scope top down Args: name (string): Search term Returns: Variable object OR False """ if isinstance(name, tuple): name = name[0] if name.startswith('@{'): n...
Search mixins for name. Allow > to be ignored.. a. b () ==. a >. b () Args: name ( string ): Search term Returns: Mixin object list OR False
def mixins(self, name): """ Search mixins for name. Allow '>' to be ignored. '.a .b()' == '.a > .b()' Args: name (string): Search term Returns: Mixin object list OR False """ m = self._smixins(name) if m: return m return...
Inner wrapper to search for mixins by name.
def _smixins(self, name): """Inner wrapper to search for mixins by name. """ return (self._mixins[name] if name in self._mixins else False)
Search for defined blocks recursively. Allow > to be ignored.. a. b ==. a >. b Args: name ( string ): Search term Returns: Block object OR False
def blocks(self, name): """ Search for defined blocks recursively. Allow '>' to be ignored. '.a .b' == '.a > .b' Args: name (string): Search term Returns: Block object OR False """ b = self._blocks(name) if b: return b ...
Inner wrapper to search for blocks by name.
def _blocks(self, name): """Inner wrapper to search for blocks by name. """ i = len(self) while i >= 0: i -= 1 if name in self[i]['__names__']: for b in self[i]['__blocks__']: r = b.raw() if r and r == name: ...
Update scope. Add another scope to this one. Args: scope ( Scope ): Scope object Kwargs: at ( int ): Level to update
def update(self, scope, at=0): """Update scope. Add another scope to this one. Args: scope (Scope): Scope object Kwargs: at (int): Level to update """ if hasattr(scope, '_mixins') and not at: self._mixins.update(scope._mixins) self[at][...
Swap variable name for variable value Args: name ( str ): Variable name Returns: Variable value ( Mixed )
def swap(self, name): """ Swap variable name for variable value Args: name (str): Variable name Returns: Variable value (Mixed) """ if name.startswith('@@'): var = self.variables(name[1:]) if var is False: raise Synt...
Process tokenslist flattening and parsing it args: tokens ( list ): tokenlist scope ( Scope ): Current scope returns: list
def process(self, tokens, scope): """ Process tokenslist, flattening and parsing it args: tokens (list): tokenlist scope (Scope): Current scope returns: list """ while True: tokens = list(utility.flatten(tokens)) done = ...
Replace variables in tokenlist args: tokens ( list ): tokenlist scope ( Scope ): Current scope returns: list
def replace_variables(self, tokens, scope): """ Replace variables in tokenlist args: tokens (list): tokenlist scope (Scope): Current scope returns: list """ list = [] for t in tokens: if utility.is_variable(t): ...
Parse node args: scope ( Scope ): current scope raises: SyntaxError returns: self
def parse(self, scope): """Parse node args: scope (Scope): current scope raises: SyntaxError returns: self """ if not self.parsed: if len(self.tokens) > 2: property, style, _ = self.tokens sel...
Hackish preprocessing from font shorthand tags. Skips expression parse on certain tags. args: style ( list ):. returns: list
def preprocess(self, style): """Hackish preprocessing from font shorthand tags. Skips expression parse on certain tags. args: style (list): . returns: list """ if self.property == 'font': style = [ ''.join(u.expression()...
Format node args: fills ( dict ): replacements returns: str
def fmt(self, fills): """ Format node args: fills (dict): replacements returns: str """ f = "%(tab)s%(property)s:%(ws)s%(style)s%(important)s;%(nl)s" imp = ' !important' if self.important else '' if fills['nl']: self.parsed = [ ...
Parse node args: scope ( Scope ): current scope raises: SyntaxError returns: self
def parse(self, scope): """Parse node args: scope (Scope): current scope raises: SyntaxError returns: self """ self.name, args, self.guards = self.tokens[0] self.args = [a for a in utility.flatten(args) if a] self.body =...
Parse arguments to mixin. Add them to scope as variables. Sets upp special variable
def parse_args(self, args, scope): """Parse arguments to mixin. Add them to scope as variables. Sets upp special variable @arguments as well. args: args (list): arguments scope (Scope): current scope raises: SyntaxError """ argu...
Parse a single argument to mixin. args: var ( Variable object ): variable arg ( mixed ): argument scope ( Scope object ): current scope returns: Variable object or None
def _parse_arg(self, var, arg, scope): """ Parse a single argument to mixin. args: var (Variable object): variable arg (mixed): argument scope (Scope object): current scope returns: Variable object or None """ if isinstance(var, Var...
Parse guards on mixin. args: scope ( Scope ): current scope raises: SyntaxError returns: bool ( passes guards )
def parse_guards(self, scope): """Parse guards on mixin. args: scope (Scope): current scope raises: SyntaxError returns: bool (passes guards) """ if self.guards: cor = True if ',' in self.guards else False for g ...
Call mixin. Parses a copy of the mixins body in the current scope and returns it. args: scope ( Scope ): current scope args ( list ): arguments raises: SyntaxError returns: list or False
def call(self, scope, args=[]): """Call mixin. Parses a copy of the mixins body in the current scope and returns it. args: scope (Scope): current scope args (list): arguments raises: SyntaxError returns: list or False """ ...
Parse function args: scope ( Scope ): Scope object returns: self
def parse(self, scope): """ Parse function args: scope (Scope): Scope object returns: self """ self.name, _, self.value = self.tokens if isinstance(self.name, tuple): if len(self.name) > 1: self.name, pad = self.name ...
Parse Node within scope. the functions ~ ( and e ( map to self. escape and % ( maps to self. sformat args: scope ( Scope ): Current scope
def parse(self, scope): """Parse Node within scope. the functions ~( and e( map to self.escape and %( maps to self.sformat args: scope (Scope): Current scope """ name = ''.join(self.tokens[0]) parsed = self.process(self.tokens[1:], scope) if n...
String format. args: string ( str ): string to format args ( list ): format options returns: str
def sformat(self, string, *args): """ String format. args: string (str): string to format args (list): format options returns: str """ format = string items = [] m = re.findall('(%[asdA])', format) if m and not args: ...
Is number args: string ( str ): match returns: bool
def isnumber(self, string, *args): """Is number args: string (str): match returns: bool """ try: n, u = utility.analyze_number(string) except SyntaxError: return False return True
Is url args: string ( str ): match returns: bool
def isurl(self, string, *args): """Is url args: string (str): match returns: bool """ arg = utility.destring(string) regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9]...
Is string args: string ( str ): match returns: bool
def isstring(self, string, *args): """Is string args: string (str): match returns: bool """ regex = re.compile(r'\'[^\']*\'|"[^"]*"') return regex.match(string)
Increment function args: value ( str ): target returns: str
def increment(self, value, *args): """ Increment function args: value (str): target returns: str """ n, u = utility.analyze_number(value) return utility.with_unit(n + 1, u)
Add integers args: args ( list ): target returns: str
def add(self, *args): """ Add integers args: args (list): target returns: str """ if (len(args) <= 1): return 0 return sum([int(v) for v in args])
Round number args: value ( str ): target returns: str
def round(self, value, *args): """ Round number args: value (str): target returns: str """ n, u = utility.analyze_number(value) return utility.with_unit( int(utility.away_from_zero_round(float(n))), u)
Ceil number args: value ( str ): target returns: str
def ceil(self, value, *args): """ Ceil number args: value (str): target returns: str """ n, u = utility.analyze_number(value) return utility.with_unit(int(math.ceil(n)), u)
Return percentage value args: value ( str ): target returns: str
def percentage(self, value, *args): """ Return percentage value args: value (str): target returns: str """ n, u = utility.analyze_number(value) n = int(n * 100.0) u = '%' return utility.with_unit(n, u)
Process color expression args: expression ( tuple ): color expression returns: str
def process(self, expression): """ Process color expression args: expression (tuple): color expression returns: str """ a, o, b = expression c1 = self._hextorgb(a) c2 = self._hextorgb(b) r = ['#'] for i in range(3): ...
Do operation on colors args: left ( str ): left side right ( str ): right side operation ( str ): Operation returns: str
def operate(self, left, right, operation): """ Do operation on colors args: left (str): left side right (str): right side operation (str): Operation returns: str """ operation = { '+': operator.add, '-': oper...
Translate rgb (... ) to color string raises: ValueError returns: str
def rgb(self, *args): """ Translate rgb(...) to color string raises: ValueError returns: str """ if len(args) == 4: args = args[:3] if len(args) == 3: try: return self._rgbatohex(list(map(int, args))) ...
Translate rgba (... ) to color string raises: ValueError returns: str
def rgba(self, *args): """ Translate rgba(...) to color string raises: ValueError returns: str """ if len(args) == 4: try: falpha = float(list(args)[3]) if falpha > 1: args = args[:3] ...
Translate argb (... ) to color string
def argb(self, *args): """ Translate argb(...) to color string Creates a hex representation of a color in #AARRGGBB format (NOT #RRGGBBAA!). This format is used in Internet Explorer, and .NET and Android development. raises: ValueError returns: s...
Translate hsl (... ) to color string raises: ValueError returns: str
def hsl(self, *args): """ Translate hsl(...) to color string raises: ValueError returns: str """ if len(args) == 4: return self.hsla(*args) elif len(args) == 3: h, s, l = args rgb = colorsys.hls_to_rgb( ...
Translate hsla (... ) to color string raises: ValueError returns: str
def hsla(self, *args): """ Translate hsla(...) to color string raises: ValueError returns: str """ if len(args) == 4: h, s, l, a = args rgb = colorsys.hls_to_rgb( int(h) / 360.0, utility.pc_or_float(l), utility.pc_or...
Return the hue value of a color args: color ( str ): color raises: ValueError returns: float
def hue(self, color, *args): """ Return the hue value of a color args: color (str): color raises: ValueError returns: float """ if color: h, l, s = self._hextohls(color) return utility.convergent_round(h * 360.0,...
Return the saturation value of a color args: color ( str ): color raises: ValueError returns: float
def saturation(self, color, *args): """ Return the saturation value of a color args: color (str): color raises: ValueError returns: float """ if color: h, l, s = self._hextohls(color) return s * 100.0 rai...
Lighten a color args: color ( str ): color diff ( str ): percentage returns: str
def lighten(self, color, diff, *args): """ Lighten a color args: color (str): color diff (str): percentage returns: str """ if color and diff: return self._ophsl(color, diff, 1, operator.add) raise ValueError('Illegal color ...
Darken a color args: color ( str ): color diff ( str ): percentage returns: str
def darken(self, color, diff, *args): """ Darken a color args: color (str): color diff (str): percentage returns: str """ if color and diff: return self._ophsl(color, diff, 1, operator.sub) raise ValueError('Illegal color va...
Spin color by degree. ( Increase/ decrease hue ) args: color ( str ): color degree ( str ): percentage raises: ValueError returns: str
def spin(self, color, degree, *args): """ Spin color by degree. (Increase / decrease hue) args: color (str): color degree (str): percentage raises: ValueError returns: str """ if color and degree: if isinstance(d...
This algorithm factors in both the user - provided weight and the difference between the alpha values of the two colors to decide how to perform the weighted average of the two RGB values.
def mix(self, color1, color2, weight=50, *args): """This algorithm factors in both the user-provided weight and the difference between the alpha values of the two colors to decide how to perform the weighted average of the two RGB values. It works by first normalizing both parameters to...
Format CSS Hex color code. uppercase becomes lowercase 3 digit codes expand to 6 digit. args: color ( str ): color raises: ValueError returns: str
def fmt(self, color): """ Format CSS Hex color code. uppercase becomes lowercase, 3 digit codes expand to 6 digit. args: color (str): color raises: ValueError returns: str """ if utility.is_color(color): color = colo...
Flatten list. Args: lst ( list ): List to flatten Returns: generator
def flatten(lst): """Flatten list. Args: lst (list): List to flatten Returns: generator """ for elm in lst: if isinstance(elm, collections.Iterable) and not isinstance( elm, string_types): for sub in flatten(elm): yield sub ...
yield item i and item i + 1 in lst. e. g. ( lst [ 0 ] lst [ 1 ] ) ( lst [ 1 ] lst [ 2 ] )... ( lst [ - 1 ] None ) Args: lst ( list ): List to process Returns: list
def pairwise(lst): """ yield item i and item i+1 in lst. e.g. (lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[-1], None) Args: lst (list): List to process Returns: list """ if not lst: return length = len(lst) for i in range(length - 1): yield lst[i], ls...
Rename all sub - blocks moved under another block. ( mixins ) Args: lst ( list ): block list scope ( object ): Scope object
def rename(blocks, scope, stype): """ Rename all sub-blocks moved under another block. (mixins) Args: lst (list): block list scope (object): Scope object """ for p in blocks: if isinstance(p, stype): p.tokens[0].parse(scope) if p.tokens[1]: ...
Recursive search for name in block ( inner blocks ) Args: name ( str ): search term Returns: Block OR False
def blocksearch(block, name): """ Recursive search for name in block (inner blocks) Args: name (str): search term Returns: Block OR False """ if hasattr(block, 'tokens'): for b in block.tokens[1]: b = (b if hasattr(b, 'raw') and b.raw() == name else blocksearch( ...
Reverse guard expression. not (
def reverse_guard(lst): """ Reverse guard expression. not (@a > 5) -> (@a =< 5) Args: lst (list): Expression returns: list """ rev = {'<': '>=', '>': '=<', '>=': '<', '=<': '>'} return [rev[l] if l in rev else l for l in lst]
Print scope tree args: lst ( list ): parse result lvl ( int ): current nesting level
def debug_print(lst, lvl=0): """ Print scope tree args: lst (list): parse result lvl (int): current nesting level """ pad = ''.join(['\t.'] * lvl) t = type(lst) if t is list: for p in lst: debug_print(p, lvl) elif hasattr(lst, 'tokens'): print(pad,...
Analyse number for type and split from unit 1px - > ( q px ) args: var ( str ): number string kwargs: err ( str ): Error message raises: SyntaxError returns: tuple
def analyze_number(var, err=''): """ Analyse number for type and split from unit 1px -> (q, 'px') args: var (str): number string kwargs: err (str): Error message raises: SyntaxError returns: tuple """ n, u = split_unit(var) if not isinstance(var, s...
Return number with unit args: number ( mixed ): Number unit ( str ): Unit returns: str
def with_unit(number, unit=None): """ Return number with unit args: number (mixed): Number unit (str): Unit returns: str """ if isinstance(number, tuple): number, unit = number if number == 0: return '0' if unit: number = str(number) if...
Is string CSS color args: value ( str ): string returns: bool
def is_color(value): """ Is string CSS color args: value (str): string returns: bool """ if not value or not isinstance(value, string_types): return False if value[0] == '#' and len(value) in [4, 5, 7, 9]: try: int(value[1:], 16) return Tru...
Check if string is LESS variable args: value ( str ): string returns: bool
def is_variable(value): """ Check if string is LESS variable args: value (str): string returns: bool """ if isinstance(value, string_types): return (value.startswith('@') or value.startswith('-@')) elif isinstance(value, tuple): value = ''.join(value) retu...
Is value float args: value ( str ): string returns: bool
def is_float(value): """ Is value float args: value (str): string returns: bool """ if not is_int(value): try: float(str(value)) return True except (ValueError, TypeError): pass return False
Split a number from its unit 1px - > ( q px ) Args: value ( str ): input returns: tuple
def split_unit(value): """ Split a number from its unit 1px -> (q, 'px') Args: value (str): input returns: tuple """ r = re.search('^(\-?[\d\.]+)(.*)$', str(value)) return r.groups() if r else ('', '')
Round half - way away from zero.
def away_from_zero_round(value, ndigits=0): """Round half-way away from zero. Python2's round() method. """ if sys.version_info[0] >= 3: p = 10**ndigits return float(math.floor((value * p) + math.copysign(0.5, value))) / p else: return round(value, ndigits)
Convergent rounding.
def convergent_round(value, ndigits=0): """Convergent rounding. Round to neareas even, similar to Python3's round() method. """ if sys.version_info[0] < 3: if value < 0.0: return -convergent_round(-value) epsilon = 0.0000001 integral_part, _ = divmod(value, 1) ...
Utility function to process strings that contain either percentiles or floats args: str: s returns: float
def pc_or_float(s): """ Utility function to process strings that contain either percentiles or floats args: str: s returns: float """ if isinstance(s, string_types) and '%' in s: return float(s.strip('%')) / 100.0 return float(s)
Return successive r length permutations of elements in the iterable.
def permutations_with_replacement(iterable, r=None): """Return successive r length permutations of elements in the iterable. Similar to itertools.permutation but withouth repeated values filtering. """ pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in itertools.p...