code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
seconds = offset.days * 24 * 60 * 60 + offset.seconds microseconds = seconds * 10**6 + offset.microseconds return microseconds / (10**6 * 1.0)
def total_seconds(offset)
Backport of offset.total_seconds() from python 2.7+.
2.676379
2.62054
1.021308
# Check if the string includes a time zone offset. Break out the # part that doesn't include time zone info. Convert to uppercase # because all our comparisons should be case-insensitive. time_zone_match = _TIME_ZONE_RE.search(encoded_datetime) if time_zone_match: time_string = encode...
def decode_datetime(encoded_datetime)
Decode a DateTimeField parameter from a string to a python datetime. Args: encoded_datetime: A string in RFC 3339 format. Returns: A datetime object with the date and time specified in encoded_datetime. Raises: ValueError: If the string is not in a recognized format.
2.417413
2.417941
0.999782
message = super(DateTimeField, self).value_from_message(message) if message.time_zone_offset is None: return datetime.datetime.utcfromtimestamp( message.milliseconds / 1000.0) # Need to subtract the time zone offset, because when we call # datetime.f...
def value_from_message(self, message)
Convert DateTimeMessage to a datetime. Args: A DateTimeMessage instance. Returns: A datetime instance.
3.270323
3.40798
0.959607
metadata_url = 'http://{}'.format( os.environ.get('GCE_METADATA_ROOT', 'metadata.google.internal')) try: o = urllib_request.build_opener(urllib_request.ProxyHandler({})).open( urllib_request.Request( metadata_url, headers={'Metadata-Flavor': 'Google'})) excep...
def DetectGce()
Determine whether or not we're running on GCE. This is based on: https://cloud.google.com/compute/docs/metadata#runninggce Returns: True iff we're running on a GCE instance.
2.974069
3.141432
0.946724
if isinstance(scope_spec, six.string_types): return set(scope_spec.split(' ')) elif isinstance(scope_spec, collections.Iterable): return set(scope_spec) raise exceptions.TypecheckError( 'NormalizeScopes expected string or iterable, found %s' % ( type(scope_spec),))
def NormalizeScopes(scope_spec)
Normalize scope_spec to a set of strings.
2.765561
2.472041
1.118736
path = relative_path or method_config.relative_path or '' for param in method_config.path_params: param_template = '{%s}' % param # For more details about "reserved word expansion", see: # http://tools.ietf.org/html/rfc6570#section-3.2.2 reserved_chars = '' reserv...
def ExpandRelativePath(method_config, params, relative_path=None)
Determine the relative path for request.
3.090018
3.015127
1.024838
wait_time = 2 ** retry_attempt max_jitter = wait_time / 4.0 wait_time += random.uniform(-max_jitter, max_jitter) return max(1, min(wait_time, max_wait))
def CalculateWaitForRetry(retry_attempt, max_wait=60)
Calculates amount of time to wait before a retry attempt. Wait time grows exponentially with the number of attempts. A random amount of jitter is added to spread out retry attempts from different clients. Args: retry_attempt: Retry attempt counter. max_wait: Upper bound for wait time [seco...
3.292525
3.184778
1.033832
if '/' not in mime_type: raise exceptions.InvalidUserInputError( 'Invalid MIME type: "%s"' % mime_type) unsupported_patterns = [p for p in accept_patterns if ';' in p] if unsupported_patterns: raise exceptions.GeneratedClientError( 'MIME patterns with parameter u...
def AcceptableMimeType(accept_patterns, mime_type)
Return True iff mime_type is acceptable for one of accept_patterns. Note that this function assumes that all patterns in accept_patterns will be simple types of the form "type/subtype", where one or both of these can be "*". We do not support parameters (i.e. "; q=") in patterns. Args: accep...
4.318086
4.20408
1.027118
return [encoding.GetCustomJsonFieldMapping(request_type, json_name=p) or p for p in params]
def MapParamNames(params, request_type)
Reverse parameter remappings for URL construction.
20.282026
17.419619
1.164321
new_params = dict(params) for param_name, value in params.items(): field_remapping = encoding.GetCustomJsonFieldMapping( request_type, python_name=param_name) if field_remapping is not None: new_params[field_remapping] = new_params.pop(param_name) param_n...
def MapRequestParams(params, request_type)
Perform any renames/remappings needed for URL construction. Currently, we have several ways to customize JSON encoding, in particular of field names and enums. This works fine for JSON bodies, but also needs to be applied for path and query parameters in the URL. This function takes a dictionary f...
3.423714
3.179737
1.076729
util.Typecheck(json_value, JsonValue) _ValidateJsonValue(json_value) if json_value.is_null: return None entries = [(f, json_value.get_assigned_value(f.name)) for f in json_value.all_fields()] assigned_entries = [(f, value) for f, value in entries i...
def _JsonValueToPythonValue(json_value)
Convert the given JsonValue to a json string.
3.465993
3.286996
1.054456
if py_value is None: return JsonValue(is_null=True) if isinstance(py_value, bool): return JsonValue(boolean_value=py_value) if isinstance(py_value, six.string_types): return JsonValue(string_value=py_value) if isinstance(py_value, numbers.Number): if isinstance(py_va...
def _PythonValueToJsonValue(py_value)
Convert the given python value to a JsonValue.
1.795027
1.746453
1.027813
capabilities = [ messages.Variant.INT64, messages.Variant.UINT64, ] if field.variant not in capabilities: return encoding.CodecResult(value=value, complete=False) if field.repeated: result = [str(x) for x in value] else: result = str(value) return en...
def _EncodeInt64Field(field, value)
Handle the special case of int64 as a string.
3.519387
3.385023
1.039694
if field.repeated: result = [d.isoformat() for d in value] else: result = value.isoformat() return encoding.CodecResult(value=result, complete=True)
def _EncodeDateField(field, value)
Encoder for datetime.date objects.
5.197536
4.651879
1.117298
homoglyphs = { '\xa0': ' ', #   ? '\u00e3': '', # TODO(gsfowler) drop after .proto spurious char elided '\u00a0': ' ', #   ? '\u00a9': '(C)', # COPYRIGHT SIGN (would you believe "asciiglyph"?) '\u00ae': '(R)', # REGISTERED SIGN (would you believe "asciigly...
def ReplaceHomoglyphs(s)
Returns s with unicode homoglyphs replaced by ascii equivalents.
3.043939
3.020684
1.007699
if not isinstance(description, six.string_types): return description if six.PY3: # https://docs.python.org/3/reference/lexical_analysis.html#index-18 description = description.replace('\\N', '\\\\N') description = description.replace('\\u', '\\\\u') description = des...
def CleanDescription(description)
Return a version of description safe for printing in a docstring.
3.521184
3.215562
1.095045
if discovery_url.startswith('http'): return [discovery_url] elif '.' not in discovery_url: raise ValueError('Unrecognized value "%s" for discovery url') api_name, _, api_version = discovery_url.partition('.') return [ 'https://www.googleapis.com/discovery/v1/apis/%s/%s/rest'...
def _NormalizeDiscoveryUrls(discovery_url)
Expands a few abbreviations into full discovery urls.
2.49041
2.426464
1.026353
f = tempfile.NamedTemporaryFile(suffix='gz', mode='w+b', delete=False) try: f.write(gzipped_content) f.close() # force file synchronization with gzip.open(f.name, 'rb') as h: decompressed_content = h.read() return decompressed_content finally: os.unl...
def _Gunzip(gzipped_content)
Returns gunzipped content from gzipped contents.
2.454038
2.457083
0.998761
response = urllib_request.urlopen(url) encoding = response.info().get('Content-Encoding') if encoding == 'gzip': content = _Gunzip(response.read()) else: content = response.read() return content
def _GetURLContent(url)
Download and return the content of URL.
2.265752
2.373886
0.954449
discovery_urls = _NormalizeDiscoveryUrls(discovery_url) discovery_doc = None last_exception = None for url in discovery_urls: for _ in range(retries): try: content = _GetURLContent(url) if isinstance(content, bytes): content = ...
def FetchDiscoveryDoc(discovery_url, retries=5)
Fetch the discovery document at the given url.
2.554806
2.492266
1.025093
if not name: return name for prefix in self.__strip_prefixes: if name.startswith(prefix): return name[len(prefix):] return name
def __StripName(self, name)
Strip strip_prefix entries from name.
2.833683
2.204185
1.285592
name = re.sub('[^_A-Za-z0-9]', '_', name) if name[0].isdigit(): name = '_%s' % name while keyword.iskeyword(name): name = '%s_' % name # If we end up with __ as a prefix, we'll run afoul of python # field renaming, so we manually correct for it. ...
def CleanName(name)
Perform generic name cleaning.
4.770554
4.709384
1.012989
path_components = path.split('/') normalized_components = [] for component in path_components: if re.match(r'{[A-Za-z0-9_]+}$', component): normalized_components.append( '{%s}' % Names.CleanName(component[1:-1])) else: ...
def NormalizeRelativePath(path)
Normalize camelCase entries in path.
2.721869
2.558244
1.06396
# TODO(craigcitro): Get rid of this case here and in MethodName. if name is None: return name # TODO(craigcitro): This is a hack to handle the case of specific # protorpc class names; clean this up. if name.startswith(('protorpc.', 'message_types.', ...
def ClassName(self, name, separator='_')
Generate a valid class name from name.
5.504889
5.386267
1.022023
if name is None: return None name = Names.__ToCamel(name, separator=separator) return Names.CleanName(name)
def MethodName(self, name, separator='_')
Generate a valid method name from name.
8.349212
7.86828
1.061123
# TODO(craigcitro): We shouldn't need to strip this name, but some # of the service names here are excessive. Fix the API and then # remove this. name = self.__StripName(name) if self.__name_convention == 'LOWER_CAMEL': name = Names.__ToLowerCamel(name) ...
def FieldName(self, name)
Generate a valid field name from name.
8.121869
7.52442
1.079401
scopes = set( discovery_doc.get('auth', {}).get('oauth2', {}).get('scopes', {})) scopes.update(scope_ls) package = discovery_doc['name'] url_version = discovery_doc['version'] base_url, base_path = _ComputePaths(package, url_version, ...
def Create(cls, discovery_doc, scope_ls, client_id, client_secret, user_agent, names, api_key)
Create a new ClientInfo object from a discovery document.
2.450586
2.4582
0.996902
old_context = self.__comment_context self.__comment_context = True yield self.__comment_context = old_context
def CommentContext(self)
Print without any argument formatting.
4.36537
3.487255
1.251807
if position is None: position = len(_CREDENTIALS_METHODS) else: position = min(position, len(_CREDENTIALS_METHODS)) _CREDENTIALS_METHODS.insert(position, method) return method
def _RegisterCredentialsMethod(method, position=None)
Register a new method for fetching credentials. This new method should be a function with signature: client_info, **kwds -> Credentials or None This method can be used as a decorator, unless position needs to be supplied. Note that method must *always* accept arbitrary keyword arguments. Ar...
2.049298
2.412508
0.849447
scopes = util.NormalizeScopes(scopes) client_info = { 'client_id': client_id, 'client_secret': client_secret, 'scope': ' '.join(sorted(scopes)), 'user_agent': user_agent or '%s-generated/0.1' % package_name, } for method in _CREDENTIALS_METHODS: credentials =...
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent, credentials_filename=None, api_key=None, # pylint: disable=unused-argument client=None, # pylint: disable=unused-argument oauth2client_args=None, ...
Attempt to get credentials, using an oauth dance as the last resort.
2.795469
2.651158
1.054433
filename = os.path.expanduser(filename) # We have two options, based on our version of oauth2client. if oauth2client.__version__ > '1.5.2': # oauth2client >= 2.0.0 credentials = ( service_account.ServiceAccountCredentials.from_json_keyfile_name( filename, sco...
def ServiceAccountCredentialsFromFile(filename, scopes, user_agent=None)
Use the credentials in filename to create a token for scopes.
2.128118
2.119621
1.004009
private_key_filename = os.path.expanduser(private_key_filename) scopes = util.NormalizeScopes(scopes) if oauth2client.__version__ > '1.5.2': # oauth2client >= 2.0.0 credentials = ( service_account.ServiceAccountCredentials.from_p12_keyfile( service_account_na...
def ServiceAccountCredentialsFromP12File( service_account_name, private_key_filename, scopes, user_agent)
Create a new credential from the named .p12 keyfile.
2.131992
2.131459
1.00025
if use_metadata_ip: base_url = os.environ.get('GCE_METADATA_IP', '169.254.169.254') else: base_url = os.environ.get( 'GCE_METADATA_ROOT', 'metadata.google.internal') url = 'http://' + base_url + '/computeMetadata/v1/' + relative_url # Extra header requirement can be foun...
def _GceMetadataRequest(relative_url, use_metadata_ip=False)
Request the given url from the GCE metadata service.
2.086559
2.084773
1.000857
# There's one rare situation where gsutil will not have argparse # available, but doesn't need anything depending on argparse anyway, # since they're bringing their own credentials. So we just allow this # to fail with an ImportError in those cases. # # TODO(craigcitro): Move this import ba...
def _GetRunFlowFlags(args=None)
Retrieves command line flags based on gflags module.
5.290605
5.029087
1.052001
user_agent = client_info['user_agent'] scope_key = client_info['scope'] if not isinstance(scope_key, six.string_types): scope_key = ':'.join(scope_key) storage_key = client_info['client_id'] + user_agent + scope_key if _NEW_FILESTORE: credential_store = multiprocess_file_storag...
def CredentialsFromFile(path, client_info, oauth2client_args=None)
Read credentials from a file.
4.574462
4.59552
0.995418
credentials.refresh(http) url = _GetUserinfoUrl(credentials) response, content = http.request(url) return json.loads(content or '{}')
def GetUserinfo(credentials, http=None): # pylint: disable=invalid-name http = http or httplib2.Http() url = _GetUserinfoUrl(credentials) # We ignore communication woes here (i.e. SSL errors, socket # timeout), as handling these should be done in a common location. response, content = http.req...
Get the userinfo associated with the given credentials. This is dependent on the token having either the userinfo.email or userinfo.profile scope for the given token. Args: credentials: (oauth2client.client.Credentials) incoming credentials http: (httplib2.Http, optional) http instance to use ...
4.942995
6.210207
0.795947
if ((service_account_name and not service_account_keyfile) or (service_account_keyfile and not service_account_name)): raise exceptions.CredentialsError( 'Service account name or keyfile provided without the other') scopes = client_info['scope'].split() user_agent = clie...
def _GetServiceAccountCredentials( client_info, service_account_name=None, service_account_keyfile=None, service_account_json_keyfile=None, **unused_kwds)
Returns ServiceAccountCredentials from give file.
2.780754
2.682171
1.036755
scopes = client_info['scope'].split() if skip_application_default_credentials: return None gc = oauth2client.client.GoogleCredentials with cache_file_lock: try: # pylint: disable=protected-access # We've already done our own check for GAE/GCE # cr...
def _GetApplicationDefaultCredentials( client_info, skip_application_default_credentials=False, **unused_kwds)
Returns ADC with right scopes.
5.627213
5.525358
1.018434
creds = { # Credentials metadata dict. 'scopes': sorted(list(scopes)) if scopes else None, 'svc_acct_name': self.__service_account_name, } cache_file = _MultiProcessCacheFile(cache_filename) try: cached_creds_str = cache_file.LockedRead() ...
def _CheckCacheFileForMatch(self, cache_filename, scopes)
Checks the cache file to see if it matches the given credentials. Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials. Returns: List of scopes (if cache matches) or None.
3.650684
3.735316
0.977343
# Credentials metadata dict. creds = {'scopes': sorted(list(scopes)), 'svc_acct_name': self.__service_account_name} creds_str = json.dumps(creds) cache_file = _MultiProcessCacheFile(cache_filename) try: cache_file.LockedWrite(creds_str) ...
def _WriteCacheFile(self, cache_filename, scopes)
Writes the credential metadata to the cache file. This does not save the credentials themselves (CredentialStore class optionally handles that after this class is initialized). Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials.
5.610873
5.80194
0.967068
if not util.DetectGce(): raise exceptions.ResourceUnavailableError( 'GCE credentials requested outside a GCE instance') if not self.GetServiceAccount(self.__service_account_name): raise exceptions.ResourceUnavailableError( 'GCE credentials...
def _ScopesFromMetadataServer(self, scopes)
Returns instance scopes based on GCE metadata server.
4.495979
4.240528
1.06024
relative_url = 'instance/service-accounts/{0}/token'.format( self.__service_account_name) try: response = _GceMetadataRequest(relative_url) except exceptions.CommunicationError: self.invalid = True if self.store: self.store...
def _do_refresh_request(self, unused_http_request)
Refresh self.access_token by querying the metadata server. If self.store is initialized, store acquired credentials there.
3.130414
2.814344
1.112307
# pylint: disable=import-error from google.appengine.api import app_identity try: token, _ = app_identity.get_access_token(self._scopes) except app_identity.Error as e: raise exceptions.CredentialsError(str(e)) self.access_token = token
def _refresh(self, _)
Refresh self.access_token. Args: _: (ignored) A function matching httplib2.Http.request's signature.
3.744386
3.061532
1.223043
try: is_locked = self._process_lock.acquire(timeout=self._lock_timeout) yield is_locked finally: if is_locked: self._process_lock.release()
def _ProcessLockAcquired(self)
Context manager for process locks with timeout.
3.088618
2.649801
1.165604
file_contents = None with self._thread_lock: if not self._EnsureFileExists(): return None with self._process_lock_getter() as acquired_plock: if not acquired_plock: return None with open(self._filename, ...
def LockedRead(self)
Acquire an interprocess lock and dump cache contents. This method safely acquires the locks then reads a string from the cache file. If the file does not exist and cannot be created, it will return None. If the locks cannot be acquired, this will also return None. Returns: ...
4.508183
4.109715
1.096958
if isinstance(cache_data, six.text_type): cache_data = cache_data.encode(encoding=self._encoding) with self._thread_lock: if not self._EnsureFileExists(): return False with self._process_lock_getter() as acquired_plock: if not...
def LockedWrite(self, cache_data)
Acquire an interprocess lock and write a string. This method safely acquires the locks then writes a string to the cache file. If the string is written successfully the function will return True, if the write fails for any reason it will return False. Args: cache_data...
3.631351
3.465033
1.047999
if not os.path.exists(self._filename): old_umask = os.umask(0o177) try: open(self._filename, 'a+b').close() except OSError: return False finally: os.umask(old_umask) return True
def _EnsureFileExists(self)
Touches a file; returns False on error, True on success.
2.376425
2.090463
1.136794
request = encoding.CopyProtoMessage(request) setattr(request, current_token_attribute, None) while limit is None or limit: if batch_size_attribute: # On Py3, None is not comparable so min() below will fail. # On Py2, None is always less than any number so if batch_size ...
def YieldFromList( service, request, global_params=None, limit=None, batch_size=100, method='List', field='items', predicate=None, current_token_attribute='pageToken', next_token_attribute='nextPageToken', batch_size_attribute='maxResults')
Make a series of List requests, keeping track of page tokens. Args: service: apitools_base.BaseApiService, A service with a .List() method. request: protorpc.messages.Message, The request message corresponding to the service's .List() method, with all the attributes populated except...
3.265479
3.409728
0.957695
if method_info.description: description = util.CleanDescription(method_info.description) first_line, newline, remaining = method_info.description.partition( '\n') if not first_line.endswith('.'): first_line = '%s.' % first_line ...
def __PrintDocstring(self, printer, method_info, method_name, name)
Print a docstring for a service method.
4.140004
3.819187
1.084001
printer() printer('service %s {', self.__GetServiceClassName(name)) with printer.Indent(): for method_name, method_info in method_info_map.items(): for line in textwrap.wrap(method_info.description, printer.CalculateW...
def __WriteProtoServiceDeclaration(self, printer, name, method_info_map)
Write a single service declaration to a proto file.
2.566642
2.478991
1.035358
self.Validate() client_info = self.__client_info printer('// Generated services for %s version %s.', client_info.package, client_info.version) printer() printer('syntax = "proto2";') printer('package %s;', self.__package) printer('import "...
def WriteProtoFile(self, printer)
Write the services in this registry to out as proto.
3.681227
3.333413
1.104342
self.Validate() client_info = self.__client_info printer('', client_info.package, client_info.version) printer('# NOTE: This file is autogenerated and should not be edited ' 'by hand.') printer('from %s import base_api', self.__base_files_...
def WriteFile(self, printer)
Write the services in this registry to out.
2.24452
2.211348
1.015001
schema = {} schema['id'] = self.__names.ClassName('%sRequest' % ( self.__names.ClassName(method_description['id'], separator='.'),)) schema['type'] = 'object' schema['properties'] = collections.OrderedDict() if 'parameterOrder' not in method_description: ...
def __CreateRequestType(self, method_description, body_type=None)
Create a request type for this method.
3.059279
3.044058
1.005
schema = {} method_name = self.__names.ClassName( method_description['id'], separator='.') schema['id'] = self.__names.ClassName('%sResponse' % method_name) schema['type'] = 'object' schema['description'] = 'An empty %s response.' % method_name self._...
def __CreateVoidResponseType(self, method_description)
Create an empty response type.
5.648316
5.150361
1.096684
if not request_type: return True method_id = method_description.get('id', '') if method_id in self.__unelidable_request_methods: return True message = self.__message_registry.LookupDescriptorOrDie(request_type) if message is None: retu...
def __NeedRequestType(self, method_description, request_type)
Determine if this method needs a new request type created.
3.729894
3.652825
1.021099
size_groups = re.match(r'(?P<size>\d+)(?P<unit>.B)?$', max_size) if size_groups is None: raise ValueError('Could not parse maxSize') size, unit = size_groups.group('size', 'unit') shift = 0 if unit is not None: unit_dict = {'KB': 10, 'MB': 20, 'GB...
def __MaxSizeToInt(self, max_size)
Convert max_size to an int.
2.573007
2.402274
1.071071
config = base_api.ApiUploadInfo() if 'maxSize' in media_upload_config: config.max_size = self.__MaxSizeToInt( media_upload_config['maxSize']) if 'accept' not in media_upload_config: logging.warn( 'No accept types found for upload c...
def __ComputeUploadConfig(self, media_upload_config, method_id)
Fill out the upload config for this method.
3.657346
3.600462
1.015799
relative_path = self.__names.NormalizeRelativePath( ''.join((self.__client_info.base_path, method_description['path']))) method_id = method_description['id'] ordered_params = [] for param_name in method_description.get('parameterOrder', []): ...
def __ComputeMethodInfo(self, method_description, request, response, request_field)
Compute the base_api.ApiMethodInfo for this method.
2.282131
2.283422
0.999434
body_field_name = self.__BodyFieldName(body_type) if body_field_name in method_description.get('parameters', {}): body_field_name = self.__names.FieldName( '%s_resource' % body_field_name) # It's exceedingly unlikely that we'd get two name collisions, which ...
def __GetRequestField(self, method_description, body_type)
Determine the request field for this method.
4.116657
4.057324
1.014624
service_name = self.__names.CleanName(service_name) method_descriptions = methods.get('methods', {}) method_info_map = collections.OrderedDict() items = sorted(method_descriptions.items()) for method_name, method_description in items: method_name = self.__nam...
def AddServiceFromResource(self, service_name, methods)
Add a new service named service_name with the given methods.
3.412632
3.430616
0.994758
buf = io.BytesIO() with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f: f.write(data) return buf.getvalue()
def compress(data, compresslevel=9)
Compress data in one shot and return the compressed string. Optional argument is the compression level, in range of 0-9.
1.859637
2.25396
0.825053
with GzipFile(fileobj=io.BytesIO(data)) as f: return f.read()
def decompress(data)
Decompress a gzip compressed string in one shot. Return the decompressed string.
3.342492
3.312952
1.008916
'''Return the uncompressed stream file position indicator to the beginning of the file''' if self.mode != READ: raise OSError("Can't rewind in write mode") self.fileobj.seek(0) self._new_member = True self.extrabuf = b"" self.extrasize = 0 self...
def rewind(self)
Return the uncompressed stream file position indicator to the beginning of the file
6.300933
4.124669
1.527622
if http_request.loggable_body is None: yield return old_level = httplib2.debuglevel http_levels = {} httplib2.debuglevel = level if http is not None: for connection_key, connection in http.connections.items(): # httplib2 stores two kinds of values in this dic...
def _Httplib2Debuglevel(http_request, level, http=None)
Temporarily change the value of httplib2.debuglevel, if necessary. If http_request has a `loggable_body` distinct from `body`, then we need to prevent httplib2 from logging the full body. This sets httplib2.debuglevel for the duration of the `with` block; however, that alone won't change the value of e...
3.357979
3.137661
1.070217
if getattr(http, 'connections', None): for conn_key in list(http.connections.keys()): if ':' in conn_key: del http.connections[conn_key]
def RebuildHttpConnections(http)
Rebuilds all http connections in the httplib2.Http instance. httplib2 overloads the map in http.connections to contain two different types of values: { scheme string: connection class } and { scheme + authority string : actual http connection } Here we remove all of the entries for actual connecti...
3.321159
3.636966
0.913167
# If the server indicates how long to wait, use that value. Otherwise, # calculate the wait time on our own. retry_after = None # Transport failures if isinstance(retry_args.exc, (http_client.BadStatusLine, http_client.IncompleteRead, ...
def HandleExceptionsAndRebuildHttpConnections(retry_args)
Exception handler for http failures. This catches known failures and rebuilds the underlying HTTP connections. Args: retry_args: An ExceptionRetryArgs tuple.
2.479664
2.49586
0.993511
retry = 0 first_req_time = time.time() while True: try: return _MakeRequestNoRetry( http, http_request, redirections=redirections, check_response_func=check_response_func) # retry_func will consume the exception types it handles and raise. ...
def MakeRequest(http, http_request, retries=7, max_retry_wait=60, redirections=5, retry_func=HandleExceptionsAndRebuildHttpConnections, check_response_func=CheckResponse)
Send http_request via the given http, performing error/retry handling. Args: http: An httplib2.Http instance, or a http multiplexer that delegates to an underlying http, for example, HTTPMultiplexer. http_request: A Request to send. retries: (int, default 7) Number of retries to attempt...
3.377247
3.489613
0.9678
connection_type = None # Handle overrides for connection types. This is used if the caller # wants control over the underlying connection for managing callbacks # or hash digestion. if getattr(http, 'connections', None): url_scheme = parse.urlsplit(http_request.url).scheme if u...
def _MakeRequestNoRetry(http, http_request, redirections=5, check_response_func=CheckResponse)
Send http_request via the given http. This wrapper exists to handle translation between the plain httplib2 request/response types and the Request and Response types above. Args: http: An httplib2.Http instance, or a http multiplexer that delegates to an underlying http, for example, HTTPMu...
4.313099
4.63979
0.929589
self.__body = value if value is not None: # Avoid calling len() which cannot exceed 4GiB in 32-bit python. body_length = getattr( self.__body, 'length', None) or len(self.__body) self.headers['content-length'] = str(body_length) else: ...
def body(self, value)
Sets the request body; handles logging and length measurement.
5.315469
4.755117
1.117842
def ProcessContentRange(content_range): _, _, range_spec = content_range.partition(' ') byte_range, _, _ = range_spec.partition('/') start, _, end = byte_range.partition('-') return int(end) - int(start) + 1 if '-content-encoding' in self.info an...
def length(self)
Return the length of this response. We expose this as an attribute since using len() directly can fail for responses larger than sys.maxint. Returns: Response length (as int or long)
3.489202
3.416611
1.021246
raise exceptions.NotYetImplementedError( 'Illegal read of size %s requested on BufferedStream. ' 'Wrapped stream %s is at position %s-%s, ' '%s bytes remaining.' % (size, self.__stream, self.__start_pos, self.__end_pos, self._b...
def read(self, size=None): # pylint: disable=invalid-name if size is None or size < 0
Reads from the buffer.
5.056664
4.631125
1.091887
self.Validate() extended_descriptor.WriteMessagesFile( self.__file_descriptor, self.__package, self.__client_info.version, printer)
def WriteProtoFile(self, printer)
Write the messages file to out as proto.
17.129868
14.101894
1.214721
self.Validate() extended_descriptor.WritePythonFile( self.__file_descriptor, self.__package, self.__client_info.version, printer)
def WriteFile(self, printer)
Write the messages file to out.
21.875067
21.377094
1.023295
if not isinstance(new_descriptor, ( extended_descriptor.ExtendedMessageDescriptor, extended_descriptor.ExtendedEnumDescriptor)): raise ValueError('Cannot add descriptor of type %s' % ( type(new_descriptor),)) full_name = self.__Compute...
def __RegisterDescriptor(self, new_descriptor)
Register the given descriptor in this registry.
2.778966
2.784138
0.998142
message = extended_descriptor.ExtendedEnumDescriptor() message.name = self.__names.ClassName(name) message.description = util.CleanDescription(description) self.__DeclareDescriptor(message.name) for index, (enum_name, enum_description) in enumerate( zip(e...
def AddEnumDescriptor(self, name, description, enum_values, enum_descriptions)
Add a new EnumDescriptor named name with the given enum values.
3.645015
3.680652
0.990318
# TODO(craigcitro): This is a hack. Remove it. message = extended_descriptor.ExtendedMessageDescriptor() message.name = self.__names.ClassName(schema['id']) message.alias_for = alias_for self.__DeclareDescriptor(message.name) self.__AddImport('from %s import extr...
def __DeclareMessageAlias(self, schema, alias_for)
Declare schema as an alias for alias_for.
9.539835
9.148257
1.042804
additional_properties_info = schema['additionalProperties'] entries_type_name = self.__AddAdditionalPropertyType( message.name, additional_properties_info) description = util.CleanDescription( additional_properties_info.get('description')) if description ...
def __AddAdditionalProperties(self, message, schema, properties)
Add an additionalProperties field to message.
4.883934
4.900885
0.996541
# TODO(craigcitro): Is schema_name redundant? if self.__GetDescriptor(schema_name): return if schema.get('enum'): self.__DeclareEnum(schema_name, schema) return if schema.get('type') == 'any': self.__DeclareMessageAlias(schema, 'ex...
def AddDescriptorFromSchema(self, schema_name, schema)
Add a new MessageDescriptor named schema_name based on schema.
4.527438
4.389608
1.031399
new_type_name = 'AdditionalProperty' property_schema = dict(property_schema) # We drop the description here on purpose, so the resulting # messages are less repetitive. property_schema.pop('description', None) description = 'An additional property for a %s object...
def __AddAdditionalPropertyType(self, name, property_schema)
Add a new nested AdditionalProperty message.
3.342621
3.061619
1.091782
entry_schema.pop('description', None) description = 'Single entry in a %s.' % parent_name schema = { 'id': entry_type_name, 'type': 'object', 'description': description, 'properties': { 'entry': { 'type'...
def __AddEntryType(self, entry_type_name, entry_schema, parent_name)
Add a type for a list entry.
2.957359
2.848449
1.038235
field = descriptor.FieldDescriptor() field.name = self.__names.CleanName(name) field.number = index field.label = self.__ComputeLabel(attrs) new_type_name_hint = self.__names.ClassName( '%sValue' % self.__names.ClassName(name)) type_info = self.__GetT...
def __FieldDescriptorFromProperties(self, name, index, attrs)
Create a field descriptor for these attrs.
3.379935
3.287405
1.028147
type_ref = self.__names.ClassName(attrs.get('$ref')) type_name = attrs.get('type') if not (type_ref or type_name): raise ValueError('No type found for %s' % attrs) if type_ref: self.__AddIfUnknown(type_ref) # We don't actually know this is a...
def __GetTypeInfo(self, attrs, name_hint)
Return a TypeInfo object for attrs, creating one if needed.
2.939783
2.907238
1.011195
if args.discovery_url: try: return util.FetchDiscoveryDoc(args.discovery_url) except exceptions.CommunicationError: raise exceptions.GeneratedClientError( 'Could not fetch discovery doc') infile = os.path.expanduser(args.infile) or '/dev/stdin' w...
def _GetDiscoveryDocFromFlags(args)
Get the discovery doc from flags.
4.459189
4.321371
1.031892
discovery_doc = _GetDiscoveryDocFromFlags(args) names = util.Names( args.strip_prefix, args.experimental_name_convention, args.experimental_capitalize_enums) if args.client_json: try: with io.open(args.client_json, encoding='utf8') as client_json: ...
def _GetCodegenFromFlags(args)
Create a codegen object from flags.
3.460611
3.415953
1.013073
codegen = _GetCodegenFromFlags(args) if codegen is None: logging.error('Failed to create codegen, exiting.') return 128 _WriteGeneratedFiles(args, codegen) if args.init_file != 'none': _WriteInit(codegen)
def GenerateClient(args)
Driver for client code generation.
7.39981
7.344214
1.00757
discovery_doc = _GetDiscoveryDocFromFlags(args) package = discovery_doc['name'] original_outdir = os.path.expanduser(args.outdir) args.outdir = os.path.join( args.outdir, 'apitools/clients/%s' % package) args.root_package = 'apitools.clients.%s' % package codegen = _GetCodegenFrom...
def GeneratePipPackage(args)
Generate a client as a pip-installable tarball.
4.721947
4.491842
1.051227
read_size = min(size, self.__remaining_bytes) else: read_size = self.__remaining_bytes data = self.__stream.read(read_size) if read_size > 0 and not data: raise exceptions.StreamExhausted( 'Not enough bytes in stream; expected %d, exhausted ' ...
def read(self, size=None): # pylint: disable=missing-docstring if size is not None
Read at most size bytes from this slice. Compared to other streams, there is one case where we may unexpectedly raise an exception on read: if the underlying stream is exhausted (i.e. returns no bytes on read), and the size of this slice indicates we should still be able to read more by...
3.505681
3.750592
0.934701
import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log ...
def download_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 )
Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the nu...
4.09857
4.240924
0.966433
try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here fi...
def main(argv, version=DEFAULT_VERSION)
Install or upgrade setuptools and EasyInstall
4.209947
4.00234
1.051871
import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = ...
def update_md5(filenames)
Update our built-in md5 registry
2.920425
2.902117
1.006309
# Retrieve the configs for the desired method and service. method_config = service.GetMethodConfig(method) upload_config = service.GetUploadConfig(method) # Prepare the HTTP Request. http_request = service.PrepareHttpRequest( method_config, request, global_p...
def Add(self, service, method, request, global_params=None)
Add a request to the batch. Args: service: A class inheriting base_api.BaseApiService. method: A string indicated desired method from the service. See the example in the class docstring. request: An input message appropriate for the specified service.me...
4.288174
3.969789
1.080202
requests = [request for request in self.api_requests if not request.terminal_state] batch_size = max_batch_size or len(requests) for attempt in range(max_retries): if attempt: time.sleep(sleep_between_polls) for i in range(0,...
def Execute(self, http, sleep_between_polls=5, max_retries=5, max_batch_size=None, batch_request_callback=None)
Execute all of the requests in the batch. Args: http: httplib2.Http object for use in the request. sleep_between_polls: Integer number of seconds to sleep between polls. max_retries: Max retries. Any requests that have not succeeded by this number of re...
3.078434
3.187186
0.965878
if not (header.startswith('<') or header.endswith('>')): raise exceptions.BatchError( 'Invalid value for Content-ID: %s' % header) if '+' not in header: raise exceptions.BatchError( 'Invalid value for Content-ID: %s' % header) _, r...
def _ConvertHeaderToId(header)
Convert a Content-ID header value to an id. Presumes the Content-ID header conforms to the format that _ConvertIdToHeader() returns. Args: header: A string indicating the Content-ID header value. Returns: The extracted id value. Raises: BatchErro...
3.622553
3.191417
1.135092
# Construct status line parsed = urllib_parse.urlsplit(request.url) request_line = urllib_parse.urlunsplit( ('', '', parsed.path, parsed.query, '')) if not isinstance(request_line, six.text_type): request_line = request_line.decode('utf-8') status...
def _SerializeRequest(self, request)
Convert a http_wrapper.Request object into a string. Args: request: A http_wrapper.Request to serialize. Returns: The request as a string in application/http format.
3.537065
3.556652
0.994493
# Strip off the status line. status_line, payload = payload.split('\n', 1) _, status, _ = status_line.split(' ', 2) # Parse the rest of the response. parser = email_parser.Parser() msg = parser.parsestr(payload) # Get the headers. info = dict(ms...
def _DeserializeResponse(self, payload)
Convert string into Response and content. Args: payload: Header and body string to be deserialized. Returns: A Response object
4.889833
4.903798
0.997152
handler = RequestResponseAndHandler(request, None, callback) self.__request_response_handlers[self._NewId()] = handler
def Add(self, request, callback=None)
Add a new request. Args: request: A http_wrapper.Request to add to the batch. callback: A callback to be called for this response, of the form callback(response, exception). The first parameter is the deserialized response object. The second is an a...
12.126768
22.673737
0.534838
message = mime_multipart.MIMEMultipart('mixed') # Message should not write out its own headers. setattr(message, '_write_headers', lambda self: None) # Add all the individual requests. for key in self.__request_response_handlers: msg = mime_nonmultipart.MIME...
def _Execute(self, http)
Serialize batch request, send to server, process response. Args: http: A httplib2.Http object to be used to make the request with. Raises: httplib2.HttpLib2Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format.
3.427081
3.286485
1.04278
self._Execute(http) for key in self.__request_response_handlers: response = self.__request_response_handlers[key].response callback = self.__request_response_handlers[key].handler exception = None if response.status_code >= 300: ...
def Execute(self, http)
Execute all the requests as a single batched HTTP request. Args: http: A httplib2.Http object to be used with the request. Returns: None Raises: BatchError if the response is the wrong format.
3.278226
3.447321
0.950949
outer_definition_name = cls.outer_definition_name() if outer_definition_name is None: return six.text_type(cls.__name__) return u'%s.%s' % (outer_definition_name, cls.__name__)
def definition_name(cls)
Helper method for creating definition name. Names will be generated to include the classes package name, scope (if the class is nested in another definition) and class name. By default, the package name for a definition is derived from its module name. However, this value can b...
2.792894
3.356714
0.832032
outer_definition = cls.message_definition() if not outer_definition: return util.get_package_for_module(cls.__module__) return outer_definition.definition_name()
def outer_definition_name(cls)
Helper method for creating outer definition name. Returns: If definition is nested, will return the outer definitions name, else the package name.
5.745057
5.706094
1.006828