_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q237300 | SWFStream.readACTIONRECORD | train | def readACTIONRECORD(self):
""" Read a SWFActionRecord """
action = None
actionCode = self.readUI8()
if actionCode != 0:
actionLength = self.readUI16() if actionCode >= 0x80 else 0
#print "0x%x"%actionCode, actionLength
action = SWFActionFactory.create... | python | {
"resource": ""
} |
q237301 | SWFStream.readCLIPACTIONRECORD | train | def readCLIPACTIONRECORD(self, version):
""" Read a SWFClipActionRecord """
pos = self.tell()
flags = self.readUI32() if version >= 6 else self.readUI16()
if flags == 0:
return None
else:
self.seek(pos)
return SWFClipActionRecord(self, version) | python | {
"resource": ""
} |
q237302 | SWFStream.readRGB | train | def readRGB(self):
""" Read a RGB color """
self.reset_bits_pending();
r = self.readUI8()
g = self.readUI8()
b = self.readUI8()
return (0xff << 24) | (r << 16) | (g << 8) | b | python | {
"resource": ""
} |
q237303 | SWFStream.readRGBA | train | def readRGBA(self):
""" Read a RGBA color """
self.reset_bits_pending();
r = self.readUI8()
g = self.readUI8()
b = self.readUI8()
a = self.readUI8()
return (a << 24) | (r << 16) | (g << 8) | b | python | {
"resource": ""
} |
q237304 | SWFStream.readString | train | def readString(self):
""" Read a string """
s = self.f.read(1)
string = b""
while ord(s) > 0:
string += s
s = self.f.read(1)
return string.decode() | python | {
"resource": ""
} |
q237305 | SWFStream.readFILTER | train | def readFILTER(self):
""" Read a SWFFilter """
filterId = self.readUI8()
filter = SWFFilterFactory.create(filterId)
filter.parse(self)
return filter | python | {
"resource": ""
} |
q237306 | SWFStream.readFILTERLIST | train | def readFILTERLIST(self):
""" Read a length-prefixed list of FILTERs """
number = self.readUI8()
return [self.readFILTER() for _ in range(number)] | python | {
"resource": ""
} |
q237307 | SWFStream.readBUTTONCONDACTIONSs | train | def readBUTTONCONDACTIONSs(self):
""" Read zero or more button-condition actions """
out = []
while 1:
action = self.readBUTTONCONDACTION()
if action:
out.append(action)
else:
break
return out | python | {
"resource": ""
} |
q237308 | SWFStream.readtag_header | train | def readtag_header(self):
""" Read a tag header """
pos = self.tell()
tag_type_and_length = self.readUI16()
tag_length = tag_type_and_length & 0x003f
if tag_length == 0x3f:
# The SWF10 spec sez that this is a signed int.
# Shouldn't it be an unsigned int?
... | python | {
"resource": ""
} |
q237309 | SWFTimelineContainer.get_dependencies | train | def get_dependencies(self):
""" Returns the character ids this tag refers to """
s = super(SWFTimelineContainer, self).get_dependencies()
for dt in self.all_tags_of_type(DefinitionTag):
s.update(dt.get_dependencies())
return s | python | {
"resource": ""
} |
q237310 | SWFTimelineContainer.all_tags_of_type | train | def all_tags_of_type(self, type_or_types, recurse_into_sprites = True):
"""
Generator for all tags of the given type_or_types.
Generates in breadth-first order, optionally including all sub-containers.
"""
for t in self.tags:
if isinstance(t, type_or_types):
... | python | {
"resource": ""
} |
q237311 | SWFTimelineContainer.build_dictionary | train | def build_dictionary(self):
"""
Return a dictionary of characterIds to their defining tags.
"""
d = {}
for t in self.all_tags_of_type(DefinitionTag, recurse_into_sprites = False):
if t.characterId in d:
#print 'redefinition of characterId %d:' % (t.cha... | python | {
"resource": ""
} |
q237312 | SWFTimelineContainer.collect_sound_streams | train | def collect_sound_streams(self):
"""
Return a list of sound streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are th... | python | {
"resource": ""
} |
q237313 | SWFTimelineContainer.collect_video_streams | train | def collect_video_streams(self):
"""
Return a list of video streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are th... | python | {
"resource": ""
} |
q237314 | SVGExporter.export | train | def export(self, swf, force_stroke=False):
""" Exports the specified SWF to SVG.
@param swf The SWF.
@param force_stroke Whether to force strokes on non-stroked fills.
"""
self.svg = self._e.svg(version=SVG_VERSION)
self.force_stroke = force_stroke
self.defs = s... | python | {
"resource": ""
} |
q237315 | SingleShapeSVGExporterMixin.export | train | def export(self, swf, shape, **export_opts):
""" Exports the specified shape of the SWF to SVG.
@param swf The SWF.
@param shape Which shape to export, either by characterId(int) or as a Tag object.
"""
# If `shape` is given as int, find corresponding shape tag.
if is... | python | {
"resource": ""
} |
q237316 | FrameSVGExporterMixin.export | train | def export(self, swf, frame, **export_opts):
""" Exports a frame of the specified SWF to SVG.
@param swf The SWF.
@param frame Which frame to export, by 0-based index (int)
"""
self.wanted_frame = frame
return super(FrameSVGExporterMixin, self).export(swf, *export_opts... | python | {
"resource": ""
} |
q237317 | _get_args_and_errors | train | def _get_args_and_errors(self, minuit=None, args=None, errors=None):
"""
consistent algorithm to get argument and errors
1) get it from minuit if minuit is available
2) if not get it from args and errors
2.1) if args is dict parse it.
3) if all else fail get it from self.last_arg
"""
ret... | python | {
"resource": ""
} |
q237318 | draw_residual | train | def draw_residual(x, y, yerr, xerr,
show_errbars=True, ax=None,
zero_line=True, grid=True,
**kwargs):
"""Draw a residual plot on the axis.
By default, if show_errbars if True, residuals are drawn as blue points
with errorbars with no endcaps. If show_er... | python | {
"resource": ""
} |
q237319 | draw_pdf | train | def draw_pdf(f, arg, bound, bins=100, scale=1.0, density=True,
normed_pdf=False, ax=None, **kwds):
"""
draw pdf with given argument and bounds.
**Arguments**
* **f** your pdf. The first argument is assumed to be independent
variable
* **arg** argument can be tuple o... | python | {
"resource": ""
} |
q237320 | get_chunks | train | def get_chunks(sequence, chunk_size):
"""Split sequence into chunks.
:param list sequence:
:param int chunk_size:
"""
return [
sequence[idx:idx + chunk_size]
for idx in range(0, len(sequence), chunk_size)
] | python | {
"resource": ""
} |
q237321 | get_kwargs | train | def get_kwargs(kwargs):
"""Get all keys and values from dictionary where key is not `self`.
:param dict kwargs: Input parameters
"""
return {
key: value for key, value in six.iteritems(kwargs)
if key != 'self'
} | python | {
"resource": ""
} |
q237322 | check_status_code | train | def check_status_code(response, codes=None):
"""Check HTTP status code and raise exception if incorrect.
:param Response response: HTTP response
:param codes: List of accepted codes or callable
:raises: ApiError if code invalid
"""
codes = codes or [httplib.OK]
checker = (
codes
... | python | {
"resource": ""
} |
q237323 | result_or_error | train | def result_or_error(response):
"""Get `result` field from Betfair response or raise exception if not
found.
:param Response response:
:raises: ApiError if no results passed
"""
data = response.json()
result = data.get('result')
if result is not None:
return result
raise exce... | python | {
"resource": ""
} |
q237324 | make_payload | train | def make_payload(base, method, params):
"""Build Betfair JSON-RPC payload.
:param str base: Betfair base ("Sports" or "Account")
:param str method: Betfair endpoint
:param dict params: Request parameters
"""
payload = {
'jsonrpc': '2.0',
'method': '{base}APING/v1.0/{method}'.for... | python | {
"resource": ""
} |
q237325 | requires_login | train | def requires_login(func, *args, **kwargs):
"""Decorator to check that the user is logged in. Raises `BetfairError`
if instance variable `session_token` is absent.
"""
self = args[0]
if self.session_token:
return func(*args, **kwargs)
raise exceptions.NotLoggedIn() | python | {
"resource": ""
} |
q237326 | nearest_price | train | def nearest_price(price, cutoffs=CUTOFFS):
"""Returns the nearest Betfair odds value to price.
Adapted from Anton Zemlyanov's AlgoTrader project (MIT licensed).
https://github.com/AlgoTrader/betfair-sports-api/blob/master/lib/betfair_price.js
:param float price: Approximate Betfair price (i.e. decimal... | python | {
"resource": ""
} |
q237327 | Betfair.login | train | def login(self, username, password):
"""Log in to Betfair. Sets `session_token` if successful.
:param str username: Username
:param str password: Password
:raises: BetfairLoginError
"""
response = self.session.post(
os.path.join(self.identity_url, 'certlogin'... | python | {
"resource": ""
} |
q237328 | Betfair.list_market_profit_and_loss | train | def list_market_profit_and_loss(
self, market_ids, include_settled_bets=False,
include_bsp_bets=None, net_of_commission=None):
"""Retrieve profit and loss for a given list of markets.
:param list market_ids: List of markets to calculate profit and loss
:param bool includ... | python | {
"resource": ""
} |
q237329 | Betfair.iter_list_market_book | train | def iter_list_market_book(self, market_ids, chunk_size, **kwargs):
"""Split call to `list_market_book` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_book`
... | python | {
"resource": ""
} |
q237330 | Betfair.iter_list_market_profit_and_loss | train | def iter_list_market_profit_and_loss(
self, market_ids, chunk_size, **kwargs):
"""Split call to `list_market_profit_and_loss` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments p... | python | {
"resource": ""
} |
q237331 | Betfair.place_orders | train | def place_orders(self, market_id, instructions, customer_ref=None):
"""Place new orders into market. This operation is atomic in that all
orders will be placed or none will be placed.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of ... | python | {
"resource": ""
} |
q237332 | Betfair.update_orders | train | def update_orders(self, market_id, instructions, customer_ref=None):
"""Update non-exposure changing fields.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of `UpdateInstruction` objects
:param str customer_ref: Optional order identif... | python | {
"resource": ""
} |
q237333 | Betfair.transfer_funds | train | def transfer_funds(self, from_, to, amount):
"""Transfer funds between the UK Exchange and Australian Exchange wallets.
:param Wallet from_: Source wallet
:param Wallet to: Destination wallet
:param float amount: Amount to transfer
"""
return self.make_api_request(
... | python | {
"resource": ""
} |
q237334 | Parser.parse | train | def parse(self, text, html=True):
'''Parse the text and return a ParseResult instance.'''
self._urls = []
self._users = []
self._lists = []
self._tags = []
reply = REPLY_REGEX.match(text)
reply = reply.groups(0)[0] if reply is not None else None
parsed_h... | python | {
"resource": ""
} |
q237335 | Parser._text | train | def _text(self, text):
'''Parse a Tweet without generating HTML.'''
URL_REGEX.sub(self._parse_urls, text)
USERNAME_REGEX.sub(self._parse_users, text)
LIST_REGEX.sub(self._parse_lists, text)
HASHTAG_REGEX.sub(self._parse_tags, text)
return None | python | {
"resource": ""
} |
q237336 | Parser._html | train | def _html(self, text):
'''Parse a Tweet and generate HTML.'''
html = URL_REGEX.sub(self._parse_urls, text)
html = USERNAME_REGEX.sub(self._parse_users, html)
html = LIST_REGEX.sub(self._parse_lists, html)
return HASHTAG_REGEX.sub(self._parse_tags, html) | python | {
"resource": ""
} |
q237337 | Parser._parse_urls | train | def _parse_urls(self, match):
'''Parse URLs.'''
mat = match.group(0)
# Fix a bug in the regex concerning www...com and www.-foo.com domains
# TODO fix this in the regex instead of working around it here
domain = match.group(5)
if domain[0] in '.-':
return ma... | python | {
"resource": ""
} |
q237338 | Parser._parse_users | train | def _parse_users(self, match):
'''Parse usernames.'''
# Don't parse lists here
if match.group(2) is not None:
return match.group(0)
mat = match.group(0)
if self._include_spans:
self._users.append((mat[1:], match.span(0)))
else:
self._... | python | {
"resource": ""
} |
q237339 | Parser._parse_lists | train | def _parse_lists(self, match):
'''Parse lists.'''
# Don't parse usernames here
if match.group(4) is None:
return match.group(0)
pre, at_char, user, list_name = match.groups()
list_name = list_name[1:]
if self._include_spans:
self._lists.append((u... | python | {
"resource": ""
} |
q237340 | Parser._parse_tags | train | def _parse_tags(self, match):
'''Parse hashtags.'''
mat = match.group(0)
# Fix problems with the regex capturing stuff infront of the #
tag = None
for i in '#\uff03':
pos = mat.rfind(i)
if pos != -1:
tag = i
break
... | python | {
"resource": ""
} |
q237341 | Parser._shorten_url | train | def _shorten_url(self, text):
'''Shorten a URL and make sure to not cut of html entities.'''
if len(text) > self._max_url_length and self._max_url_length != -1:
text = text[0:self._max_url_length - 3]
amp = text.rfind('&')
close = text.rfind(';')
if amp !... | python | {
"resource": ""
} |
q237342 | Parser.format_list | train | def format_list(self, at_char, user, list_name):
'''Return formatted HTML for a list.'''
return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' \
% (user, list_name, at_char, user, list_name) | python | {
"resource": ""
} |
q237343 | follow_shortlinks | train | def follow_shortlinks(shortlinks):
"""Follow redirects in list of shortlinks, return dict of resulting URLs"""
links_followed = {}
for shortlink in shortlinks:
url = shortlink
request_result = requests.get(url)
redirect_history = request_result.history
# history might look li... | python | {
"resource": ""
} |
q237344 | _GetFieldAttributes | train | def _GetFieldAttributes(field):
"""Decomposes field into the needed arguments to pass to the constructor.
This can be used to create copies of the field or to compare if two fields
are "equal" (since __eq__ is not implemented on messages.Field).
Args:
field: A ProtoRPC message field (potentially to be cop... | python | {
"resource": ""
} |
q237345 | _CompareFields | train | def _CompareFields(field, other_field):
"""Checks if two ProtoRPC fields are "equal".
Compares the arguments, rather than the id of the elements (which is
the default __eq__ behavior) as well as the class of the fields.
Args:
field: A ProtoRPC message field to be compared.
other_field: A ProtoRPC mess... | python | {
"resource": ""
} |
q237346 | ResourceContainer.combined_message_class | train | def combined_message_class(self):
"""A ProtoRPC message class with both request and parameters fields.
Caches the result in a local private variable. Uses _CopyField to create
copies of the fields from the existing request and parameters classes since
those fields are "owned" by the message classes.
... | python | {
"resource": ""
} |
q237347 | ResourceContainer.add_to_cache | train | def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name
"""Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
... | python | {
"resource": ""
} |
q237348 | ResourceContainer.get_request_message | train | def get_request_message(cls, remote_info): # pylint: disable=g-bad-name
"""Gets request message or container from remote info.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
Returns:
Either an instance of the request type from the remote ... | python | {
"resource": ""
} |
q237349 | _is_auth_info_available | train | def _is_auth_info_available():
"""Check if user auth info has been set in environment variables."""
return (_ENDPOINTS_USER_INFO in os.environ or
(_ENV_AUTH_EMAIL in os.environ and _ENV_AUTH_DOMAIN in os.environ) or
_ENV_USE_OAUTH_SCOPE in os.environ) | python | {
"resource": ""
} |
q237350 | _get_token | train | def _get_token(
request=None, allowed_auth_schemes=('OAuth', 'Bearer'),
allowed_query_keys=('bearer_token', 'access_token')):
"""Get the auth token for this request.
Auth token may be specified in either the Authorization header or
as a query param (either access_token or bearer_token). We'll check in
... | python | {
"resource": ""
} |
q237351 | _get_id_token_user | train | def _get_id_token_user(token, issuers, audiences, allowed_client_ids, time_now, cache):
"""Get a User for the given id token, if the token is valid.
Args:
token: The id_token to check.
issuers: dict of Issuers
audiences: List of audiences that are acceptable.
allowed_client_ids: List of client IDs ... | python | {
"resource": ""
} |
q237352 | _process_scopes | train | def _process_scopes(scopes):
"""Parse a scopes list into a set of all scopes and a set of sufficient scope sets.
scopes: A list of strings, each of which is a space-separated list of scopes.
Examples: ['scope1']
['scope1', 'scope2']
['scope1', 'scope2 scope3']
Retu... | python | {
"resource": ""
} |
q237353 | _are_scopes_sufficient | train | def _are_scopes_sufficient(authorized_scopes, sufficient_scopes):
"""Check if a list of authorized scopes satisfies any set of sufficient scopes.
Args:
authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes
sufficient_scopes: a set of sets of strings, return value from... | python | {
"resource": ""
} |
q237354 | _set_bearer_user_vars | train | def _set_bearer_user_vars(allowed_client_ids, scopes):
"""Validate the oauth bearer token and set endpoints auth user variables.
If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE. This
provides enough information that our endpoints.get_current_user() function
can get the user.
Args:
all... | python | {
"resource": ""
} |
q237355 | _set_bearer_user_vars_local | train | def _set_bearer_user_vars_local(token, allowed_client_ids, scopes):
"""Validate the oauth bearer token on the dev server.
Since the functions in the oauth module return only example results in local
development, this hits the tokeninfo endpoint and attempts to validate the
token. If it's valid, we'll set _ENV... | python | {
"resource": ""
} |
q237356 | _verify_parsed_token | train | def _verify_parsed_token(parsed_token, issuers, audiences, allowed_client_ids, is_legacy_google_auth=True):
"""Verify a parsed user ID token.
Args:
parsed_token: The parsed token information.
issuers: A list of allowed issuers
audiences: The allowed audiences.
allowed_client_ids: The allowed client... | python | {
"resource": ""
} |
q237357 | _get_cert_expiration_time | train | def _get_cert_expiration_time(headers):
"""Get the expiration time for a cert, given the response headers.
Get expiration time from the headers in the result. If we can't get
a time from the headers, this returns 0, indicating that the cert
shouldn't be cached.
Args:
headers: A dict containing the resp... | python | {
"resource": ""
} |
q237358 | _get_cached_certs | train | def _get_cached_certs(cert_uri, cache):
"""Get certs from cache if present; otherwise, gets from URI and caches them.
Args:
cert_uri: URI from which to retrieve certs if cache is stale or empty.
cache: Cache of pre-fetched certs.
Returns:
The retrieved certs.
"""
certs = cache.get(cert_uri, name... | python | {
"resource": ""
} |
q237359 | _verify_signed_jwt_with_certs | train | def _verify_signed_jwt_with_certs(
jwt, time_now, cache,
cert_uri=_DEFAULT_CERT_URI):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
The PyCrypto library included with Google App Engine is severely limited and
so you have to use it very carefull... | python | {
"resource": ""
} |
q237360 | get_verified_jwt | train | def get_verified_jwt(
providers, audiences,
check_authorization_header=True, check_query_arg=True,
request=None, cache=memcache):
"""
This function will extract, verify, and parse a JWT token from the
Authorization header or access_token query argument.
The JWT is assumed to contain an issuer and a... | python | {
"resource": ""
} |
q237361 | DirectoryListGenerator.__item_descriptor | train | def __item_descriptor(self, config):
"""Builds an item descriptor for a service configuration.
Args:
config: A dictionary containing the service configuration to describe.
Returns:
A dictionary that describes the service configuration.
"""
descriptor = {
'kind': 'discovery#dire... | python | {
"resource": ""
} |
q237362 | DirectoryListGenerator.__directory_list_descriptor | train | def __directory_list_descriptor(self, configs):
"""Builds a directory list for an API.
Args:
configs: List of dicts containing the service configurations to list.
Returns:
A dictionary that can be deserialized into JSON in discovery list format.
Raises:
ApiConfigurationError: If the... | python | {
"resource": ""
} |
q237363 | DirectoryListGenerator.get_directory_list_doc | train | def get_directory_list_doc(self, configs):
"""JSON dict description of a protorpc.remote.Service in list format.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
dict, The directory list document as a JSON dict.
"""
... | python | {
"resource": ""
} |
q237364 | DirectoryListGenerator.pretty_print_config_to_json | train | def pretty_print_config_to_json(self, configs):
"""JSON string description of a protorpc.remote.Service in a discovery doc.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
string, The directory list document as a JSON strin... | python | {
"resource": ""
} |
q237365 | RequestError.__format_error | train | def __format_error(self, error_list_tag):
"""Format this error into a JSON response.
Args:
error_list_tag: A string specifying the name of the tag to use for the
error list.
Returns:
A dict containing the reformatted JSON error response.
"""
error = {'domain': self.domain(),
... | python | {
"resource": ""
} |
q237366 | RequestError.rest_error | train | def rest_error(self):
"""Format this error into a response to a REST request.
Returns:
A string containing the reformatted error response.
"""
error_json = self.__format_error('errors')
return json.dumps(error_json, indent=1, sort_keys=True) | python | {
"resource": ""
} |
q237367 | BackendError._get_status_code | train | def _get_status_code(self, http_status):
"""Get the HTTP status code from an HTTP status string.
Args:
http_status: A string containing a HTTP status code and reason.
Returns:
An integer with the status code number from http_status.
"""
try:
return int(http_status.split(' ', 1)[0... | python | {
"resource": ""
} |
q237368 | ApiConfigManager.process_api_config_response | train | def process_api_config_response(self, config_json):
"""Parses a JSON API config and registers methods for dispatch.
Side effects:
Parses method name, etc. for all methods and updates the indexing
data structures with the information.
Args:
config_json: A dict, the JSON body of the getApi... | python | {
"resource": ""
} |
q237369 | ApiConfigManager._get_sorted_methods | train | def _get_sorted_methods(self, methods):
"""Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server.
"""... | python | {
"resource": ""
} |
q237370 | ApiConfigManager._get_path_params | train | def _get_path_params(match):
"""Gets path parameters from a regular expression match.
Args:
match: A regular expression Match object for a path.
Returns:
A dictionary containing the variable names converted from base64.
"""
result = {}
for var_name, value in match.groupdict().iteri... | python | {
"resource": ""
} |
q237371 | ApiConfigManager.lookup_rest_method | train | def lookup_rest_method(self, path, request_uri, http_method):
"""Look up the rest method at call time.
The method is looked up in self._rest_methods, the list it is saved
in for SaveRestMethod.
Args:
path: A string containing the path from the URL of the request.
http_method: A string cont... | python | {
"resource": ""
} |
q237372 | ApiConfigManager._add_discovery_config | train | def _add_discovery_config(self):
"""Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held.
"""
lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'],
discovery_service.Discov... | python | {
"resource": ""
} |
q237373 | ApiConfigManager.save_config | train | def save_config(self, lookup_key, config):
"""Save a configuration to the cache of configs.
Args:
lookup_key: A string containing the cache lookup key.
config: The dict containing the configuration to save to the cache.
"""
with self._config_lock:
self._configs[lookup_key] = config | python | {
"resource": ""
} |
q237374 | ApiConfigManager._from_safe_path_param_name | train | def _from_safe_path_param_name(safe_parameter):
"""Takes a safe regex group name and converts it back to the original value.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
The safe_parameter is a base32 representatio... | python | {
"resource": ""
} |
q237375 | ApiConfigManager._compile_path_pattern | train | def _compile_path_pattern(pattern):
r"""Generates a compiled regex pattern for a path pattern.
e.g. '/MyApi/v1/notes/{id}'
returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)')
Args:
pattern: A string, the parameterized path pattern to be checked.
Returns:
A compiled regex obje... | python | {
"resource": ""
} |
q237376 | ApiConfigManager._save_rest_method | train | def _save_rest_method(self, method_name, api_name, version, method):
"""Store Rest api methods in a list for lookup at call time.
The list is self._rest_methods, a list of tuples:
[(<compiled_path>, <path_pattern>, <method_dict>), ...]
where:
<compiled_path> is a compiled regex to match against... | python | {
"resource": ""
} |
q237377 | api_server | train | def api_server(api_services, **kwargs):
"""Create an api_server.
The primary function of this method is to set up the WSGIApplication
instance for the service handlers described by the services passed in.
Additionally, it registers each API in ApiConfigRegistry for later use
in the BackendService.getApiConfi... | python | {
"resource": ""
} |
q237378 | ApiConfigRegistry.register_backend | train | def register_backend(self, config_contents):
"""Register a single API and its config contents.
Args:
config_contents: Dict containing API configuration.
"""
if config_contents is None:
return
self.__register_class(config_contents)
self.__api_configs.append(config_contents)
self.... | python | {
"resource": ""
} |
q237379 | ApiConfigRegistry.__register_class | train | def __register_class(self, parsed_config):
"""Register the class implementing this config, so we only add it once.
Args:
parsed_config: The JSON object with the API configuration being added.
Raises:
ApiConfigurationError: If the class has already been registered.
"""
methods = parsed_... | python | {
"resource": ""
} |
q237380 | ApiConfigRegistry.__register_methods | train | def __register_methods(self, parsed_config):
"""Register all methods from the given api config file.
Methods are stored in a map from method_name to rosyMethod,
the name of the ProtoRPC method to be called on the backend.
If no rosyMethod was specified the value will be None.
Args:
parsed_co... | python | {
"resource": ""
} |
q237381 | _ApiServer.__register_services | train | def __register_services(api_name_version_map, api_config_registry):
"""Register & return a list of each URL and class that handles that URL.
This finds every service class in api_name_version_map, registers it with
the given ApiConfigRegistry, builds the URL for that class, and adds
the URL and its fac... | python | {
"resource": ""
} |
q237382 | _ApiServer.__is_json_error | train | def __is_json_error(self, status, headers):
"""Determine if response is an error.
Args:
status: HTTP status code.
headers: Dictionary of (lowercase) header name to value.
Returns:
True if the response was an error, else False.
"""
content_header = headers.get('content-type', '')
... | python | {
"resource": ""
} |
q237383 | _ApiServer.__write_error | train | def __write_error(self, status_code, error_message=None):
"""Return the HTTP status line and body for a given error code and message.
Args:
status_code: HTTP status code to be returned.
error_message: Error message to be returned.
Returns:
Tuple (http_status, body):
http_status: ... | python | {
"resource": ""
} |
q237384 | _ApiServer.protorpc_to_endpoints_error | train | def protorpc_to_endpoints_error(self, status, body):
"""Convert a ProtoRPC error to the format expected by Google Endpoints.
If the body does not contain an ProtoRPC message in state APPLICATION_ERROR
the status and body will be returned unchanged.
Args:
status: HTTP status of the response from ... | python | {
"resource": ""
} |
q237385 | EndpointsDispatcherMiddleware._add_dispatcher | train | def _add_dispatcher(self, path_regex, dispatch_function):
"""Add a request path and dispatch handler.
Args:
path_regex: A string regex, the path to match against incoming requests.
dispatch_function: The function to call for these requests. The function
should take (request, start_response... | python | {
"resource": ""
} |
q237386 | EndpointsDispatcherMiddleware.dispatch | train | def dispatch(self, request, start_response):
"""Handles dispatch to apiserver handlers.
This typically ends up calling start_response and returning the entire
body of the response.
Args:
request: An ApiRequest, the request from the user.
start_response: A function with semantics defined ... | python | {
"resource": ""
} |
q237387 | EndpointsDispatcherMiddleware.dispatch_non_api_requests | train | def dispatch_non_api_requests(self, request, start_response):
"""Dispatch this request if this is a request to a reserved URL.
If the request matches one of our reserved URLs, this calls
start_response and returns the response body. This also handles OPTIONS
CORS requests.
Args:
request: An... | python | {
"resource": ""
} |
q237388 | EndpointsDispatcherMiddleware.verify_response | train | def verify_response(response, status_code, content_type=None):
"""Verifies that a response has the expected status and content type.
Args:
response: The ResponseTuple to be checked.
status_code: An int, the HTTP status code to be compared with response
status.
content_type: A string w... | python | {
"resource": ""
} |
q237389 | EndpointsDispatcherMiddleware.prepare_backend_environ | train | def prepare_backend_environ(self, host, method, relative_url, headers, body,
source_ip, port):
"""Build an environ object for the backend to consume.
Args:
host: A string containing the host serving the request.
method: A string containing the HTTP method of the reques... | python | {
"resource": ""
} |
q237390 | EndpointsDispatcherMiddleware.handle_backend_response | train | def handle_backend_response(self, orig_request, backend_request,
response_status, response_headers,
response_body, method_config, start_response):
"""Handle backend response, transforming output as needed.
This calls start_response and returns the res... | python | {
"resource": ""
} |
q237391 | EndpointsDispatcherMiddleware.fail_request | train | def fail_request(self, orig_request, message, start_response):
"""Write an immediate failure response to outfile, no redirect.
This calls start_response and returns the error body.
Args:
orig_request: An ApiRequest, the original request from the user.
message: A string containing the error mes... | python | {
"resource": ""
} |
q237392 | EndpointsDispatcherMiddleware.lookup_rest_method | train | def lookup_rest_method(self, orig_request):
"""Looks up and returns rest method for the currently-pending request.
Args:
orig_request: An ApiRequest, the original request from the user.
Returns:
A tuple of (method descriptor, parameters), or (None, None) if no method
was found for the cu... | python | {
"resource": ""
} |
q237393 | EndpointsDispatcherMiddleware.transform_request | train | def transform_request(self, orig_request, params, method_config):
"""Transforms orig_request to apiserving request.
This method uses orig_request to determine the currently-pending request
and returns a new transformed request ready to send to the backend. This
method accepts a rest-style or RPC-style... | python | {
"resource": ""
} |
q237394 | EndpointsDispatcherMiddleware._add_message_field | train | def _add_message_field(self, field_name, value, params):
"""Converts a . delimitied field name to a message field in parameters.
This adds the field to the params dict, broken out so that message
parameters appear as sub-dicts within the outer param.
For example:
{'a.b.c': ['foo']}
becomes:
... | python | {
"resource": ""
} |
q237395 | EndpointsDispatcherMiddleware._update_from_body | train | def _update_from_body(self, destination, source):
"""Updates the dictionary for an API payload with the request body.
The values from the body should override those already in the payload, but
for nested fields (message objects) the values can be combined
recursively.
Args:
destination: A di... | python | {
"resource": ""
} |
q237396 | EndpointsDispatcherMiddleware.transform_rest_request | train | def transform_rest_request(self, orig_request, params, method_parameters):
"""Translates a Rest request into an apiserving request.
This makes a copy of orig_request and transforms it to apiserving
format (moving request parameters to the body).
The request can receive values from the path, query and ... | python | {
"resource": ""
} |
q237397 | EndpointsDispatcherMiddleware.check_error_response | train | def check_error_response(self, body, status):
"""Raise an exception if the response from the backend was an error.
Args:
body: A string containing the backend response body.
status: A string containing the backend response status.
Raises:
BackendError if the response is an error.
"""... | python | {
"resource": ""
} |
q237398 | EndpointsDispatcherMiddleware.check_empty_response | train | def check_empty_response(self, orig_request, method_config, start_response):
"""If the response from the backend is empty, return a HTTP 204 No Content.
Args:
orig_request: An ApiRequest, the original request from the user.
method_config: A dict, the API config of the method to be called.
sta... | python | {
"resource": ""
} |
q237399 | EndpointsDispatcherMiddleware.transform_rest_response | train | def transform_rest_response(self, response_body):
"""Translates an apiserving REST response so it's ready to return.
Currently, the only thing that needs to be fixed here is indentation,
so it's consistent with what the live app will return.
Args:
response_body: A string containing the backend r... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.