Extract schemas from 'source'.

    The 'source' parameter must be a string, and should be valid python
    source.

    If 'source' is not valid python source, a SyntaxError will be raised.

    :returns: a list of ViewSchema objects.
502495
def extract_schemas_from_source(source, filename='<unknown>'):
    
    # Track which acceptable services have been configured.
    acceptable_services = set()
    # Track which acceptable views have been configured:
    acceptable_views = {}
    schemas_found = []
    ast_tree = ast.parse(source, filename)
    simple_names = _get_simple_assignments(ast_tree)

    assigns = [n for n in ast_tree.body if isinstance(n, ast.Assign)]
    call_assigns = [n for n in assigns if isinstance(n.value, ast.Call)]

    # We need to extract the AcceptableService-related views. We parse the
    # assignations twice: The first time to extract the AcceptableService
    # instances, the second to extract the views created on those services.
    for assign in call_assigns:
        if isinstance(assign.value.func, ast.Attribute):
            continue
        if assign.value.func.id == 'AcceptableService':
            for target in assign.targets:
                acceptable_services.add(target.id)

    for assign in call_assigns:
        # only consider calls which are attribute accesses, AND
        # calls where the object being accessed is in acceptable_services, AND
        # calls where the attribute being accessed is the 'api' method.
        if isinstance(assign.value.func, ast.Attribute) and \
           assign.value.func.value.id in acceptable_services and \
           assign.value.func.attr == 'api':
            # this is a view. We need to extract the url and methods specified.
            # they may be specified positionally or via a keyword.
            url = None
            name = None
            # methods has a default value:
            methods = ['GET']

            # This is a view - the URL is the first positional argument:
            args = assign.value.args
            if len(args) >= 1:
                url = ast.literal_eval(args[0])
            if len(args) >= 2:
                name = ast.literal_eval(args[1])
            kwargs = assign.value.keywords
            for kwarg in kwargs:
                if kwarg.arg == 'url':
                    url = ast.literal_eval(kwarg.value)
                if kwarg.arg == 'methods':
                    methods = ast.literal_eval(kwarg.value)
                if kwarg.arg == 'view_name':
                    name = ast.literal_eval(kwarg.value)
            if url and name:
                for target in assign.targets:
                    acceptable_views[target.id] = {
                        'url': url,
                        'name': name,
                        'methods': methods,
                    }

    # iterate over all functions, attempting to find the views.
    functions = [n for n in ast_tree.body if isinstance(n, ast.FunctionDef)]
    for function in functions:
        input_schema = None
        output_schema = None
        doc = ast.get_docstring(function)
        api_options_list = []
        for decorator in function.decorator_list:
            if not isinstance(decorator, ast.Call):
                continue
            if isinstance(decorator.func, ast.Attribute):
                decorator_name = decorator.func.value.id
                # extract version this view was introduced at, which can be
                # specified as an arg or a kwarg:
                version = None
                for kwarg in decorator.keywords:
                    if kwarg.arg == 'introduced_at':
                        version = ast.literal_eval(kwarg.value)
                        break
                if len(decorator.args) == 1:
                    version = ast.literal_eval(decorator.args[0])

                if decorator_name in acceptable_views:
                    api_options = acceptable_views[decorator_name]
                    api_options['version'] = version
                    api_options_list.append(api_options)
            else:
                decorator_name = decorator.func.id
                if decorator_name == 'validate_body':
                    _SimpleNamesResolver(simple_names).visit(decorator.args[0])
                    input_schema = ast.literal_eval(decorator.args[0])
                if decorator_name == 'validate_output':
                    _SimpleNamesResolver(simple_names).visit(decorator.args[0])
                    output_schema = ast.literal_eval(decorator.args[0])
        for api_options in api_options_list:
            schema = ViewSchema(
                    view_name=api_options['name'],
                    version=api_options['version'],
                    input_schema=input_schema,
                    output_schema=output_schema,
                    methods=api_options['methods'],
                    url=api_options['url'],
                    doc=doc,
                )
            schemas_found.append(schema)
    return schemas_found
5394
def source_getattr():
    

    def source_getattr(_value, context, **_params):
        value = getattr(context["model"].source, context["key"])
        return _attr(value)

    return source_getattr
355480
def schemaNewDocParserCtxt(self):
        
        ret = libxml2mod.xmlSchemaNewDocParserCtxt(self._o)
        if ret is None:raise parserError('xmlSchemaNewDocParserCtxt() failed')
        __tmp = SchemaParserCtxt(_obj=ret)
        return __tmp
403506
def _get_schema(self):
		
		d={}
		layout_kwargs=dict((_,'') for _ in get_layout_kwargs())
		for _ in ('data','layout','theme','panels'):
			d[_]={}
			for __ in eval('__QUANT_FIGURE_{0}'.format(_.upper())):
				layout_kwargs.pop(__,None)
				d[_][__]=None
		d['layout'].update(annotations=dict(values=[],
											params=utils.make_dict_from_list(get_annotation_kwargs())))
		d['layout'].update(shapes=utils.make_dict_from_list(get_shapes_kwargs()))
		[layout_kwargs.pop(_,None) for _ in get_annotation_kwargs()+get_shapes_kwargs()]
		d['layout'].update(**layout_kwargs)
		return d
319706
def to_qtree(self, instring, schema):
        
        root_list = self.to_syntax_tree(instring, schema)
        return qtree_translator.translate(root_list)
247390
def source_set(method_name):
    

    def source_set(value, context, **_params):
        method = getattr(context["model"].source, method_name)
        return _set(method, context["key"], value, (), {})

    return source_set
799059
def source_get(method_name):
    

    def source_get(_value, context, **_params):
        method = getattr(context["model"].source, method_name)
        return _get(method, context["key"], (), {})

    return source_get
1163914
def schema(self):
        
        schema = "%s %s %s %s('%s'" % (
            self.name,
            self.data_type,
            self.index_type,
            self.key_type,
            self.index_name,
        )
        if self.includes is not None:
            schema += ", ["
            schema += ", ".join(("'%s'" % i for i in self.includes))
            schema += "]"
        return schema + ")"
182789
def [](key, src = name.to_sym)
      attr =
        if count_index[key].equal?(1)
          name_index[key]
        else
          source_index[src][key]
        end

      unless attr
        raise(KeyError, "#{key.inspect} attribute doesn't exist in #{src} schema")
      end

      attr
    end
780412
def schema(self):
        
        if self.status == "DELETING":
            return ""
        parts = ["GLOBAL", self.index_type, "INDEX"]
        parts.append("('%s', %s," % (self.name, self.hash_key.name))
        if self.range_key:
            parts.append("%s," % self.range_key.name)
        if self.includes:
            parts.append("[%s]," % ", ".join(("'%s'" % i for i in self.includes)))

        parts.append(
            "THROUGHPUT (%d, %d))" % (self.read_throughput, self.write_throughput)
        )
        return " ".join(parts)
452096
def use_schema(schema, list_view=False, locations=None):
    

    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            use_args_wrapper = parser.use_args(schema, locations=locations)
            # Function wrapped with use_args
            func_with_args = use_args_wrapper(func)
            ret = func_with_args(*args, **kwargs)
            # Serialize and jsonify the return value
            return jsonify(schema.dump(ret, many=list_view).data)

        return wrapped

    return decorator
1265425
def source_lookup(request):
    
    source = request.GET['source']
    source_slug = slugify(source.strip())
    source_candidates = Dataset.objects.values('source').filter(
        source_slug__startswith=source_slug
    )
    sources = json.dumps([cand['source'] for cand in source_candidates])

    return HttpResponse(sources, content_type='application/json')
692747
def schema_map(schema):
    """"""
    mapper = {}
    for name in getFieldNames(schema):
        mapper[name] = name
    return mapper
409043
def _schema_getter(self, db):
        """"""
        # Change DB connection if needed
        if self.database != db:
            self.change_db(db)
        schema_dict = {tbl: self.get_schema(tbl) for tbl in self.tables}

        schema_lst = []
        for table, schema in schema_dict.items():
            for col in schema:
                col.insert(0, table)
                schema_lst.append(col)
        return schema_lst
1146898
def to_dict(self):
        

        # 1. extract the schema fields
        data = self.extract_fields()

        # 2. include custom key-value pairs listed in the mapping dictionary
        for key, attr in self.attributes.iteritems():
            if key in self.ignore:
                continue  # skip ignores
            # fetch the mapped attribute
            value = getattr(self.context, attr, None)
            if value is None:
                value = getattr(self, attr, None)
            # handle function calls
            if callable(value):
                value = value()
            # map the value to the given key from the mapping
            data[key] = api.to_json_value(self.context, key, value)
        return data
291702
def schema(self):
        

        if self.headers is None:
            raise exceptions.NoResourceLoadedException(
                'Resource must be loaded to find schema')
        try:
            fields = self.specification.get('fields', {})
            parsed = {
                'primaryKey': 'id',
                'fields': [{
                        'name': header,
                        'type': fields[header]['type'],
                        'description': fields[header]['description']
                        } for header in self.headers]
                }
        except KeyError:
            raise exceptions.NotABudgetDataPackageException(
                'Includes other fields than the Budget Data Package fields')
        return parsed
672471
def _schema_line(args):
  
  # TODO(gram): surely we could just return the schema itself?
  name = args['table'] if args['table'] else args['view']
  if name is None:
    raise Exception('No table or view specified; cannot show schema')

  schema = _get_schema(name)
  if schema:
    html = _repr_html_table_schema(schema)
    return IPython.core.display.HTML(html)
  else:
    raise Exception('%s is not a schema and does not appear to have a schema member' % name)