_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q237400 | EndpointsDispatcherMiddleware._handle_request_error | train | def _handle_request_error(self, orig_request, error, start_response):
"""Handle a request error, converting it to a WSGI response.
Args:
orig_request: An ApiRequest, the original request from the user.
error: A RequestError containing information about the error.
start_response: A function wi... | python | {
"resource": ""
} |
q237401 | _WriteFile | train | def _WriteFile(output_path, name, content):
"""Write given content to a file in a given directory.
Args:
output_path: The directory to store the file in.
name: The name of the file to store the content in.
content: The content to write to the file.close
Returns:
The full path to the written file... | python | {
"resource": ""
} |
q237402 | GenApiConfig | train | def GenApiConfig(service_class_names, config_string_generator=None,
hostname=None, application_path=None, **additional_kwargs):
"""Write an API configuration for endpoints annotated ProtoRPC services.
Args:
service_class_names: A list of fully qualified ProtoRPC service classes.
config_str... | python | {
"resource": ""
} |
q237403 | _GetAppYamlHostname | train | def _GetAppYamlHostname(application_path, open_func=open):
"""Build the hostname for this app based on the name in app.yaml.
Args:
application_path: A string with the path to the AppEngine application. This
should be the directory containing the app.yaml file.
open_func: Function to call to open a f... | python | {
"resource": ""
} |
q237404 | _GenDiscoveryDoc | train | def _GenDiscoveryDoc(service_class_names,
output_path, hostname=None,
application_path=None):
"""Write discovery documents generated from the service classes to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
output_path: The dire... | python | {
"resource": ""
} |
q237405 | _GenOpenApiSpec | train | def _GenOpenApiSpec(service_class_names, output_path, hostname=None,
application_path=None, x_google_api_name=False):
"""Write openapi documents generated from the service classes to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
output_path: The dire... | python | {
"resource": ""
} |
q237406 | _GetClientLib | train | def _GetClientLib(service_class_names, language, output_path, build_system,
hostname=None, application_path=None):
"""Fetch client libraries from a cloud service.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
language: The client library language to generate... | python | {
"resource": ""
} |
q237407 | _GenApiConfigCallback | train | def _GenApiConfigCallback(args, api_func=GenApiConfig):
"""Generate an api file.
Args:
args: An argparse.Namespace object to extract parameters from.
api_func: A function that generates and returns an API configuration
for a list of services.
"""
service_configs = api_func(args.service,
... | python | {
"resource": ""
} |
q237408 | _GetClientLibCallback | train | def _GetClientLibCallback(args, client_func=_GetClientLib):
"""Generate discovery docs and client libraries to files.
Args:
args: An argparse.Namespace object to extract parameters from.
client_func: A function that generates client libraries and stores them to
files, accepting a list of service name... | python | {
"resource": ""
} |
q237409 | _GenDiscoveryDocCallback | train | def _GenDiscoveryDocCallback(args, discovery_func=_GenDiscoveryDoc):
"""Generate discovery docs to files.
Args:
args: An argparse.Namespace object to extract parameters from
discovery_func: A function that generates discovery docs and stores them to
files, accepting a list of service names, a discove... | python | {
"resource": ""
} |
q237410 | _GenClientLibCallback | train | def _GenClientLibCallback(args, client_func=_GenClientLib):
"""Generate a client library to file.
Args:
args: An argparse.Namespace object to extract parameters from
client_func: A function that generates client libraries and stores them to
files, accepting a path to a discovery doc, a client library... | python | {
"resource": ""
} |
q237411 | _EndpointsParser.error | train | def error(self, message):
"""Override superclass to support customized error message.
Error message needs to be rewritten in order to display visible commands
only, when invalid command is called by user. Otherwise, hidden commands
will be displayed in stderr, which is not expected.
Refer the foll... | python | {
"resource": ""
} |
q237412 | _SetupPaths | train | def _SetupPaths():
"""Sets up the sys.path with special directories for endpointscfg.py."""
sdk_path = _FindSdkPath()
if sdk_path:
sys.path.append(sdk_path)
try:
import dev_appserver # pylint: disable=g-import-not-at-top
if hasattr(dev_appserver, 'fix_sys_path'):
dev_appserver.fix_sys... | python | {
"resource": ""
} |
q237413 | _Enum | train | def _Enum(docstring, *names):
"""Utility to generate enum classes used by annotations.
Args:
docstring: Docstring for the generated enum class.
*names: Enum names.
Returns:
A class that contains enum names as attributes.
"""
enums = dict(zip(names, range(len(names))))
reverse = dict((value, ke... | python | {
"resource": ""
} |
q237414 | _CheckType | train | def _CheckType(value, check_type, name, allow_none=True):
"""Check that the type of an object is acceptable.
Args:
value: The object whose type is to be checked.
check_type: The type that the object must be an instance of.
name: Name of the object, to be placed in any error messages.
allow_none: Tr... | python | {
"resource": ""
} |
q237415 | api | train | def api(name, version, description=None, hostname=None, audiences=None,
scopes=None, allowed_client_ids=None, canonical_name=None,
auth=None, owner_domain=None, owner_name=None, package_path=None,
frontend_limits=None, title=None, documentation=None, auth_level=None,
issuers=None, namesp... | python | {
"resource": ""
} |
q237416 | method | train | def method(request_message=message_types.VoidMessage,
response_message=message_types.VoidMessage,
name=None,
path=None,
http_method='POST',
scopes=None,
audiences=None,
allowed_client_ids=None,
auth_level=None,
api_key_re... | python | {
"resource": ""
} |
q237417 | _ApiInfo.is_same_api | train | def is_same_api(self, other):
"""Check if this implements the same API as another _ApiInfo instance."""
if not isinstance(other, _ApiInfo):
return False
# pylint: disable=protected-access
return self.__common_info is other.__common_info | python | {
"resource": ""
} |
q237418 | _ApiDecorator.api_class | train | def api_class(self, resource_name=None, path=None, audiences=None,
scopes=None, allowed_client_ids=None, auth_level=None,
api_key_required=None):
"""Get a decorator for a class that implements an API.
This can be used for single-class or multi-class implementations. It's
us... | python | {
"resource": ""
} |
q237419 | _MethodInfo.__safe_name | train | def __safe_name(self, method_name):
"""Restrict method name to a-zA-Z0-9_, first char lowercase."""
# Endpoints backend restricts what chars are allowed in a method name.
safe_name = re.sub(r'[^\.a-zA-Z0-9_]', '', method_name)
# Strip any number of leading underscores.
safe_name = safe_name.lstrip(... | python | {
"resource": ""
} |
q237420 | _MethodInfo.method_id | train | def method_id(self, api_info):
"""Computed method name."""
# This is done here for now because at __init__ time, the method is known
# but not the api, and thus not the api name. Later, in
# ApiConfigGenerator.__method_descriptor, the api name is known.
if api_info.resource_name:
resource_par... | python | {
"resource": ""
} |
q237421 | ApiConfigGenerator.__field_to_subfields | train | def __field_to_subfields(self, field):
"""Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case, we can't simply descr... | python | {
"resource": ""
} |
q237422 | ApiConfigGenerator.__field_to_parameter_type | train | def __field_to_parameter_type(self, field):
"""Converts the field variant type into a string describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A string corresponding to the variant enum of the field, with a few
exceptions. In the case of signe... | python | {
"resource": ""
} |
q237423 | ApiConfigGenerator.__get_path_parameters | train | def __get_path_parameters(self, path):
"""Parses path paremeters from a URI path and organizes them by parameter.
Some of the parameters may correspond to message fields, and so will be
represented as segments corresponding to each subfield; e.g. first.second if
the field "second" in the message field ... | python | {
"resource": ""
} |
q237424 | ApiConfigGenerator.__validate_simple_subfield | train | def __validate_simple_subfield(self, parameter, field, segment_list,
_segment_index=0):
"""Verifies that a proposed subfield actually exists and is a simple field.
Here, simple means it is not a MessageField (nested).
Args:
parameter: String; the '.' delimited name o... | python | {
"resource": ""
} |
q237425 | ApiConfigGenerator.__validate_path_parameters | train | def __validate_path_parameters(self, field, path_parameters):
"""Verifies that all path parameters correspond to an existing subfield.
Args:
field: An instance of a subclass of messages.Field. Should be the root
level property name in each path parameter in path_parameters. For
exampl... | python | {
"resource": ""
} |
q237426 | ApiConfigGenerator.__parameter_default | train | def __parameter_default(self, final_subfield):
"""Returns default value of final subfield if it has one.
If this subfield comes from a field list returned from __field_to_subfields,
none of the fields in the subfield list can have a default except the final
one since they all must be message fields.
... | python | {
"resource": ""
} |
q237427 | ApiConfigGenerator.__parameter_enum | train | def __parameter_enum(self, final_subfield):
"""Returns enum descriptor of final subfield if it is an enum.
An enum descriptor is a dictionary with keys as the names from the enum and
each value is a dictionary with a single key "backendValue" and value equal
to the same enum name used to stored it in t... | python | {
"resource": ""
} |
q237428 | ApiConfigGenerator.__parameter_descriptor | train | def __parameter_descriptor(self, subfield_list):
"""Creates descriptor for a parameter using the subfields that define it.
Each parameter is defined by a list of fields, with all but the last being
a message field and the final being a simple (non-message) field.
Many of the fields in the descriptor a... | python | {
"resource": ""
} |
q237429 | ApiConfigGenerator.__schema_descriptor | train | def __schema_descriptor(self, services):
"""Descriptor for the all the JSON Schema used.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
Returns:
Dictionary containing all the JSON Schema used in the service.
"""
methods_desc = {}
for... | python | {
"resource": ""
} |
q237430 | ApiConfigGenerator.__auth_descriptor | train | def __auth_descriptor(self, api_info):
"""Builds an auth descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys.
"""
if api_info.auth is None:
return None
auth_descriptor = {}
if api_info.au... | python | {
"resource": ""
} |
q237431 | ApiConfigGenerator.__frontend_limit_descriptor | train | def __frontend_limit_descriptor(self, api_info):
"""Builds a frontend limit descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with frontend limit information.
"""
if api_info.frontend_limits is None:
return None
descriptor = {}
for propn... | python | {
"resource": ""
} |
q237432 | ApiConfigGenerator.__frontend_limit_rules_descriptor | train | def __frontend_limit_rules_descriptor(self, api_info):
"""Builds a frontend limit rules descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A list of dictionaries with frontend limit rules information.
"""
if not api_info.frontend_limits.rules:
return None
... | python | {
"resource": ""
} |
q237433 | ApiConfigGenerator.get_config_dict | train | def get_config_dict(self, services, hostname=None):
"""JSON dict description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set... | python | {
"resource": ""
} |
q237434 | ApiConfigGenerator.pretty_print_config_to_json | train | def pretty_print_config_to_json(self, services, hostname=None):
"""JSON string description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override... | python | {
"resource": ""
} |
q237435 | DiscoveryGenerator.__parameter_enum | train | def __parameter_enum(self, param):
"""Returns enum descriptor of a parameter if it is an enum.
An enum descriptor is a list of keys.
Args:
param: A simple field.
Returns:
The enum descriptor for the field, if it's an enum descriptor, else
returns None.
"""
if isinstance(... | python | {
"resource": ""
} |
q237436 | DiscoveryGenerator.__params_order_descriptor | train | def __params_order_descriptor(self, message_type, path, is_params_class=False):
"""Describe the order of path parameters.
Args:
message_type: messages.Message class, Message with parameters to describe.
path: string, HTTP path to method.
is_params_class: boolean, Whether the message represent... | python | {
"resource": ""
} |
q237437 | DiscoveryGenerator.__schemas_descriptor | train | def __schemas_descriptor(self):
"""Describes the schemas section of the discovery document.
Returns:
Dictionary describing the schemas of the document.
"""
# Filter out any keys that aren't 'properties', 'type', or 'id'
result = {}
for schema_key, schema_value in self.__parser.schemas().i... | python | {
"resource": ""
} |
q237438 | DiscoveryGenerator.__resource_descriptor | train | def __resource_descriptor(self, resource_path, methods):
"""Describes a resource.
Args:
resource_path: string, the path of the resource (e.g., 'entries.items')
methods: list of tuples of type
(endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods
that serve this resourc... | python | {
"resource": ""
} |
q237439 | DiscoveryGenerator.__discovery_doc_descriptor | train | def __discovery_doc_descriptor(self, services, hostname=None):
"""Builds a discovery doc for an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaul... | python | {
"resource": ""
} |
q237440 | DiscoveryGenerator.get_discovery_doc | train | def get_discovery_doc(self, services, hostname=None):
"""JSON dict description of a protorpc.remote.Service in discovery format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the v... | python | {
"resource": ""
} |
q237441 | send_wsgi_response | train | def send_wsgi_response(status, headers, content, start_response,
cors_handler=None):
"""Dump reformatted response to CGI start_response.
This calls start_response and returns the response body.
Args:
status: A string containing the HTTP status code to send.
headers: A list of (hea... | python | {
"resource": ""
} |
q237442 | get_headers_from_environ | train | def get_headers_from_environ(environ):
"""Get a wsgiref.headers.Headers object with headers from the environment.
Headers in environ are prefixed with 'HTTP_', are all uppercase, and have
had dashes replaced with underscores. This strips the HTTP_ prefix and
changes underscores back to dashes before adding th... | python | {
"resource": ""
} |
q237443 | put_headers_in_environ | train | def put_headers_in_environ(headers, environ):
"""Given a list of headers, put them into environ based on PEP-333.
This converts headers to uppercase, prefixes them with 'HTTP_', and
converts dashes to underscores before adding them to the environ dict.
Args:
headers: A list of (header, value) tuples. The... | python | {
"resource": ""
} |
q237444 | get_hostname_prefix | train | def get_hostname_prefix():
"""Returns the hostname prefix of a running Endpoints service.
The prefix is the portion of the hostname that comes before the API name.
For example, if a non-default version and a non-default service are in use,
the returned result would be '{VERSION}-dot-{SERVICE}-'.
Returns:
... | python | {
"resource": ""
} |
q237445 | get_app_hostname | train | def get_app_hostname():
"""Return hostname of a running Endpoints service.
Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT"
if running on development server, or 2) "app_id.appspot.com" if running on
external app engine prod, or "app_id.googleplex.com" if running as Google
first-par... | python | {
"resource": ""
} |
q237446 | check_list_type | train | def check_list_type(objects, allowed_type, name, allow_none=True):
"""Verify that objects in list are of the allowed type or raise TypeError.
Args:
objects: The list of objects to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the list of objects, added to the exception.
... | python | {
"resource": ""
} |
q237447 | snake_case_to_headless_camel_case | train | def snake_case_to_headless_camel_case(snake_string):
"""Convert snake_case to headlessCamelCase.
Args:
snake_string: The string to be converted.
Returns:
The input string converted to headlessCamelCase.
"""
return ''.join([snake_string.split('_')[0]] +
list(sub_string.capitalize()
... | python | {
"resource": ""
} |
q237448 | StartResponseProxy.Proxy | train | def Proxy(self, status, headers, exc_info=None):
"""Save args, defer start_response until response body is parsed.
Create output buffer for body to be written into.
Note: this is not quite WSGI compliant: The body should come back as an
iterator returned from calling service_app() but instead, StartR... | python | {
"resource": ""
} |
q237449 | DiscoveryService._send_success_response | train | def _send_success_response(self, response, start_response):
"""Sends an HTTP 200 json success response.
This calls start_response and returns the response body.
Args:
response: A string containing the response body to return.
start_response: A function with semantics defined in PEP-333.
R... | python | {
"resource": ""
} |
q237450 | DiscoveryService._get_rest_doc | train | def _get_rest_doc(self, request, start_response):
"""Sends back HTTP response with API directory.
This calls start_response and returns the response body. It will return
the discovery doc for the requested api/version.
Args:
request: An ApiRequest, the transformed request sent to the Discovery ... | python | {
"resource": ""
} |
q237451 | DiscoveryService._generate_api_config_with_root | train | def _generate_api_config_with_root(self, request):
"""Generate an API config with a specific root hostname.
This uses the backend object and the ApiConfigGenerator to create an API
config specific to the hostname of the incoming request. This allows for
flexible API configs for non-standard environment... | python | {
"resource": ""
} |
q237452 | DiscoveryService._list | train | def _list(self, request, start_response):
"""Sends HTTP response containing the API directory.
This calls start_response and returns the response body.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.... | python | {
"resource": ""
} |
q237453 | DiscoveryService.handle_discovery_request | train | def handle_discovery_request(self, path, request, start_response):
"""Returns the result of a discovery service request.
This calls start_response and returns the response body.
Args:
path: A string containing the API path (the portion of the path
after /_ah/api/).
request: An ApiReque... | python | {
"resource": ""
} |
q237454 | ApiRequest._process_req_body | train | def _process_req_body(self, body):
"""Process the body of the HTTP request.
If the body is valid JSON, return the JSON as a dict.
Else, convert the key=value format to a dict and return that.
Args:
body: The body of the HTTP request.
"""
try:
return json.loads(body)
except Valu... | python | {
"resource": ""
} |
q237455 | ApiRequest._reconstruct_relative_url | train | def _reconstruct_relative_url(self, environ):
"""Reconstruct the relative URL of this request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
URL from the pieces available in the environment.
Args:
env... | python | {
"resource": ""
} |
q237456 | ApiRequest.reconstruct_hostname | train | def reconstruct_hostname(self, port_override=None):
"""Reconstruct the hostname of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
... | python | {
"resource": ""
} |
q237457 | ApiRequest.reconstruct_full_url | train | def reconstruct_full_url(self, port_override=None):
"""Reconstruct the full URL of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
... | python | {
"resource": ""
} |
q237458 | OpenApiGenerator._construct_operation_id | train | def _construct_operation_id(self, service_name, protorpc_method_name):
"""Return an operation id for a service method.
Args:
service_name: The name of the service.
protorpc_method_name: The ProtoRPC method name.
Returns:
A string representing the operation id.
"""
# camelCase th... | python | {
"resource": ""
} |
q237459 | OpenApiGenerator.__definitions_descriptor | train | def __definitions_descriptor(self):
"""Describes the definitions section of the OpenAPI spec.
Returns:
Dictionary describing the definitions of the spec.
"""
# Filter out any keys that aren't 'properties' or 'type'
result = {}
for def_key, def_value in self.__parser.schemas().iteritems():... | python | {
"resource": ""
} |
q237460 | OpenApiGenerator.__response_message_descriptor | train | def __response_message_descriptor(self, message_type, method_id):
"""Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response.
"""
... | python | {
"resource": ""
} |
q237461 | OpenApiGenerator.__x_google_quota_descriptor | train | def __x_google_quota_descriptor(self, metric_costs):
"""Describes the metric costs for a call.
Args:
metric_costs: Dict of metric definitions to the integer cost value against
that metric.
Returns:
A dict descriptor describing the Quota limits for the endpoint.
"""
return {
... | python | {
"resource": ""
} |
q237462 | OpenApiGenerator.__x_google_quota_definitions_descriptor | train | def __x_google_quota_definitions_descriptor(self, limit_definitions):
"""Describes the quota limit definitions for an API.
Args:
limit_definitions: List of endpoints.LimitDefinition tuples
Returns:
A dict descriptor of the API's quota limit definitions.
"""
if not limit_definitions:
... | python | {
"resource": ""
} |
q237463 | OpenApiGenerator.__security_definitions_descriptor | train | def __security_definitions_descriptor(self, issuers):
"""Create a descriptor for the security definitions.
Args:
issuers: dict, mapping issuer names to Issuer tuples
Returns:
The dict representing the security definitions descriptor.
"""
if not issuers:
result = {
_DEFA... | python | {
"resource": ""
} |
q237464 | OpenApiGenerator.__api_openapi_descriptor | train | def __api_openapi_descriptor(self, services, hostname=None, x_google_api_name=False):
"""Builds an OpenAPI description of an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
... | python | {
"resource": ""
} |
q237465 | OpenApiGenerator.get_openapi_dict | train | def get_openapi_dict(self, services, hostname=None, x_google_api_name=False):
"""JSON dict description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the ... | python | {
"resource": ""
} |
q237466 | OpenApiGenerator.pretty_print_config_to_json | train | def pretty_print_config_to_json(self, services, hostname=None, x_google_api_name=False):
"""JSON string description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hos... | python | {
"resource": ""
} |
q237467 | EndpointsProtoJson.__pad_value | train | def __pad_value(value, pad_len_multiple, pad_char):
"""Add padding characters to the value if needed.
Args:
value: The string value to be padded.
pad_len_multiple: Pad the result so its length is a multiple
of pad_len_multiple.
pad_char: The character to use for padding.
Return... | python | {
"resource": ""
} |
q237468 | MessageTypeToJsonSchema.add_message | train | def add_message(self, message_type):
"""Add a new message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError if the Schema id for this message_type would collide with the
Schema id of a different message_type... | python | {
"resource": ""
} |
q237469 | MessageTypeToJsonSchema.ref_for_message_type | train | def ref_for_message_type(self, message_type):
"""Returns the JSON Schema id for the given message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError: if the message hasn't been parsed via add_message().
"""
... | python | {
"resource": ""
} |
q237470 | MessageTypeToJsonSchema.__normalized_name | train | def __normalized_name(self, message_type):
"""Normalized schema name.
Generate a normalized schema name, taking the class name and stripping out
everything but alphanumerics, and camel casing the remaining words.
A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*
Args:
mess... | python | {
"resource": ""
} |
q237471 | MessageTypeToJsonSchema.__message_to_schema | train | def __message_to_schema(self, message_type):
"""Parse a single message into JSON Schema.
Will recursively descend the message structure
and also parse other messages references via MessageFields.
Args:
message_type: protorpc.messages.Message class to parse.
Returns:
An object represen... | python | {
"resource": ""
} |
q237472 | _check_enum | train | def _check_enum(parameter_name, value, parameter_config):
"""Checks if an enum value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This verifies that the value of an enum parameter is valid.
Args:
parameter_name: A string containing the name of the... | python | {
"resource": ""
} |
q237473 | _check_boolean | train | def _check_boolean(parameter_name, value, parameter_config):
"""Checks if a boolean value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This checks that the string value passed in can be converted to a valid
boolean value.
Args:
parameter_name: A... | python | {
"resource": ""
} |
q237474 | _get_parameter_conversion_entry | train | def _get_parameter_conversion_entry(parameter_config):
"""Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Re... | python | {
"resource": ""
} |
q237475 | transform_parameter_value | train | def transform_parameter_value(parameter_name, value, parameter_config):
"""Validates and transforms parameters to the type expected by the API.
If the value is a list this will recursively call _transform_parameter_value
on the values in the list. Otherwise, it checks all parameter rules for the
the current va... | python | {
"resource": ""
} |
q237476 | NavigationWidgetMixin.filter_items | train | def filter_items(self, items):
'''perform filtering items by specific criteria'''
items = self._filter_active(items)
items = self._filter_in_nav(items)
return items | python | {
"resource": ""
} |
q237477 | is_leonardo_module | train | def is_leonardo_module(mod):
"""returns True if is leonardo module
"""
if hasattr(mod, 'default') \
or hasattr(mod, 'leonardo_module_conf'):
return True
for key in dir(mod):
if 'LEONARDO' in key:
return True
return False | python | {
"resource": ""
} |
q237478 | _translate_page_into | train | def _translate_page_into(page, language, default=None):
"""
Return the translation for a given page
"""
# Optimisation shortcut: No need to dive into translations if page already what we want
if page.language == language:
return page
translations = dict((t.language, t) for t in page.ava... | python | {
"resource": ""
} |
q237479 | feincms_breadcrumbs | train | def feincms_breadcrumbs(page, include_self=True):
"""
Generate a list of the page's ancestors suitable for use as breadcrumb navigation.
By default, generates an unordered list with the id "breadcrumbs" -
override breadcrumbs.html to change this.
::
{% feincms_breadcrumbs feincms_page %}
... | python | {
"resource": ""
} |
q237480 | is_parent_of | train | def is_parent_of(page1, page2):
"""
Determines whether a given page is the parent of another page
Example::
{% if page|is_parent_of:feincms_page %} ... {% endif %}
"""
try:
return page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght
except Attri... | python | {
"resource": ""
} |
q237481 | PageCreateView.parent | train | def parent(self):
'''We use parent for some initial data'''
if not hasattr(self, '_parent'):
if 'parent' in self.kwargs:
try:
self._parent = Page.objects.get(id=self.kwargs["parent"])
except Exception as e:
raise e
... | python | {
"resource": ""
} |
q237482 | Page.tree_label | train | def tree_label(self):
'''render tree label like as `root > child > child`'''
titles = []
page = self
while page:
titles.append(page.title)
page = page.parent
return smart_text(' > '.join(reversed(titles))) | python | {
"resource": ""
} |
q237483 | Page.flush_ct_inventory | train | def flush_ct_inventory(self):
"""internal method used only if ct_inventory is enabled
"""
if hasattr(self, '_ct_inventory'):
# skip self from update
self._ct_inventory = None
self.update_view = False
self.save() | python | {
"resource": ""
} |
q237484 | Page.register_default_processors | train | def register_default_processors(cls, frontend_editing=None):
"""
Register our default request processors for the out-of-the-box
Page experience.
Since FeinCMS 1.11 was removed from core.
"""
super(Page, cls).register_default_processors()
if frontend_editing:
... | python | {
"resource": ""
} |
q237485 | Page.run_request_processors | train | def run_request_processors(self, request):
"""
Before rendering a page, run all registered request processors. A
request processor may peruse and modify the page or the request. It can
also return a ``HttpResponse`` for shortcutting the rendering and
returning that response immed... | python | {
"resource": ""
} |
q237486 | Page.as_text | train | def as_text(self):
'''Fetch and render all regions
For search and test purposes
just a prototype
'''
from leonardo.templatetags.leonardo_tags import _render_content
request = get_anonymous_request(self)
content = ''
try:
for region in [re... | python | {
"resource": ""
} |
q237487 | technical_404_response | train | def technical_404_response(request, exception):
"Create a technical 404 error response. The exception should be the Http404."
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried =... | python | {
"resource": ""
} |
q237488 | ListMixin.items | train | def items(self):
'''access for filtered items'''
if hasattr(self, '_items'):
return self.filter_items(self._items)
self._items = self.get_items()
return self.filter_items(self._items) | python | {
"resource": ""
} |
q237489 | ListMixin.populate_items | train | def populate_items(self, request):
'''populate and returns filtered items'''
self._items = self.get_items(request)
return self.items | python | {
"resource": ""
} |
q237490 | ListMixin.columns_classes | train | def columns_classes(self):
'''returns columns count'''
md = 12 / self.objects_per_row
sm = None
if self.objects_per_row > 2:
sm = 12 / (self.objects_per_row / 2)
return md, (sm or md), 12 | python | {
"resource": ""
} |
q237491 | ListMixin.get_pages | train | def get_pages(self):
'''returns pages with rows'''
pages = []
page = []
for i, item in enumerate(self.get_rows):
if i > 0 and i % self.objects_per_page == 0:
pages.append(page)
page = []
page.append(item)
pages.append(page)
... | python | {
"resource": ""
} |
q237492 | ListMixin.needs_pagination | train | def needs_pagination(self):
"""Calculate needs pagination"""
if self.objects_per_page == 0:
return False
if len(self.items) > self.objects_per_page \
or len(self.get_pages[0]) > self.objects_per_page:
return True
return False | python | {
"resource": ""
} |
q237493 | ListMixin.get_item_template | train | def get_item_template(self):
'''returns template for signle object from queryset
If you have a template name my_list_template.html
then template for a single object will be
_my_list_template.html
Now only for default generates _item.html
_item.html is obsolete use _defau... | python | {
"resource": ""
} |
q237494 | ContentProxyWidgetMixin.is_obsolete | train | def is_obsolete(self):
"""returns True is data is obsolete and needs revalidation
"""
if self.cache_updated:
now = timezone.now()
delta = now - self.cache_updated
if delta.seconds < self.cache_validity:
return False
return True | python | {
"resource": ""
} |
q237495 | ContentProxyWidgetMixin.update_cache | train | def update_cache(self, data=None):
"""call with new data or set data to self.cache_data and call this
"""
if data:
self.cache_data = data
self.cache_updated = timezone.now()
self.save() | python | {
"resource": ""
} |
q237496 | ContentProxyWidgetMixin.data | train | def data(self):
"""this property just calls ``get_data``
but here you can serilalize your data or render as html
these data will be saved to self.cached_content
also will be accessable from template
"""
if self.is_obsolete():
self.update_cache(self.get_data())... | python | {
"resource": ""
} |
q237497 | JSONContentMixin.data | train | def data(self):
"""load and cache data in json format
"""
if self.is_obsolete():
data = self.get_data()
for datum in data:
if 'published_parsed' in datum:
datum['published_parsed'] = \
self.parse_time(datum['pub... | python | {
"resource": ""
} |
q237498 | get_loaded_modules | train | def get_loaded_modules(modules):
'''load modules and order it by ordering key'''
_modules = []
for mod in modules:
mod_cfg = get_conf_from_module(mod)
_modules.append((mod, mod_cfg,))
_modules = sorted(_modules, key=lambda m: m[1].get('ordering'))
return _modules | python | {
"resource": ""
} |
q237499 | _is_leonardo_module | train | def _is_leonardo_module(whatever):
'''check if is leonardo module'''
# check if is python module
if hasattr(whatever, 'default') \
or hasattr(whatever, 'leonardo_module_conf'):
return True
# check if is python object
for key in dir(whatever):
if 'LEONARDO' in key:
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.