code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
result = self.search(artist_name, search_type=100, limit=limit) if result['result']['artistCount'] <= 0: LOG.warning('Artist %s not existed!', artist_name) raise SearchNotFound('Artist {} not existed.'.format(artist_name)) else: artists = result['re...
def search_artist(self, artist_name, quiet=False, limit=9)
Search artist by artist name. :params artist_name: artist name. :params quiet: automatically select the best one. :params limit: artist count returned by weapi. :return: a Artist object.
3.317434
3.145239
1.054748
result = self.search(playlist_name, search_type=1000, limit=limit) if result['result']['playlistCount'] <= 0: LOG.warning('Playlist %s not existed!', playlist_name) raise SearchNotFound('playlist {} not existed'.format(playlist_name)) else: playlist...
def search_playlist(self, playlist_name, quiet=False, limit=9)
Search playlist by playlist name. :params playlist_name: playlist name. :params quiet: automatically select the best one. :params limit: playlist count returned by weapi. :return: a Playlist object.
3.326632
3.170994
1.049082
result = self.search(user_name, search_type=1002, limit=limit) if result['result']['userprofileCount'] <= 0: LOG.warning('User %s not existed!', user_name) raise SearchNotFound('user {} not existed'.format(user_name)) else: users = result['result'][...
def search_user(self, user_name, quiet=False, limit=9)
Search user by user name. :params user_name: user name. :params quiet: automatically select the best one. :params limit: user count returned by weapi. :return: a User object.
4.089898
4.058319
1.007781
url = 'http://music.163.com/weapi/user/playlist?csrf_token=' csrf = '' params = {'offset': 0, 'uid': user_id, 'limit': limit, 'csrf_token': csrf} result = self.post_request(url, params) playlists = result['playlist'] return self.display.select_...
def get_user_playlists(self, user_id, limit=1000)
Get a user's all playlists. warning: login is required for private playlist. :params user_id: user id. :params limit: playlist count returned by weapi. :return: a Playlist Object.
3.451555
3.101528
1.112856
url = 'http://music.163.com/weapi/v3/playlist/detail?csrf_token=' csrf = '' params = {'id': playlist_id, 'offset': 0, 'total': True, 'limit': limit, 'n': 1000, 'csrf_token': csrf} result = self.post_request(url, params) songs = result['playlist']['tra...
def get_playlist_songs(self, playlist_id, limit=1000)
Get a playlists's all songs. :params playlist_id: playlist id. :params limit: length of result returned by weapi. :return: a list of Song object.
2.304689
2.14725
1.073321
url = 'http://music.163.com/api/album/{}/'.format(album_id) result = self.get_request(url) songs = result['album']['songs'] songs = [Song(song['id'], song['name']) for song in songs] return songs
def get_album_songs(self, album_id)
Get a album's all songs. warning: use old api. :params album_id: album id. :return: a list of Song object.
2.611627
2.490122
1.048795
url = 'http://music.163.com/api/artist/{}'.format(artist_id) result = self.get_request(url) hot_songs = result['hotSongs'] songs = [Song(song['id'], song['name']) for song in hot_songs] return songs
def get_artists_hot_songs(self, artist_id)
Get a artist's top50 songs. warning: use old api. :params artist_id: artist id. :return: a list of Song object.
2.342818
2.441073
0.959749
url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token=' csrf = '' params = {'ids': [song_id], 'br': bit_rate, 'csrf_token': csrf} result = self.post_request(url, params) song_url = result['data'][0]['url'] # download address if song_url is None:...
def get_song_url(self, song_id, bit_rate=320000)
Get a song's download address. :params song_id: song id<int>. :params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000} :return: a song's download address.
3.053683
2.854229
1.06988
url = 'http://music.163.com/api/song/lyric?os=osx&id={}&lv=-1&kv=-1&tv=-1'.format( # NOQA song_id) result = self.get_request(url) if 'lrc' in result and result['lrc']['lyric'] is not None: lyric_info = result['lrc']['lyric'] else: lyric_info...
def get_song_lyric(self, song_id)
Get a song's lyric. warning: use old api. :params song_id: song id. :return: a song's lyric.
2.264598
2.207221
1.025995
if not os.path.exists(folder): os.makedirs(folder) fpath = os.path.join(folder, song_name+'.mp3') if sys.platform == 'win32' or sys.platform == 'cygwin': valid_name = re.sub(r'[<>:"/\\|?*]', '', song_name) if valid_name != song_name: ...
def get_song_by_url(self, song_url, song_name, folder, lyric_info)
Download a song and save it to disk. :params song_url: download address. :params song_name: song name. :params folder: storage path. :params lyric: lyric info.
1.787878
1.79776
0.994503
username = click.prompt('Please enter your email or phone number') password = click.prompt('Please enter your password', hide_input=True) pattern = re.compile(r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$') if pattern.match(username): # use phone number to login url = 'https...
def login(self)
Login entrance.
2.395299
2.33815
1.024442
# prepare OrderedDict geojson structure feature = OrderedDict() # the list of fields that will be processed by get_properties # we will remove fields that have been already processed # to increase performance on large numbers fields = list(self.fields.values()) ...
def to_representation(self, instance)
Serialize objects -> primitives.
3.356359
3.307971
1.014628
properties = OrderedDict() for field in fields: if field.write_only: continue value = field.get_attribute(instance) representation = None if value is not None: representation = field.to_representation(value) ...
def get_properties(self, instance, fields)
Get the feature metadata which will be used for the GeoJSON "properties" key. By default it returns all serializer fields excluding those used for the ID, the geometry and the bounding box. :param instance: The current Django model instance :param fields: The list of fields to ...
2.948001
3.254222
0.9059
if 'properties' in data: data = self.unformat_geojson(data) return super(GeoFeatureModelSerializer, self).to_internal_value(data)
def to_internal_value(self, data)
Override the parent method to first remove the GeoJSON formatting
5.382009
3.088508
1.742592
attrs = feature["properties"] if 'geometry' in feature: attrs[self.Meta.geo_field] = feature['geometry'] if self.Meta.bbox_geo_field and 'bbox' in feature: attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature['bbox']) return attrs
def unformat_geojson(self, feature)
This function should return a dictionary containing keys which maps to serializer fields. Remember that GeoJSON contains a key "properties" which contains the feature metadata. This should be flattened to make sure this metadata is stored in the right serializer fields. :param ...
3.252904
3.582741
0.907937
if hasattr(value, '__iter__'): return tuple(self._recursive_round(v, precision) for v in value) return round(value, precision)
def _recursive_round(self, value, precision)
Round all numbers within an array or nested arrays value: number or nested array of numbers precision: integer valueue of number of decimals to keep
2.53648
3.0143
0.841482
if geo_type in ('MultiPoint', 'LineString'): close = (geo_type == 'LineString') output = [] for coord in geometry: coord = tuple(coord) if not output or coord != output[-1]: output.append(coord) if close...
def _rm_redundant_points(self, geometry, geo_type)
Remove redundant coordinate pairs from geometry geometry: array of coordinates or nested-array of coordinates geo_type: GeoJSON type attribute for provided geometry, used to determine structure of provided `geometry` argument
2.124415
2.16633
0.980651
from django.contrib.gis.db import models from rest_framework.serializers import ModelSerializer from .fields import GeometryField try: # drf 3.0 field_mapping = ModelSerializer._field_mapping.mapping except AttributeError: # drf 3.1 ...
def ready(self)
update Django Rest Framework serializer mappings
2.499902
2.204364
1.13407
# d * (180 / pi) / earthRadius ==> degrees longitude # (degrees longitude) / cos(latitude) ==> degrees latitude lat = latitude if latitude >= 0 else -1 * latitude rad2deg = 180 / pi earthRadius = 6378160.0 latitudeCorrection = 0.5 * (1 + cos(lat * pi / 180...
def dist_to_deg(self, distance, latitude)
distance = distance in meters latitude = latitude in degrees at the equator, the distance of one degree is equal in latitude and longitude. at higher latitudes, a degree longitude is shorter in length, proportional to cos(latitude) http://en.wikipedia.org/wiki/Decimal_degrees T...
4.765443
5.05414
0.942879
# * base will never contain params, query, or fragment # * url will never contain a scheme or net_loc. # In general, this means we can safely join on /; we just need to # ensure we end up with precisely one / joining base and url. The # exception here is the case of media uploads, where url will b...
def _urljoin(base, url): # pylint: disable=invalid-name # In general, it's unsafe to simply join base and url. However, for # the case of discovery documents, we know
Custom urljoin replacement supporting : before / in url.
5.555404
5.85896
0.948189
args = { 'api_key': self._API_KEY, 'client': self, 'client_id': self._CLIENT_ID, 'client_secret': self._CLIENT_SECRET, 'package_name': self._PACKAGE, 'scopes': self._SCOPES, 'user_agent': self._USER_AGENT, } ...
def _SetCredentials(self, **kwds)
Fetch credentials, and set them for this client. Note that we can't simply return credentials, since creating them may involve side-effecting self. Args: **kwds: Additional keyword arguments are passed on to GetCredentials. Returns: None. Sets self._credentials.
5.493142
5.444002
1.009026
old_model = self.response_type_model self.__response_type_model = 'json' yield self.__response_type_model = old_model
def JsonResponseModel(self)
In this context, return raw JSON instead of proto.
4.928895
4.5707
1.078368
if self.log_request: logging.info( 'Calling method %s with %s: %s', method_config.method_id, method_config.request_type_name, request) return request
def ProcessRequest(self, method_config, request)
Hook for pre-processing of requests.
4.438678
4.367477
1.016303
http_request.headers.update(self.additional_http_headers) if self.log_request: logging.info('Making http %s to %s', http_request.http_method, http_request.url) logging.info('Headers: %s', pprint.pformat(http_request.headers)) if http_...
def ProcessHttpRequest(self, http_request)
Hook for pre-processing of http requests.
3.48067
3.358329
1.036429
try: message = encoding.JsonToMessage(response_type, data) except (exceptions.InvalidDataFromServerError, messages.ValidationError, ValueError) as e: raise exceptions.InvalidDataFromServerError( 'Error decoding response "%s" as type %s: %s...
def DeserializeMessage(self, response_type, data)
Deserialize the given data as method_config.response_type.
4.406787
4.311622
1.022072
url_builder = _UrlBuilder.FromUrl(url) if self.global_params.key: url_builder.query_params['key'] = self.global_params.key return url_builder.url
def FinalizeTransferUrl(self, url)
Modify the url for a given transfer, based on auth and version.
4.657919
4.683556
0.994526
method_config = self._method_configs.get(method) if method_config: return method_config func = getattr(self, method, None) if func is None: raise KeyError(method) method_config = getattr(func, 'method_config', None) if method_config is Non...
def GetMethodConfig(self, method)
Returns service cached method config for given method.
2.281445
2.237793
1.019507
util.Typecheck(global_params, (type(None), self.__client.params_type)) result = self.__client.params_type() global_params = global_params or self.__client.params_type() for field in result.all_fields(): value = global_params.get_assigned_value(field.name) ...
def __CombineGlobalParams(self, global_params, default_params)
Combine the given params with the defaults.
3.481728
3.272967
1.063783
if isinstance(field, messages.BytesField) and value is not None: return base64.urlsafe_b64encode(value) elif isinstance(value, six.text_type): return value.encode('utf8') elif isinstance(value, six.binary_type): return value.decode('utf8') eli...
def __FinalUrlValue(self, value, field)
Encode value for the URL, using field to skip encoding for bytes.
2.267944
2.177902
1.041343
# First, handle the global params. global_params = self.__CombineGlobalParams( global_params, self.__client.global_params) global_param_names = util.MapParamNames( [x.name for x in self.__client.params_type.all_fields()], self.__client.params_type) ...
def __ConstructQueryParams(self, query_params, request, global_params)
Construct a dictionary of query parameters for this request.
3.278734
3.219539
1.018386
python_param_names = util.MapParamNames( method_config.path_params, type(request)) params = dict([(param, getattr(request, param, None)) for param in python_param_names]) params = util.MapRequestParams(params, type(request)) return util.ExpandR...
def __ConstructRelativePath(self, method_config, request, relative_path=None)
Determine the relative path for request.
4.391394
4.26283
1.030159
if (http_request.http_method == 'GET' and len(http_request.url) > _MAX_URL_LENGTH): http_request.http_method = 'POST' http_request.headers['x-http-method-override'] = 'GET' http_request.headers[ 'content-type'] = 'application/x-www-for...
def __FinalizeRequest(self, http_request, url_builder)
Make any final general adjustments to the request.
2.527205
2.505237
1.008769
if http_response.status_code not in (http_client.OK, http_client.CREATED, http_client.NO_CONTENT): raise exceptions.HttpError.FromResponse( http_response, method_config=method_config, r...
def __ProcessHttpResponse(self, method_config, http_response, request)
Process the given http response.
3.458881
3.50253
0.987538
# TODO(craigcitro): Make the default a little better here, and # include the apitools version. user_agent = client.user_agent or 'apitools-client/1.0' http_request.headers['user-agent'] = user_agent http_request.headers['accept'] = 'application/json' http_request...
def __SetBaseHeaders(self, http_request, client)
Fill in the basic headers on http_request.
3.796301
3.691957
1.028262
if not method_config.request_field: return request_type = _LoadClass( method_config.request_type_name, self.__client.MESSAGES_MODULE) if method_config.request_field == REQUEST_IS_BODY: body_value = request body_type = request_type ...
def __SetBody(self, http_request, method_config, request, upload)
Fill in the body on http_request.
3.592741
3.483766
1.031281
request_type = _LoadClass( method_config.request_type_name, self.__client.MESSAGES_MODULE) util.Typecheck(request, request_type) request = self.__client.ProcessRequest(method_config, request) http_request = http_wrapper.Request( http_method=method_config...
def PrepareHttpRequest(self, method_config, request, global_params=None, upload=None, upload_config=None, download=None)
Prepares an HTTP request to be sent.
3.435085
3.413005
1.006469
if upload is not None and download is not None: # TODO(craigcitro): This just involves refactoring the logic # below into callbacks that we can pass around; in particular, # the order should be that the upload gets the initial request, # and then passes i...
def _RunMethod(self, method_config, request, global_params=None, upload=None, upload_config=None, download=None)
Call this method with request.
4.33732
4.350792
0.996904
return self.__client.ProcessResponse( method_config, self.__ProcessHttpResponse(method_config, http_response, request))
def ProcessHttpResponse(self, method_config, http_response, request=None)
Convert an HTTP response to the expected message type.
6.50029
6.07608
1.069816
enum_value_descriptor = EnumValueDescriptor() enum_value_descriptor.name = six.text_type(enum_value.name) enum_value_descriptor.number = enum_value.number return enum_value_descriptor
def describe_enum_value(enum_value)
Build descriptor for Enum instance. Args: enum_value: Enum value to provide descriptor for. Returns: Initialized EnumValueDescriptor instance describing the Enum instance.
2.231517
2.539523
0.878715
enum_descriptor = EnumDescriptor() enum_descriptor.name = enum_definition.definition_name().split('.')[-1] values = [] for number in enum_definition.numbers(): value = enum_definition.lookup_by_number(number) values.append(describe_enum_value(value)) if values: enum_de...
def describe_enum(enum_definition)
Build descriptor for Enum class. Args: enum_definition: Enum class to provide descriptor for. Returns: Initialized EnumDescriptor instance describing the Enum class.
3.001738
3.532976
0.849634
field_descriptor = FieldDescriptor() field_descriptor.name = field_definition.name field_descriptor.number = field_definition.number field_descriptor.variant = field_definition.variant if isinstance(field_definition, messages.EnumField): field_descriptor.type_name = field_definition.ty...
def describe_field(field_definition)
Build descriptor for Field instance. Args: field_definition: Field instance to provide descriptor for. Returns: Initialized FieldDescriptor instance describing the Field instance.
2.100514
2.101882
0.999349
message_descriptor = MessageDescriptor() message_descriptor.name = message_definition.definition_name().split( '.')[-1] fields = sorted(message_definition.all_fields(), key=lambda v: v.number) if fields: message_descriptor.fields = [describe_field(field) for fie...
def describe_message(message_definition)
Build descriptor for Message class. Args: message_definition: Message class to provide descriptor for. Returns: Initialized MessageDescriptor instance describing the Message class.
2.0176
2.123562
0.950102
descriptor = FileDescriptor() descriptor.package = util.get_package_for_module(module) if not descriptor.package: descriptor.package = None message_descriptors = [] enum_descriptors = [] # Need to iterate over all top level attributes of the module looking for # message and e...
def describe_file(module)
Build a file from a specified Python module. Args: module: Python module to describe. Returns: Initialized FileDescriptor instance describing the module.
2.988718
3.087894
0.967882
descriptor = FileSet() file_descriptors = [] for module in modules: file_descriptors.append(describe_file(module)) if file_descriptors: descriptor.files = file_descriptors return descriptor
def describe_file_set(modules)
Build a file set from a specified Python modules. Args: modules: Iterable of Python module to describe. Returns: Initialized FileSet instance describing the modules.
3.446715
4.445404
0.775343
if isinstance(value, types.ModuleType): return describe_file(value) elif isinstance(value, messages.Field): return describe_field(value) elif isinstance(value, messages.Enum): return describe_enum_value(value) elif isinstance(value, type): if issubclass(value, messag...
def describe(value)
Describe any value as a descriptor. Helper function for describing any object with an appropriate descriptor object. Args: value: Value to describe as a descriptor. Returns: Descriptor message class if object is describable as a descriptor, else None.
2.157217
2.449238
0.880771
# Attempt to import descriptor as a module. if definition_name.startswith('.'): definition_name = definition_name[1:] if not definition_name.startswith('.'): leaf = definition_name.split('.')[-1] if definition_name: try: module = importer(definition_n...
def import_descriptor_loader(definition_name, importer=__import__)
Find objects by importing modules as needed. A definition loader is a function that resolves a definition name to a descriptor. The import finder resolves definitions to their names by importing modules when necessary. Args: definition_name: Name of definition to find. importer: Impor...
3.631516
3.681502
0.986422
try: return self.__descriptors[definition_name] except KeyError: pass if self.__descriptor_loader: definition = self.__descriptor_loader(definition_name) self.__descriptors[definition_name] = definition return definition ...
def lookup_descriptor(self, definition_name)
Lookup descriptor by name. Get descriptor from library by name. If descriptor is not found will attempt to find via descriptor loader if provided. Args: definition_name: Definition name to find. Returns: Descriptor that describes definition name. Raises: ...
2.741362
2.616538
1.047706
while True: descriptor = self.lookup_descriptor(definition_name) if isinstance(descriptor, FileDescriptor): return descriptor.package else: index = definition_name.rfind('.') if index < 0: return Non...
def lookup_package(self, definition_name)
Determines the package name for any definition. Determine the package that any definition name belongs to. May check parent for package name and will resolve missing descriptors if provided descriptor loader. Args: definition_name: Definition name to find package for.
2.898144
2.974405
0.974361
first_import_error = None for module_name in ['json', 'simplejson']: try: module = __import__(module_name, {}, {}, 'json') if not hasattr(module, 'JSONEncoder'): message = ( 'json library "%s" is not compatible with...
def _load_json_module()
Try to load a valid json module. There are more than one json modules that might be installed. They are mostly compatible with one another but some versions may be different. This function attempts to load various json modules in a preferred order. It does a basic check to guess if a loaded version of...
3.302884
3.183669
1.037446
if isinstance(value, messages.Enum): return str(value) if six.PY3 and isinstance(value, bytes): return value.decode('utf8') if isinstance(value, messages.Message): result = {} for field in value.all_fields(): item = value...
def default(self, value)
Return dictionary instance from a message object. Args: value: Value to get dictionary for. If not encodable, will call superclasses default method.
4.168869
4.205711
0.99124
if isinstance(field, messages.BytesField): if field.repeated: value = [base64.b64encode(byte) for byte in value] else: value = base64.b64encode(value) elif isinstance(field, message_types.DateTimeField): # DateTimeField stores ...
def encode_field(self, field, value)
Encode a python field value to a JSON value. Args: field: A ProtoRPC field instance. value: A python value supported by field. Returns: A JSON serializable value appropriate for field.
2.687272
2.655512
1.01196
message.check_initialized() return json.dumps(message, cls=MessageJSONEncoder, protojson_protocol=self)
def encode_message(self, message)
Encode Message instance to JSON string. Args: Message instance to encode in to JSON string. Returns: String encoding of Message instance in protocol JSON format. Raises: messages.ValidationError if message is not initialized.
17.817205
14.953481
1.191509
encoded_message = six.ensure_str(encoded_message) if not encoded_message.strip(): return message_type() dictionary = json.loads(encoded_message) message = self.__decode_dictionary(message_type, dictionary) message.check_initialized() return message
def decode_message(self, message_type, encoded_message)
Merge JSON structure to Message instance. Args: message_type: Message to decode data to. encoded_message: JSON encoded version of message. Returns: Decoded instance of message_type. Raises: ValueError: If encoded_message is not valid JSON. mes...
3.947392
4.232828
0.932566
if isinstance(value, bool): return messages.Variant.BOOL elif isinstance(value, six.integer_types): return messages.Variant.INT64 elif isinstance(value, float): return messages.Variant.DOUBLE elif isinstance(value, six.string_types): ...
def __find_variant(self, value)
Find the messages.Variant type that describes this value. Args: value: The value whose variant type is being determined. Returns: The messages.Variant value that best describes value's type, or None if it's a type we don't know how to handle.
2.241062
2.086882
1.073881
message = message_type() for key, value in six.iteritems(dictionary): if value is None: try: message.reset(key) except AttributeError: pass # This is an unrecognized field, skip it. continue ...
def __decode_dictionary(self, message_type, dictionary)
Merge dictionary in to message. Args: message: Message to merge dictionary in to. dictionary: Dictionary to extract information from. Dictionary is as parsed from JSON. Nested objects will also be dictionaries.
3.406875
3.512592
0.969903
if isinstance(field, messages.EnumField): try: return field.type(value) except TypeError: raise messages.DecodeError( 'Invalid enum value "%s"' % (value or '')) elif isinstance(field, messages.BytesField): ...
def decode_field(self, field, value)
Decode a JSON value to a python value. Args: field: A ProtoRPC field instance. value: A serialized JSON value. Return: A Python value compatible with field.
2.068672
2.077704
0.995653
printer = self._GetPrinter(out) if self.__init_wildcards_file: printer('', self.__client_info.package) printer('# pylint:disable=wildcard-import') else: printer('') printer() printer('import pkgutil') printe...
def WriteInit(self, out)
Write a simple __init__.py for the generated client.
4.101141
3.696849
1.109361
printer = self._GetPrinter(out) printer('#!/usr/bin/env python') printer('') printer() printer('from pkgutil import extend_path') printer('__path__ = extend_path(__path__, __name__)')
def WriteIntermediateInit(self, out)
Write a simple __init__.py for an intermediate directory.
4.010555
3.403115
1.178495
printer = self._GetPrinter(out) year = datetime.datetime.now().year printer('# Copyright %s Google Inc. All Rights Reserved.' % year) printer('#') printer('# Licensed under the Apache License, Version 2.0 (the' '"License");') printer('# you may no...
def WriteSetupPy(self, out)
Write a setup.py for upload to PyPI.
2.3537
2.33614
1.007517
if 'content-range' in response.info: print('Received %s' % response.info['content-range']) else: print('Received %d bytes' % response.length)
def DownloadProgressPrinter(response, unused_download)
Print download progress based on response.
2.925685
3.047096
0.960155
self.EnsureUninitialized() if self.http is None: self.__http = http or http_wrapper.GetHttp() self.__url = url
def _Initialize(self, http, url)
Initialize this download by setting self.http and self.url. We want the user to be able to override self.http by having set the value in the constructor; in that case, we ignore the provided http. Args: http: An httplib2.Http instance or None. url: The url for this ...
7.408791
8.320272
0.89045
path = os.path.expanduser(filename) if os.path.exists(path) and not overwrite: raise exceptions.InvalidUserInputError( 'File %s exists and overwrite not specified' % path) return cls(open(path, 'wb'), close_stream=True, auto_transfer=auto_t...
def FromFile(cls, filename, overwrite=False, auto_transfer=True, **kwds)
Create a new download object from a filename.
3.232644
3.243759
0.996573
return cls(stream, auto_transfer=auto_transfer, total_size=total_size, **kwds)
def FromStream(cls, stream, auto_transfer=True, total_size=None, **kwds)
Create a new Download object from a stream.
2.528207
2.695419
0.937964
info = json.loads(json_data) missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys()) if missing_keys: raise exceptions.InvalidDataError( 'Invalid serialization data, missing keys: %s' % ( ', '.join(missing_keys))) downlo...
def FromData(cls, stream, json_data, http=None, auto_transfer=None, **kwds)
Create a new Download object from a stream and serialized data.
2.818512
2.559097
1.10137
if 'content-range' in info: _, _, total = info['content-range'].rpartition('/') if total != '*': self.__total_size = int(total) # Note "total_size is None" means we don't know it; if no size # info was returned on our initial range request, that m...
def __SetTotal(self, info)
Sets the total size based off info if possible otherwise 0.
6.897319
6.44642
1.069946
self.EnsureUninitialized() if http is None and client is None: raise exceptions.UserError('Must provide client or http.') http = http or client.http if client is not None: http_request.url = client.FinalizeTransferUrl(http_request.url) url = http_...
def InitializeDownload(self, http_request, http=None, client=None)
Initialize this download by making a request. Args: http_request: The HttpRequest to use to initialize this download. http: The httplib2.Http instance for this request. client: If provided, let this client process the final URL before sending any additional requests....
4.880149
4.552161
1.072051
if end is not None: if start < 0: raise exceptions.TransferInvalidError( 'Cannot have end index with negative start index ' + '[start=%d, end=%d]' % (start, end)) elif start >= self.total_size: raise excepti...
def __NormalizeStartEnd(self, start, end=None)
Normalizes start and end values based on total size.
2.334549
2.253385
1.036019
end_byte = end if start < 0 and not self.total_size: return end_byte if use_chunks: alternate = start + self.chunksize - 1 if end_byte is not None: end_byte = min(end_byte, alternate) else: end_byte = alte...
def __ComputeEndByte(self, start, end=None, use_chunks=True)
Compute the last byte to fetch for this request. This is all based on the HTTP spec for Range and Content-Range. Note that this is potentially confusing in several ways: * the value for the last byte is 0-based, eg "fetch 10 bytes from the beginning" would return 9 here. ...
2.377068
2.600986
0.91391
self.EnsureInitialized() request = http_wrapper.Request(url=self.url) self.__SetRangeHeader(request, start, end=end) if additional_headers is not None: request.headers.update(additional_headers) return http_wrapper.MakeRequest( self.bytes_http, re...
def __GetChunk(self, start, end, additional_headers=None)
Retrieve a chunk, and return the full response.
4.273395
3.948043
1.082408
if response.status_code not in self._ACCEPTABLE_STATUSES: # We distinguish errors that mean we made a mistake in setting # up the transfer versus something we should attempt again. if response.status_code in (http_client.FORBIDDEN, ...
def __ProcessResponse(self, response)
Process response (by updating self and writing to self.stream).
4.30838
4.114381
1.047151
self.EnsureInitialized() progress_end_normalized = False if self.total_size is not None: progress, end_byte = self.__NormalizeStartEnd(start, end) progress_end_normalized = True else: progress = start end_byte = end while (...
def GetRange(self, start, end=None, additional_headers=None, use_chunks=True)
Retrieve a given byte range from this download, inclusive. Range must be of one of these three forms: * 0 <= start, end = None: Fetch from start to the end of the file. * 0 <= start <= end: Fetch the bytes from start to end. * start < 0, end = None: Fetch the last -start bytes of the fi...
4.521364
4.744075
0.953055
self.StreamMedia(callback=callback, finish_callback=finish_callback, additional_headers=additional_headers, use_chunks=True)
def StreamInChunks(self, callback=None, finish_callback=None, additional_headers=None)
Stream the entire download in chunks.
4.117861
3.642694
1.130444
callback = callback or self.progress_callback finish_callback = finish_callback or self.finish_callback self.EnsureInitialized() while True: if self.__initial_response is not None: response = self.__initial_response self.__initial_res...
def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True)
Stream the entire download. Args: callback: (default: None) Callback to call as each chunk is completed. finish_callback: (default: None) Callback to call when the download is complete. additional_headers: (default: None) Additional headers to ...
3.375994
3.486878
0.9682
path = os.path.expanduser(filename) if not os.path.exists(path): raise exceptions.NotFoundError('Could not find file %s' % path) if not mime_type: mime_type, _ = mimetypes.guess_type(path) if mime_type is None: raise exceptions.Invalid...
def FromFile(cls, filename, mime_type=None, auto_transfer=True, gzip_encoded=False, **kwds)
Create a new Upload object from a filename.
2.248543
2.173832
1.034368
if mime_type is None: raise exceptions.InvalidUserInputError( 'No mime_type specified for stream') return cls(stream, mime_type, total_size=total_size, close_stream=False, auto_transfer=auto_transfer, gzip_encoded=gzip_encoded, *...
def FromStream(cls, stream, mime_type, total_size=None, auto_transfer=True, gzip_encoded=False, **kwds)
Create a new Upload object from a stream.
2.658208
2.650285
1.002989
info = json.loads(json_data) missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys()) if missing_keys: raise exceptions.InvalidDataError( 'Invalid serialization data, missing keys: %s' % ( ', '.join(missing_keys))) if 'to...
def FromData(cls, stream, json_data, http, auto_transfer=None, gzip_encoded=False, **kwds)
Create a new Upload of stream from serialized json_data and http.
3.548662
3.393924
1.045592
if upload_config.resumable_path is None: self.strategy = SIMPLE_UPLOAD if self.strategy is not None: return strategy = SIMPLE_UPLOAD if (self.total_size is not None and self.total_size > _RESUMABLE_UPLOAD_THRESHOLD): strategy =...
def __SetDefaultUploadStrategy(self, upload_config, http_request)
Determine and set the default upload strategy for this upload. We generally prefer simple or multipart, unless we're forced to use resumable. This happens when any of (1) the upload is too large, (2) the simple endpoint doesn't support multipart requests and we have metadata, or (3) the...
3.560772
3.121175
1.140843
# Validate total_size vs. max_size if (self.total_size and upload_config.max_size and self.total_size > upload_config.max_size): raise exceptions.InvalidUserInputError( 'Upload too big: %s larger than max size %s' % ( self.total_si...
def ConfigureRequest(self, upload_config, http_request, url_builder)
Configure the request and url for this upload.
4.063945
4.075301
0.997214
http_request.headers['content-type'] = self.mime_type http_request.body = self.stream.read() http_request.loggable_body = '<media body>'
def __ConfigureMediaRequest(self, http_request)
Configure http_request as a simple request for this upload.
5.248802
4.739975
1.107348
# This is a multipart/related upload. msg_root = mime_multipart.MIMEMultipart('related') # msg_root should not write out its own headers setattr(msg_root, '_write_headers', lambda self: None) # attach the body as one part msg = mime_nonmultipart.MIMENonMultipart...
def __ConfigureMultipartRequest(self, http_request)
Configure http_request as a multipart request for this upload.
3.557787
3.579254
0.994002
if self.strategy != RESUMABLE_UPLOAD: return self.EnsureInitialized() refresh_request = http_wrapper.Request( url=self.url, http_method='PUT', headers={'Content-Range': 'bytes */*'}) refresh_response = http_wrapper.MakeRequest( sel...
def RefreshResumableUploadState(self)
Talk to the server and refresh the state of this resumable upload. Returns: Response if the upload is complete.
3.864011
3.87563
0.997002
if self.strategy is None: raise exceptions.UserError( 'No upload strategy set; did you call ConfigureRequest?') if http is None and client is None: raise exceptions.UserError('Must provide client or http.') if self.strategy != RESUMABLE_UPLOAD: ...
def InitializeUpload(self, http_request, http=None, client=None)
Initialize this upload from the given http_request.
4.497727
4.439781
1.013052
if self.strategy != RESUMABLE_UPLOAD: raise exceptions.InvalidUserInputError( 'Cannot stream non-resumable upload') callback = callback or self.progress_callback finish_callback = finish_callback or self.finish_callback # final_response is set if we r...
def __StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True)
Helper function for StreamMedia / StreamInChunks.
3.753491
3.751216
1.000606
return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers, use_chunks=False)
def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None)
Send this resumable upload in a single request. Args: callback: Progress callback function with inputs (http_wrapper.Response, transfer.Upload) finish_callback: Final callback function with inputs (http_wrapper.Response, transfer.Upload) additional_head...
3.656393
4.851691
0.753633
return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers)
def StreamInChunks(self, callback=None, finish_callback=None, additional_headers=None)
Send this (resumable) upload in chunks.
4.441714
4.343122
1.022701
def CheckResponse(response): if response is None: # Caller shouldn't call us if the response is None, # but handle anyway. raise exceptions.RequestError( 'Request to url %s did not return a response.' % ...
def __SendMediaRequest(self, request, end)
Request helper function for SendMediaBody & SendChunk.
4.745858
4.680548
1.013953
self.EnsureInitialized() if self.total_size is None: raise exceptions.TransferInvalidError( 'Total size must be known for SendMediaBody') body_stream = stream_slice.StreamSlice( self.stream, self.total_size - start) request = http_wrapper...
def __SendMediaBody(self, start, additional_headers=None)
Send the entire media stream in a single request.
3.246264
3.175148
1.022398
self.EnsureInitialized() no_log_body = self.total_size is None request = http_wrapper.Request(url=self.url, http_method='PUT') if self.__gzip_encoded: request.headers['Content-Encoding'] = 'gzip' body_stream, read_length, exhausted = compression.CompressS...
def __SendChunk(self, start, additional_headers=None)
Send the specified chunk.
4.277201
4.23301
1.01044
in_read = 0 in_exhausted = False out_stream = StreamingBuffer() with gzip.GzipFile(mode='wb', fileobj=out_stream, compresslevel=compresslevel) as compress_stream: # Read until we've written at least length bytes to the output stream. wh...
def CompressStream(in_stream, length=None, compresslevel=2, chunksize=16777216)
Compresses an input stream into a file-like buffer. This reads from the input stream until either we've stored at least length compressed bytes, or the input stream has been exhausted. This supports streams of unknown size. Args: in_stream: The input stream to read from. length: The t...
2.572556
2.477252
1.038472
if size is None: size = self.__size ret_list = [] while size > 0 and self.__buf: data = self.__buf.popleft() size -= len(data) ret_list.append(data) if size < 0: ret_list[-1], remainder = ret_list[-1][:size], ret_list[-...
def read(self, size=None)
Read at most size bytes from this buffer. Bytes read from this buffer are consumed and are permanently removed. Args: size: If provided, read no more than size bytes from the buffer. Otherwise, this reads the entire buffer. Returns: The bytes read from this buf...
2.232605
2.508444
0.890036
proto_printer.PrintPreamble(package, version, file_descriptor) _PrintEnums(proto_printer, file_descriptor.enum_types) _PrintMessages(proto_printer, file_descriptor.message_types) custom_json_mappings = _FetchCustomMappings(file_descriptor.enum_types) custom_json_mappings.extend( _FetchC...
def _WriteFile(file_descriptor, package, version, proto_printer)
Write the given extended file descriptor to the printer.
2.693368
2.751845
0.97875
_WriteFile(file_descriptor, package, version, _Proto2Printer(printer))
def WriteMessagesFile(file_descriptor, package, version, printer)
Write the given extended file descriptor to out as a message file.
17.188141
18.392401
0.934524
_WriteFile(file_descriptor, package, version, _ProtoRpcPrinter(printer))
def WritePythonFile(file_descriptor, package, version, printer)
Write the given extended file descriptor to out.
16.300524
18.126663
0.899257
custom_mappings = [] for descriptor in descriptor_ls: if isinstance(descriptor, ExtendedEnumDescriptor): custom_mappings.extend( _FormatCustomJsonMapping('Enum', m, descriptor) for m in descriptor.enum_mappings) elif isinstance(descriptor, Extende...
def _FetchCustomMappings(descriptor_ls)
Find and return all custom mappings for descriptors in descriptor_ls.
2.63839
2.55498
1.032646
enum_types = sorted(enum_types, key=operator.attrgetter('name')) for enum_type in enum_types: proto_printer.PrintEnum(enum_type)
def _PrintEnums(proto_printer, enum_types)
Print all enums to the given proto_printer.
2.280117
2.089643
1.091151
description = message_type.description or '%s message type.' % ( message_type.name) width = self.__printer.CalculateWidth() - 3 for line in textwrap.wrap(description, width): self.__printer('// %s', line) PrintIndentedDescriptions(self.__printer, message_...
def __PrintMessageCommentLines(self, message_type)
Print the description of this message.
3.414423
3.125353
1.092492
google_imports = [x for x in imports if 'google' in x] other_imports = [x for x in imports if 'google' not in x] if other_imports: for import_ in sorted(other_imports): self.__printer(import_) self.__printer() # Note: If we ever were going...
def __PrintAdditionalImports(self, imports)
Print additional imports needed for protorpc.
3.618151
3.492085
1.0361
description = message_type.description or '%s message type.' % ( message_type.name) short_description = ( _EmptyMessage(message_type) and len(description) < (self.__printer.CalculateWidth() - 6)) with self.__printer.CommentContext(): if sh...
def __PrintMessageDocstringLines(self, message_type)
Print the docstring for this message.
9.736904
9.406953
1.035075
def positional_decorator(wrapped): @functools.wraps(wrapped) def positional_wrapper(*args, **kwargs): if len(args) > max_positional_args: plural_s = '' if max_positional_args != 1: plural_s = 's' raise Type...
def positional(max_positional_args)
A decorator that declares only the first N arguments may be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after * must be a k...
2.169315
2.244575
0.96647
if isinstance(module, six.string_types): try: module = sys.modules[module] except KeyError: return None try: return six.text_type(module.package) except AttributeError: if module.__name__ == '__main__': try: file_name ...
def get_package_for_module(module)
Get package name for a module. Helper calculates the package name of a module. Args: module: Module to get name for. If module is a string, try to find module in sys.modules. Returns: If module contains 'package' attribute, uses that as package name. Else, if module is not the ...
2.206026
2.086954
1.057056