Convert BEL string to AST dictionary

    Args:
        belstr: BEL string
        component_type: Empty string or 'subject' or 'object' to indicate that we
            are parsing the subject or object field input
346453
def get_ast_dict(belstr, component_type: str = ""):
    

    errors = []
    parsed = {}
    bels = list(belstr)
    char_locs, errors = parse_chars(bels, errors)
    parsed, errors = parse_functions(belstr, char_locs, parsed, errors)
    parsed, errors = parse_args(bels, char_locs, parsed, errors)
    parsed, errors = arg_types(parsed, errors)
    parsed, errors = parse_relations(belstr, char_locs, parsed, errors)
    parsed, errors = parse_nested(bels, char_locs, parsed, errors)
    errors = parsed_top_level_errors(parsed, errors)

    ast, errors = parsed_to_ast(parsed, errors, component_type=component_type)

    return ast, errors
666438
def map_object_literal(v: Union[str, jsonasobj.JsonObj]) -> ShExJ.ObjectLiteral:
    
    # TODO: isinstance(v, JSGString) should work here, but it doesn't with IRIREF(http://a.example/v1)
    return v if issubclass(type(v), JSGString) or (isinstance(v, JSGObject) and 'type' in v) else \
        ShExJ.IRIREF(v) if isinstance(v, str) else ShExJ.ObjectLiteral(**v._as_dict)
1108499
def _convert_to_ast(self, data_e, size_e=None):
        
        if type(data_e) is bytes:
            # Convert the string into a BVV, *regardless of endness*
            bits = len(data_e) * self.state.arch.byte_width
            data_e = self.state.solver.BVV(data_e, bits)
        elif type(data_e) is int:
            data_e = self.state.solver.BVV(data_e, size_e*self.state.arch.byte_width if size_e is not None
                                       else self.state.arch.bits)
        else:
            data_e = data_e.raw_to_bv()

        return data_e
220391
def parse_component_value(input = @tokens)
      input = TokenScanner.new(input) unless input.is_a?(TokenScanner)

      while input.peek && input.peek[:node] == :whitespace
        input.consume
      end

      if input.peek.nil?
        return create_node(:error, :value => 'empty')
      end

      value = consume_component_value(input)

      while input.peek && input.peek[:node] == :whitespace
        input.consume
      end

      if input.peek.nil?
        value
      else
        create_node(:error, :value => 'extra-input')
      end
    end
1083043
def object_type_repr(obj):
    
    if obj is None:
        return 'None'
    elif obj is Ellipsis:
        return 'Ellipsis'
    if obj.__class__.__module__ == '__builtin__':
        name = obj.__class__.__name__
    else:
        name = obj.__class__.__module__ + '.' + obj.__class__.__name__
    return '%s object' % name
1276494
def is_string_type(type_):
    

    string_types = _get_types(Types.STRING)
    if is_typing_type(type_):
        return type_ in string_types or is_regex_type(type_)
    return type_ in string_types
200926
def _str_to_type_from_member_module(cls, module_, string):
        

        module_name_short, class_name = string.split(cls._DELIMITER_MODULE)
        members = inspect.getmembers(module_, inspect.ismodule)

        for name, module_member in members:
            if module_name_short == name:
                return getattr(module_member, class_name)

        error_message = cls._ERROR_COULD_NOT_FIND_CLASS.format(string)

        raise exception.BunqException(error_message)
788827
def parse_partlist(str):
    '''
    '''
    lines = str.strip().splitlines()
    lines = filter(len, lines)
    hind = header_index(lines)
    if hind is None:
        log.debug('empty partlist found')
        return ([], [])

    header_line = lines[hind]
    header = header_line.split('  ')
    header = filter(len, header)
    positions = [header_line.index(x) for x in header]
    header = [x.strip().split()[0].lower() for x in header]

    data_lines = lines[hind + 1:]

    def parse_data_line(line):
        y = [(h, line[pos1:pos2].strip()) for h, pos1, pos2 in zip(
            header, positions, positions[1:] + [1000])]
        return dict(y)

    data = [parse_data_line(x) for x in data_lines]
    return (header, data)
1229742
def convert_bool(key, val, attr_type, attr={}, cdata=False):
    """"""
    LOG.info('Inside convert_bool(): key="%s", val="%s", type(val) is: "%s"' % (
        unicode_me(key), unicode_me(val), type(val).__name__)
    )

    key, attr = make_valid_xml_name(key, attr)

    if attr_type:
        attr['type'] = get_xml_type(val)
    attrstring = make_attrstring(attr)
    return '<%s%s>%s</%s>' % (key, attrstring, unicode(val).lower(), key)
1224956
def parse(cls, on_str, force_type=None):  # @ReservedAssignment
        """"""

        on_str_orig = on_str

        if on_str is None:
            return None

        if not on_str:
            raise NotObjectNumberError("Got null input")

        if not isinstance(on_str, string_types):
            raise NotObjectNumberError("Must be a string. Got a {} ".format(type(on_str)))

        # if isinstance(on_str, unicode):
        #     dataset = on_str.encode('ascii')

        if force_type:
            type_ = force_type
        else:
            type_ = on_str[0]

        on_str = on_str[1:]

        if type_ not in list(cls.NDS_LENGTH.keys()):
            raise NotObjectNumberError("Unknown type character '{}' for '{}'".format(type_, on_str_orig))

        ds_length = len(on_str) - cls.NDS_LENGTH[type_]

        if ds_length not in cls.DATASET_LENGTHS:
            raise NotObjectNumberError(
                "Dataset string '{}' has an unfamiliar length: {}".format(on_str_orig, ds_length))

        ds_lengths = cls.DATASET_LENGTHS[ds_length]

        assignment_class = ds_lengths[2]

        try:
            dataset = int(ObjectNumber.base62_decode(on_str[0:ds_lengths[0]]))

            if ds_lengths[1]:
                i = len(on_str) - ds_lengths[1]
                revision = int(ObjectNumber.base62_decode(on_str[i:]))
                on_str = on_str[0:i]  # remove the revision
            else:
                revision = None

            on_str = on_str[ds_lengths[0]:]

            if type_ == cls.TYPE.DATASET:
                return DatasetNumber(dataset, revision=revision, assignment_class=assignment_class)

            elif type_ == cls.TYPE.TABLE:
                table = int(ObjectNumber.base62_decode(on_str))
                return TableNumber(
                    DatasetNumber(dataset, assignment_class=assignment_class), table, revision=revision)

            elif type_ == cls.TYPE.PARTITION:
                partition = int(ObjectNumber.base62_decode(on_str))
                return PartitionNumber(
                    DatasetNumber(dataset, assignment_class=assignment_class), partition, revision=revision)

            elif type_ == cls.TYPE.COLUMN:
                table = int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.TABLE]))
                column = int(ObjectNumber.base62_decode(on_str[cls.DLEN.TABLE:]))

                return ColumnNumber(
                    TableNumber(DatasetNumber(dataset, assignment_class=assignment_class), table),
                    column, revision=revision)

            elif type_ == cls.TYPE.OTHER1 or type_ == cls.TYPE.CONFIG:
                    return GeneralNumber1(on_str_orig[0],
                                          DatasetNumber(dataset, assignment_class=assignment_class),
                                          int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.OTHER1])),
                                          revision=revision)

            elif type_ == cls.TYPE.OTHER2:
                    return GeneralNumber2(on_str_orig[0],
                                          DatasetNumber(dataset, assignment_class=assignment_class),
                                          int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.OTHER1])),
                                          int(ObjectNumber.base62_decode(
                                              on_str[cls.DLEN.OTHER1:cls.DLEN.OTHER1+cls.DLEN.OTHER2])),
                                          revision=revision)

            else:

                raise NotObjectNumberError('Unknown type character: ' + type_ + ' in ' + str(on_str_orig))

        except Base62DecodeError as e:
            raise NotObjectNumberError('Unknown character:  ' + str(e))
388553
def parse_type(parser):
    # type: (Parser) -> Union[NamedType, NonNullType, ListType]
    """"""
    start = parser.token.start
    if skip(parser, TokenKind.BRACKET_L):
        ast_type = parse_type(parser)
        expect(parser, TokenKind.BRACKET_R)
        ast_type = ast.ListType(type=ast_type, loc=loc(parser, start))  # type: ignore

    else:
        ast_type = parse_named_type(parser)

    if skip(parser, TokenKind.BANG):
        return ast.NonNullType(type=ast_type, loc=loc(parser, start))

    return ast_type
603115
def _input_to_dict(i):
    
    var_type = _to_variable_type(i["type"])
    if var_type.startswith("Array") and "inputBinding" in i.get("type", {}):
        ib = i["type"]["inputBinding"]
    elif "inputBinding" in i:
        ib = i["inputBinding"]
    else:
        ib = {"prefix": None, "itemSeparator": None, "position": None}
    return {"name": _id_to_localname(i["id"]) if "id" in i else i["name"],
            "variable_type": var_type,
            "prefix": ib["prefix"], "separator": ib["itemSeparator"],
            "position": ib["position"], "is_required": True,
            "default": i.get("default", None), "separate": ib.get("separate", True)}
520823
function htmlToComponent(str, tags, opts) {
  var keys = objectKeys(tags);
  var props = opts.props || {};
  var preserveAttributes = opts.preserveAttributes || [];
  var tagAttributes = [];
  var reactTags={};
  var reactKeys=[];
  var key;
  for(var i = 0; i<keys.length; i++) {
    key = "AB"+Math.random().toString(36).substring(2);
    if(typeof tags[keys[i]] !== "function") {
      if(typeof tags[keys[i]].slice !== "function") continue;
      tagAttributes = tags[keys[i]].slice(0,-1);
      reactTags[key] = tags[keys[i]].slice(-1)[0];
    }
    else
      reactTags[key] = tags[keys[i]];

    reactKeys.push(key);

    str = str
      .replace(new RegExp("(<\/?)"+keys[i]+"(?:[^>\"']|\".*\"|'.*')*>", "ig"), function(match, start){
        // find/replace spell-save attributes within tag to restore capitals
        if(start !== "</")
          for(var a=0; a<tagAttributes.length; a++)
            match = replaceAttribute(match, tagAttributes[a], tagAttributes[a]);

        // replace key
        return match
          .replace(new RegExp(start+keys[i]+"(\\s|>)", "i"), start+key+"$1");
      });
  }

  // remove/disable html comments
  str = str.replace(/<!--|-->/g,"")

  // find/replace global spell-save attributes to restore capitals
  var attributes = preserveReactAttributes.concat(preserveAttributes);
  for(var i=0; i<attributes.length; i++) 
    str = replaceAttribute(str, attributes[i], attributes[i]);
 
  var jsx = htmlToJsx(str);

  // replace props variables {key} with corrected variables {props['key']}
  for(var key in props) {
    jsx = jsx
      .replace(new RegExp("(\{"+key+"\})","g"),"{props['"+key+"']}");
  }
  
  var component = ReactTransform(jsx).code;
  
  // replace component variables (ComponentName) with corrected variables (tags['ComponentName'])
  for(var i=0; i<reactKeys.length; i++) {
    component = component
      .replace(new RegExp(reactKeys[i],"g"), "reactTags['"+reactKeys[i]+"']"); 
  }

  return eval(component);
}
738689
def as_bel(self) -> str:
        """"""
        return '{}(fus({}:{}, "{}", {}:{}, "{}"))'.format(
            self._func,
            self.partner_5p.namespace,
            self.partner_5p._priority_id,
            self.range_5p.as_bel(),
            self.partner_3p.namespace,
            self.partner_3p._priority_id,
            self.range_3p.as_bel(),
        )
1213726
def as_bel(self) -> str:
        """"""
        return "{}({}:{})".format(
            self._func,
            self.namespace,
            ensure_quotes(self._priority_id)
        )
807334
def __convert_string_type(self, p_c_tuple):
        # type: (Tuple[text_type,...])->Tuple[text_type]
        
        if not isinstance(p_c_tuple, tuple):
            raise Exception('Pos condition expects tuple of string. However = {}'.format(p_c_tuple))

        converted = [text_type] * len(p_c_tuple)
        for i, pos_element in enumerate(p_c_tuple):
            if six.PY2 and isinstance(pos_element, str):
                """str into unicode if python2.x"""
                converted[i] = pos_element.decode(self.string_encoding)
            elif six.PY2 and isinstance(pos_element, text_type):
                converted[i] = pos_element
            elif six.PY3:
                converted[i] = pos_element
            else:
                raise Exception()

        return tuple(converted)
1114391
def print_tree(self, ast_obj=None):
        

        if not ast_obj:
            ast_obj = self

        if hasattr(self, "bel_subject"):
            print("Subject:")
            self.bel_subject.print_tree(self.bel_subject, indent=0)

        if hasattr(self, "bel_relation"):
            print("Relation:", self.bel_relation)

        if hasattr(self, "bel_object"):
            if self.bel_object.type == "BELAst":
                if hasattr(self, "bel_subject"):
                    print("Nested Subject:")
                    self.bel_object.bel_subject.print_tree(indent=0)

                if hasattr(self, "bel_relation"):
                    print("Nested Relation:", self.bel_object.bel_relation)

                if hasattr(self, "bel_object"):
                    print("Nested Object:")
                    self.bel_object.bel_object.print_tree(indent=0)
            else:
                print("Object:")
                self.bel_object.print_tree(self.bel_object, indent=0)

        return self