Parses a string containing a 'cut' expression
 It can be a set (`{Dim.Mem, Dim2.Mem2}`), a range (`([Time].[Year].[1997]:[Time].[Year].[1998])`), a member identifier (`[Time].[Year].[1998]`) or a NamedSet.
340369
def parse_cut(cube, cut_expr)
      p = mdx_parser.parseExpression(cut_expr)

      case p
      when org.olap4j.mdx.CallNode
        case p.getOperatorName
        when '{}'
          # check that the set contains only Members of a single dimension level
          set_members = p.getArgList.map do |id_node|
            get_member(cube, unparse_node(id_node))
          end

          if set_members.any?(&:nil?)
            error!('Illegal cut. Unknown member in cut set', 400)
          end

          ls = set_members.map(&:raw_level).uniq
          error!('Illegal cut: ' + cut_expr, 400) unless ls.size == 1
          { level: ls.first, cut: unparse_node(p), type: :set, set_members: set_members }
        when '()'
          # check that the range contains a valid range

          unless p.getArgList.first.is_a?(org.olap4j.mdx.CallNode) \
            && (p.getArgList.first.getOperatorName == ':')
            error!('Illegal cut: ' + cut_expr, 400)
          end

          ls = p.getArgList.first.getArgList.map do |id_node|
            get_member(cube, unparse_node(id_node)).raw_level
          end.uniq

          error!('Illegal cut: ' + cut_expr, 400) unless ls.size == 1

          { level: ls.first, cut: unparse_node(p), type: :range }
        else
          error!('Illegal cut: ' + cut_expr, 400)
        end
      when org.olap4j.mdx.IdentifierNode

        # does cut_expr look like a NamedSet?
        s = get_named_set(cube, cut_expr)
        return { level: nil, cut: cut_expr, type: :named_set } unless s.nil?

        # if `cut_expr` looks like a member, check that it's level is
        # equal to `level`
        m = get_member(cube, cut_expr)

        if m.nil?
          error!("Illegal cut: #{cut_expr} — Member does not exist", 400)
        end

        { level: m.raw_level, cut: cut_expr, type: :member }
      else
        error!('Illegal cut: ' + cut_expr, 400)
      end
    end
373769
function parse(string) {
            var match = isoDateExpression.exec(string);
            if (match) {
                // parse months, days, hours, minutes, seconds, and milliseconds
                // provide default values if necessary
                // parse the UTC offset component
                var year = $Number(match[1]),
                    month = $Number(match[2] || 1) - 1,
                    day = $Number(match[3] || 1) - 1,
                    hour = $Number(match[4] || 0),
                    minute = $Number(match[5] || 0),
                    second = $Number(match[6] || 0),
                    millisecond = Math.floor($Number(match[7] || 0) * 1000),
                    // When time zone is missed, local offset should be used
                    // (ES 5.1 bug)
                    // see https://bugs.ecmascript.org/show_bug.cgi?id=112
                    isLocalTime = Boolean(match[4] && !match[8]),
                    signOffset = match[9] === '-' ? 1 : -1,
                    hourOffset = $Number(match[10] || 0),
                    minuteOffset = $Number(match[11] || 0),
                    result;
                var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0;
                if (
                    hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) &&
                    minute < 60 && second < 60 && millisecond < 1000 &&
                    month > -1 && month < 12 && hourOffset < 24 &&
                    minuteOffset < 60 && // detect invalid offsets
                    day > -1 &&
                    day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month))
                ) {
                    result = (
                        (dayFromMonth(year, month) + day) * 24 +
                        hour +
                        hourOffset * signOffset
                    ) * 60;
                    result = (
                        (result + minute + minuteOffset * signOffset) * 60 +
                        second
                    ) * 1000 + millisecond;
                    if (isLocalTime) {
                        result = toUTC(result);
                    }
                    if (-8.64e15 <= result && result <= 8.64e15) {
                        return result;
                    }
                }
                return NaN;
            }
            return NativeDate.parse.apply(this, arguments);
        }
1317898
def from_string(cls, s):
        """"""
        tables = []
        seen = set()
        current_table = None
        lines = list(reversed(s.splitlines()))  # to pop() in right order
        while lines:
            line = lines.pop().strip()
            table_m = re.match(r'^(?P<table>\w.+):$', line)
            field_m = re.match(r'\s*(?P<name>\S+)'
                               r'(\s+(?P<attrs>[^#]+))?'
                               r'(\s*#\s*(?P<comment>.*)$)?',
                               line)
            if table_m is not None:
                table_name = table_m.group('table')
                if table_name in seen:
                    raise ItsdbError(
                        'Table {} already defined.'.format(table_name)
                    )
                current_table = (table_name, [])
                tables.append(current_table)
                seen.add(table_name)
            elif field_m is not None and current_table is not None:
                name = field_m.group('name')
                attrs = field_m.group('attrs').split()
                datatype = attrs.pop(0)
                key = ':key' in attrs
                partial = ':partial' in attrs
                comment = field_m.group('comment')
                current_table[1].append(
                    Field(name, datatype, key, partial, comment)
                )
            elif line != '':
                raise ItsdbError('Invalid line: ' + line)
        return cls(tables)
617132
def _parse_string(self):
        """"""
        if self._next_token() in ['{', '(']:
            field = self._parse_field()
            if field:
                self.definitions[field[0]] = field[1]
718413
def parse_term(s):
    """"""
    size, s = s.split(b':', 1)
    size = int(size)
    return s[:size], s[size:]
148479
def _parse_expression(s):
    """"""

    # Converters for opeartor clauses
    operators = {
        'and': And,
        'or': Or,
        None: lambda *args: args[0]
    }

    # Pairing of end group symbols with start group symbols
    group_pairs = {
        ')': '(',
        ']': '['
    }

    scanner = re.compile(r'''
        (\s+) |              # space
        (\(|\[) |            # group_start
        (\)|\]) |            # group_end
        ((?:or|and)\b) |     # operator
        ([^\s\(\)\[\]]+) |   # variable
        (\Z) |               # end
        (.)                  # error
    ''', re.DOTALL | re.VERBOSE | re.UNICODE | re.IGNORECASE)

    # Parsed using two states and a stack of open clauses
    # At state 0 (not expect_operator): Expect variable, or parenthesis group
    #  start.
    # At state 1 (expect_operator): Expect operator, parenthesis group end, or
    #  end.
    expect_operator = False
    clause_stack = []
    current_clause = []
    clause_operator = None
    clause_symbol = None

    def close():
        prev_op, prev_symbol, prev_clause = clause_stack.pop()
        prev_clause.append(operators[clause_operator](*current_clause))
        return prev_op, prev_symbol, prev_clause

    for match in re.finditer(scanner, s):
        (space, group_start, group_end, operator, variable, end,
            error) = match.groups()

        if error is not None:
            raise ParseError('Invalid token in expression string: {}'.format(
                repr(match.group(0))), span=(match.start(), match.end()))
        elif space is not None:
            continue
        elif expect_operator and operator is not None:
            operator = operator.lower()
            if operator == 'and' and clause_operator != 'and':
                prev_term = current_clause.pop()
                clause_stack.append(
                    (clause_operator, clause_symbol, current_clause))
                current_clause = [prev_term]
            elif operator == 'or' and clause_operator == 'and':
                clause_operator, clause_symbol, current_clause = close()
            clause_operator = operator
            expect_operator = False
        elif expect_operator and group_end is not None:
            if clause_operator == 'and':
                clause_operator, clause_symbol, current_clause = close()
            if len(clause_stack) == 0:
                raise ParseError(
                    'Unbalanced parenthesis group in expression',
                    span=(match.start(), match.end()))
            if group_pairs[group_end] != clause_symbol:
                raise ParseError(
                    'Group started with {} ended with {}'.format(
                        clause_symbol, group_end),
                    span=(match.start(), match.end()))
            clause_operator, clause_symbol, current_clause = close()
        elif expect_operator and end is not None:
            if clause_operator == 'and':
                clause_operator, clause_symbol, current_clause = close()
        elif not expect_operator and variable is not None:
            current_clause.append(Variable(variable))
            expect_operator = True
        elif not expect_operator and group_start is not None:
            clause_stack.append(
                (clause_operator, clause_symbol, current_clause))
            current_clause = []
            clause_operator = None
            clause_symbol = group_start
        else:
            raise ParseError(
                'Invalid token in expression string: {!r}'.format(
                    match.group(0)),
                span=(match.start(), match.end()))

    if len(clause_stack) > 0:
        raise ParseError('Unbalanced parenthesis group in expression')

    expr = operators[clause_operator](*current_clause)
    return expr
1063213
private int processSet(String regex, int i, StringBuilder result, UnicodeSet temp, ParsePosition pos) {
        try {
            pos.setIndex(i);
            UnicodeSet x = temp.clear().applyPattern(regex, pos, symbolTable, 0);
            x.complement().complement(); // hack to fix toPattern
            result.append(x.toPattern(false));
            i = pos.getIndex() - 1; // allow for the loop increment
            return i;
        } catch (Exception e) {
            throw (IllegalArgumentException) new IllegalArgumentException("Error in " + regex).initCause(e);
        }
    }
16831
def parse(self, expression):
        
        if isinstance(expression, (list, dict)):
            return (True if expression else False, expression)
        if sys.version_info[0] > 2:
            self.next = self.tokenize(expression).__next__
        else:
            self.next = self.tokenize(expression).next
        self.token = self.next()
        return self.expression()
646740
def parse(self, string, parent):
        """"""
        result = {}
        for member in self.RE_MEMBERS.finditer(string):
            mems = self._process_member(member, parent, string)
            #The regex match could contain multiple members that were defined
            #on the same line in the code file.
            for onemem in mems:
                result[onemem.name.lower()] = onemem
                
        return result
1085912
def _fstring_parse(s, i, level, parts, exprs):
    """"""
    while True:
        i, parse_expr = _find_literal(s, i, level, parts, exprs)
        if i == len(s) or s[i] == '}':
            return i
        if parse_expr:
            i = _find_expr(s, i, level, parts, exprs)
84393
def _process_member(self, member, parent, string):
        """"""
        #The modifiers regex is very greedy so we have some cleaning up to do
        #to extract the mods.
        modifiers = member.group("modifiers")
        dimension = None
        
        if modifiers is not None:
            #Unfortunately, the dimension can also be specified as a modifier and
            #the dimensions can include variable names and functions. This introduces
            #the possibility of nested lists.
            modifiers = modifiers.lower()
            if "dimension" in modifiers:
                start, end = self._get_dim_modifier(modifiers)
                dimension = modifiers[start+1:end]
                dimtext = modifiers[modifiers.index("dimension"):end+1]
                modifiers = re.split(",\s*", modifiers.replace(dimtext, "").strip())
                #modifiers.append("dimension")
            else:
                modifiers = re.split("[,\s]+", modifiers.strip())

            if "" in modifiers:
                modifiers.remove("")

        dtype = member.group("type")
        kind = member.group("kind")
        names = member.group("names")

        #If there are multiple vars defined on this line we need to return
        #a list of all of them.
        result = []

        #They might have defined multiple vars on the same line
        refstring = string[member.start():member.end()].strip()
        if parent is not None:
            refline = parent.module.linenum(member.start())
        else:
            refline = "?"
        ready = self._separate_multiple_def(re.sub(",\s*", ", ", names.strip()), parent, refstring, refline)
        
        for name, ldimension, default, D in self._clean_multiple_def(ready):
            #Now construct the element and set all the values, then add it in the results list.
            udim = ldimension if ldimension is not None else dimension
            uD = D if ldimension is not None else count_dimensions([dimension])
            result.append(ValueElement(name, modifiers, dtype, kind, default, udim, parent, uD))

        return result
326400
def string_to_expression_parts(expression_str)
      return {} if expression_str.nil?

      parts, interval = split_parts_and_interval(expression_str)

      expression_parts = ::Hash[EXPRESSION_PART_KEYS.zip(parts)]
      expression_parts.select! do |_key, value|
        !value.nil?
      end
      expression_parts[:interval] = interval unless interval.nil?

      expression_parts
    end
206264
def range_parse(s):
    
    chr, se = s.split(":")
    start, end = se.split("-")
    start, end = int(start), int(end)
    if start > end:
        start, end = end, start

    return Range(chr, start, end, 0, 0)
1086611
def cut_range(string):
    
    value_range = string.split(':')
    if len(value_range) == 1:
        start = int(value_range[0])
        stop = start
    elif len(value_range) == 2:
        start, stop = tuple(int(i) if i else None for i in value_range)
    else:
        msg = "{0} is not a valid, 1-indexed range.".format(string)
        raise argparse.ArgumentTypeError(msg)

    if start == 0 or (stop or sys.maxsize) < (start or 0):
        msg = "{0} is not a valid, 1-indexed range.".format(string)
        raise argparse.ArgumentTypeError(msg)

    # Convert from 1-indexed to 0-indexed
    if start is not None and start > 0:
        start -= 1

    return slice(start, stop)
837137
def string(s):
    ''''''
    @Parser
    def string_parser(text, index=0):
        slen, tlen = len(s), len(text)
        if text[index:index + slen] == s:
            return Value.success(index + slen, s)
        else:
            matched = 0
            while matched < slen and index + matched < tlen and text[index + matched] == s[matched]:
                matched = matched + 1
            return Value.failure(index + matched, s)
    return string_parser
170450
def parse_version_string(version_string):
    """"""
    string_parts =  version_string.split(".")
    version_parts = [
        int(re.match("([0-9]*)", string_parts[0]).group(0)),
        int(re.match("([0-9]*)", string_parts[1]).group(0)),
        int(re.match("([0-9]*)", string_parts[2]).group(0))
    ]
    return version_parts
356731
def _str_parser(string):
        
        if not any(c.isalpha() for c in string):
            _string = string[:19]
            _length = len(_string)
            if _length > 10:
                return BaseParser.parse_datetime
            elif 6 <= _length <= 10:
                if ':' in _string:
                    return BaseParser.parse_time
                else:
                    return BaseParser.parse_date
            elif _length < 6:
                return BaseParser.parse_time
            else:
                return BaseParser.parse_special
        else:
            return BaseParser.__parse_not_only_str