_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q36100
ID3Tags._copy
train
def _copy(self): """Creates a shallow copy of all tags""" items = self.items() subs = {} for f in (self.getall("CHAP") + self.getall("CTOC")): subs[f.HashKey] = f.sub_frames._copy() return (items, subs)
python
{ "resource": "" }
q36101
SignalHandler.block
train
def block(self): """While this context manager is active any signals for aborting the process will be queued and exit the program once the context is left. """ self._nosig = True yield self._nosig = False if self._interrupted: raise SystemExit...
python
{ "resource": "" }
q36102
is_valid_key
train
def is_valid_key(key): """Return true if a string is a valid Vorbis comment key. Valid Vorbis comment keys are printable ASCII between 0x20 (space) and 0x7D ('}'), excluding '='. Takes str/unicode in Python 2, unicode in Python 3 """ if PY3 and isinstance(key, bytes): raise TypeError(...
python
{ "resource": "" }
q36103
VComment.load
train
def load(self, fileobj, errors='replace', framing=True): """Parse a Vorbis comment from a file-like object. Arguments: errors (str): 'strict', 'replace', or 'ignore'. This affects Unicode decoding and how other malformed content is interpreted. fr...
python
{ "resource": "" }
q36104
VComment.validate
train
def validate(self): """Validate keys and values. Check to make sure every key used is a valid Vorbis key, and that every value used is a valid Unicode or UTF-8 string. If any invalid keys or values are found, a ValueError is raised. In Python 3 all keys and values have to be a ...
python
{ "resource": "" }
q36105
ParseID3v1
train
def ParseID3v1(data, v2_version=4, known_frames=None): """Parse an ID3v1 tag, returning a list of ID3v2 frames Returns a {frame_name: frame} dict or None. v2_version: Decides whether ID3v2.3 or ID3v2.4 tags should be returned. Must be 3 or 4. known_frames (Dict[`mutagen.text`, `Frame`...
python
{ "resource": "" }
q36106
MakeID3v1
train
def MakeID3v1(id3): """Return an ID3v1.1 tag string from a dict of ID3v2.4 frames.""" v1 = {} for v2id, name in {"TIT2": "title", "TPE1": "artist", "TALB": "album"}.items(): if v2id in id3: text = id3[v2id].text[0].encode('latin1', 'replace')[:30] else: ...
python
{ "resource": "" }
q36107
OggVorbisInfo._post_tags
train
def _post_tags(self, fileobj): """Raises ogg.error""" page = OggPage.find_last(fileobj, self.serial, finishing=True) if page is None: raise OggVorbisHeaderError self.length = page.position / float(self.sample_rate)
python
{ "resource": "" }
q36108
IFFChunk.write
train
def write(self, data): """Write the chunk data""" if len(data) > self.data_size: raise ValueError self.__fileobj.seek(self.data_offset) self.__fileobj.write(data)
python
{ "resource": "" }
q36109
IFFChunk.resize
train
def resize(self, new_data_size): """Resize the file and update the chunk sizes""" resize_bytes( self.__fileobj, self.data_size, new_data_size, self.data_offset) self._update_size(new_data_size)
python
{ "resource": "" }
q36110
IFFFile.insert_chunk
train
def insert_chunk(self, id_): """Insert a new chunk at the end of the IFF file""" assert_valid_chunk_id(id_) self.__fileobj.seek(self.__next_offset) self.__fileobj.write(pack('>4si', id_.ljust(4).encode('ascii'), 0)) self.__fileobj.seek(self.__next_offset) chunk = IFFChu...
python
{ "resource": "" }
q36111
_IFFID3.save
train
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None): """Save ID3v2 data to the AIFF file""" fileobj = filething.fileobj iff_file = IFFFile(fileobj) if u'ID3' not in iff_file: iff_file.insert_chunk(u'ID3') chunk = iff_file[u'ID3'] try: ...
python
{ "resource": "" }
q36112
AIFF.load
train
def load(self, filething, **kwargs): """Load stream and tag information from a file.""" fileobj = filething.fileobj try: self.tags = _IFFID3(fileobj, **kwargs) except ID3NoHeaderError: self.tags = None except ID3Error as e: raise error(e) ...
python
{ "resource": "" }
q36113
Engine.is_valid_image
train
def is_valid_image(self, raw_data): ''' Wand library makes sure when opening any image that is fine, when the image is corrupted raises an exception. ''' try: Image(blob=raw_data) return True except (exceptions.CorruptImageError, exceptions.Missin...
python
{ "resource": "" }
q36114
parse_cropbox
train
def parse_cropbox(cropbox): """ Returns x, y, x2, y2 tuple for cropping. """ if isinstance(cropbox, six.text_type): return tuple([int(x.strip()) for x in cropbox.split(',')]) else: return tuple(cropbox)
python
{ "resource": "" }
q36115
Engine.get_image
train
def get_image(self, source): """ Returns the backend image objects from a ImageFile instance """ with NamedTemporaryFile(mode='wb', delete=False) as fp: fp.write(source.read()) return {'source': fp.name, 'options': OrderedDict(), 'size': None}
python
{ "resource": "" }
q36116
Engine.is_valid_image
train
def is_valid_image(self, raw_data): """ This is not very good for imagemagick because it will say anything is valid that it can use as input. """ with NamedTemporaryFile(mode='wb') as fp: fp.write(raw_data) fp.flush() args = settings.THUMBNAIL_...
python
{ "resource": "" }
q36117
Engine._crop
train
def _crop(self, image, width, height, x_offset, y_offset): """ Crops the image """ image['options']['crop'] = '%sx%s+%s+%s' % (width, height, x_offset, y_offset) image['size'] = (width, height) # update image size return image
python
{ "resource": "" }
q36118
Engine._scale
train
def _scale(self, image, width, height): """ Does the resizing of the image """ image['options']['scale'] = '%sx%s!' % (width, height) image['size'] = (width, height) # update image size return image
python
{ "resource": "" }
q36119
Engine._padding
train
def _padding(self, image, geometry, options): """ Pads the image """ # The order is important. The gravity option should come before extent. image['options']['background'] = options.get('padding_color') image['options']['gravity'] = 'center' image['options']['exte...
python
{ "resource": "" }
q36120
tokey
train
def tokey(*args): """ Computes a unique key from arguments given. """ salt = '||'.join([force_text(arg) for arg in args]) hash_ = hashlib.md5(encode(salt)) return hash_.hexdigest()
python
{ "resource": "" }
q36121
get_module_class
train
def get_module_class(class_path): """ imports and returns module class from ``path.to.module.Class`` argument """ mod_name, cls_name = class_path.rsplit('.', 1) try: mod = import_module(mod_name) except ImportError as e: raise ImproperlyConfigured(('Error importing module %s...
python
{ "resource": "" }
q36122
get_thumbnail
train
def get_thumbnail(file_, geometry_string, **options): """ A shortcut for the Backend ``get_thumbnail`` method """ return default.backend.get_thumbnail(file_, geometry_string, **options)
python
{ "resource": "" }
q36123
safe_filter
train
def safe_filter(error_output=''): """ A safe filter decorator only raising errors when ``THUMBNAIL_DEBUG`` is ``True`` otherwise returning ``error_output``. """ def inner(f): @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) ...
python
{ "resource": "" }
q36124
resolution
train
def resolution(file_, resolution_string): """ A filter to return the URL for the provided resolution of the thumbnail. """ if sorl_settings.THUMBNAIL_DUMMY: dummy_source = sorl_settings.THUMBNAIL_DUMMY_SOURCE source = dummy_source.replace('%(width)s', '(?P<width>[0-9]+)') source ...
python
{ "resource": "" }
q36125
is_portrait
train
def is_portrait(file_): """ A very handy filter to determine if an image is portrait or landscape. """ if sorl_settings.THUMBNAIL_DUMMY: return sorl_settings.THUMBNAIL_DUMMY_RATIO < 1 if not file_: return False image_file = default.kvstore.get_or_set(ImageFile(file_)) return ...
python
{ "resource": "" }
q36126
margin
train
def margin(file_, geometry_string): """ Returns the calculated margin for an image and geometry """ if not file_ or (sorl_settings.THUMBNAIL_DUMMY or isinstance(file_, DummyImageFile)): return 'auto' margin = [0, 0, 0, 0] image_file = default.kvstore.get_or_set(ImageFile(file_)) ...
python
{ "resource": "" }
q36127
text_filter
train
def text_filter(regex_base, value): """ Helper method to regex replace images with captions in different markups """ regex = regex_base % { 're_cap': r'[a-zA-Z0-9\.\,:;/_ \(\)\-\!\?"]+', 're_img': r'[a-zA-Z0-9\.:/_\-\% ]+' } images = re.findall(regex, value) for i in images:...
python
{ "resource": "" }
q36128
ImageField.delete_file
train
def delete_file(self, instance, sender, **kwargs): """ Adds deletion of thumbnails and key value store references to the parent class implementation. Only called in Django < 1.2.5 """ file_ = getattr(instance, self.attname) # If no other object of this type references th...
python
{ "resource": "" }
q36129
Engine.get_image_size
train
def get_image_size(self, image): """ Returns the image width and height as a tuple """ if image['size'] is None: args = settings.THUMBNAIL_VIPSHEADER.split(' ') args.append(image['source']) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subp...
python
{ "resource": "" }
q36130
ThumbnailBackend.get_thumbnail
train
def get_thumbnail(self, file_, geometry_string, **options): """ Returns thumbnail as an ImageFile instance for file with geometry and options given. First it will try to get it from the key value store, secondly it will create it. """ logger.debug('Getting thumbnail for f...
python
{ "resource": "" }
q36131
ThumbnailBackend.delete
train
def delete(self, file_, delete_file=True): """ Deletes file_ references in Key Value store and optionally the file_ it self. """ image_file = ImageFile(file_) if delete_file: image_file.delete() default.kvstore.delete(image_file)
python
{ "resource": "" }
q36132
ThumbnailBackend._create_thumbnail
train
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail): """ Creates the thumbnail by using default.engine """ logger.debug('Creating thumbnail file [%s] at [%s] with [%s]', thumbnail.name, geometry_string, options) ...
python
{ "resource": "" }
q36133
ThumbnailBackend._create_alternative_resolutions
train
def _create_alternative_resolutions(self, source_image, geometry_string, options, name): """ Creates the thumbnail by using default.engine with multiple output sizes. Appends @<ratio>x to the file name. """ ratio = default.engine.get_image...
python
{ "resource": "" }
q36134
ThumbnailBackend._get_thumbnail_filename
train
def _get_thumbnail_filename(self, source, geometry_string, options): """ Computes the destination filename. """ key = tokey(source.key, geometry_string, serialize(options)) # make some subdirs path = '%s/%s/%s' % (key[:2], key[2:4], key) return '%s%s.%s' % (settin...
python
{ "resource": "" }
q36135
round_corner
train
def round_corner(radius, fill): """Draw a round corner""" corner = Image.new('L', (radius, radius), 0) # (0, 0, 0, 0)) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill) return corner
python
{ "resource": "" }
q36136
round_rectangle
train
def round_rectangle(size, radius, fill): """Draw a rounded rectangle""" width, height = size rectangle = Image.new('L', size, 255) # fill corner = round_corner(radius, 255) # fill rectangle.paste(corner, (0, 0)) rectangle.paste(corner.rotate(90), (0, height - radius)) # Ro...
python
{ "resource": "" }
q36137
Engine._get_image_entropy
train
def _get_image_entropy(self, image): """calculate the entropy of an image""" hist = image.histogram() hist_size = sum(hist) hist = [float(h) / hist_size for h in hist] return -sum([p * math.log(p, 2) for p in hist if p != 0])
python
{ "resource": "" }
q36138
EngineBase.create
train
def create(self, image, geometry, options): """ Processing conductor, returns the thumbnail as an image engine instance """ image = self.cropbox(image, geometry, options) image = self.orientation(image, geometry, options) image = self.colorspace(image, geometry, options) ...
python
{ "resource": "" }
q36139
EngineBase.cropbox
train
def cropbox(self, image, geometry, options): """ Wrapper for ``_cropbox`` """ cropbox = options['cropbox'] if not cropbox: return image x, y, x2, y2 = parse_cropbox(cropbox) return self._cropbox(image, x, y, x2, y2)
python
{ "resource": "" }
q36140
EngineBase.orientation
train
def orientation(self, image, geometry, options): """ Wrapper for ``_orientation`` """ if options.get('orientation', settings.THUMBNAIL_ORIENTATION): return self._orientation(image) self.reoriented = True return image
python
{ "resource": "" }
q36141
EngineBase.colorspace
train
def colorspace(self, image, geometry, options): """ Wrapper for ``_colorspace`` """ colorspace = options['colorspace'] return self._colorspace(image, colorspace)
python
{ "resource": "" }
q36142
EngineBase.scale
train
def scale(self, image, geometry, options): """ Wrapper for ``_scale`` """ upscale = options['upscale'] x_image, y_image = map(float, self.get_image_size(image)) factor = self._calculate_scaling_factor(x_image, y_image, geometry, options) if factor < 1 or upscale:...
python
{ "resource": "" }
q36143
EngineBase.crop
train
def crop(self, image, geometry, options): """ Wrapper for ``_crop`` """ crop = options['crop'] x_image, y_image = self.get_image_size(image) if not crop or crop == 'noop': return image elif crop == 'smart': # Smart cropping is suitably dif...
python
{ "resource": "" }
q36144
EngineBase.rounded
train
def rounded(self, image, geometry, options): """ Wrapper for ``_rounded`` """ r = options['rounded'] if not r: return image return self._rounded(image, int(r))
python
{ "resource": "" }
q36145
EngineBase.blur
train
def blur(self, image, geometry, options): """ Wrapper for ``_blur`` """ if options.get('blur'): return self._blur(image, int(options.get('blur'))) return image
python
{ "resource": "" }
q36146
EngineBase.padding
train
def padding(self, image, geometry, options): """ Wrapper for ``_padding`` """ if options.get('padding') and self.get_image_size(image) != geometry: return self._padding(image, geometry, options) return image
python
{ "resource": "" }
q36147
EngineBase.get_image_ratio
train
def get_image_ratio(self, image, options): """ Calculates the image ratio. If cropbox option is used, the ratio may have changed. """ cropbox = options['cropbox'] if cropbox: x, y, x2, y2 = parse_cropbox(cropbox) x = x2 - x y = y2 - y ...
python
{ "resource": "" }
q36148
KVStoreBase.set
train
def set(self, image_file, source=None): """ Updates store for the `image_file`. Makes sure the `image_file` has a size set. """ image_file.set_size() # make sure its got a size self._set(image_file.key, image_file) if source is not None: if not self.g...
python
{ "resource": "" }
q36149
KVStoreBase.delete
train
def delete(self, image_file, delete_thumbnails=True): """ Deletes the reference to the ``image_file`` and deletes the references to thumbnails as well as thumbnail files if ``delete_thumbnails`` is `True``. Does not delete the ``image_file`` is self. """ if delete_thumbna...
python
{ "resource": "" }
q36150
KVStoreBase.delete_thumbnails
train
def delete_thumbnails(self, image_file): """ Deletes references to thumbnails as well as thumbnail ``image_files``. """ thumbnail_keys = self._get(image_file.key, identity='thumbnails') if thumbnail_keys: # Delete all thumbnail keys from store and delete the ...
python
{ "resource": "" }
q36151
KVStoreBase.clear
train
def clear(self): """ Brutely clears the key value store for keys with THUMBNAIL_KEY_PREFIX prefix. Use this in emergency situations. Normally you would probably want to use the ``cleanup`` method instead. """ all_keys = self._find_keys_raw(settings.THUMBNAIL_KEY_PREFIX) ...
python
{ "resource": "" }
q36152
KVStoreBase._get
train
def _get(self, key, identity='image'): """ Deserializing, prefix wrapper for _get_raw """ value = self._get_raw(add_prefix(key, identity)) if not value: return None if identity == 'image': return deserialize_image_file(value) return dese...
python
{ "resource": "" }
q36153
KVStoreBase._set
train
def _set(self, key, value, identity='image'): """ Serializing, prefix wrapper for _set_raw """ if identity == 'image': s = serialize_image_file(value) else: s = serialize(value) self._set_raw(add_prefix(key, identity), s)
python
{ "resource": "" }
q36154
KVStoreBase._find_keys
train
def _find_keys(self, identity='image'): """ Finds and returns all keys for identity, """ prefix = add_prefix('', identity) raw_keys = self._find_keys_raw(prefix) or [] for raw_key in raw_keys: yield del_prefix(raw_key)
python
{ "resource": "" }
q36155
dtw
train
def dtw(x, y, dist=None): ''' return the distance between 2 time series without approximation Parameters ---------- x : array_like input array 1 y : array_like input array 2 dist : function or int The method for calculating the distance be...
python
{ "resource": "" }
q36156
get_next_url
train
def get_next_url(request, redirect_field_name): """Retrieves next url from request Note: This verifies that the url is safe before returning it. If the url is not safe, this returns None. :arg HttpRequest request: the http request :arg str redirect_field_name: the name of the field holding the nex...
python
{ "resource": "" }
q36157
OIDCAuthenticationCallbackView.get
train
def get(self, request): """Callback handler for OIDC authorization code flow""" nonce = request.session.get('oidc_nonce') if nonce: # Make sure that nonce is not used twice del request.session['oidc_nonce'] if request.GET.get('error'): # Ouch! Someth...
python
{ "resource": "" }
q36158
OIDCAuthenticationRequestView.get
train
def get(self, request): """OIDC client authentication initialization HTTP endpoint""" state = get_random_string(self.get_settings('OIDC_STATE_SIZE', 32)) redirect_field_name = self.get_settings('OIDC_REDIRECT_FIELD_NAME', 'next') reverse_url = self.get_settings('OIDC_AUTHENTICATION_CALLB...
python
{ "resource": "" }
q36159
get_oidc_backend
train
def get_oidc_backend(): """ Get the Django auth backend that uses OIDC. """ # allow the user to force which back backend to use. this is mostly # convenient if you want to use OIDC with DRF but don't want to configure # OIDC for the "normal" Django auth. backend_setting = import_from_settin...
python
{ "resource": "" }
q36160
OIDCAuthentication.get_access_token
train
def get_access_token(self, request): """ Get the access token based on a request. Returns None if no authentication details were provided. Raises AuthenticationFailed if the token is incorrect. """ header = authentication.get_authorization_header(request) if not ...
python
{ "resource": "" }
q36161
import_from_settings
train
def import_from_settings(attr, *args): """ Load an attribute from the django settings. :raises: ImproperlyConfigured """ try: if args: return getattr(settings, attr, args[0]) return getattr(settings, attr) except AttributeError: raise ImproperlyConfig...
python
{ "resource": "" }
q36162
default_username_algo
train
def default_username_algo(email): """Generate username for the Django user. :arg str/unicode email: the email address to use to generate a username :returns: str/unicode """ # bluntly stolen from django-browserid # store the username as a base64 encoded sha224 of the email address # this ...
python
{ "resource": "" }
q36163
OIDCAuthenticationBackend.filter_users_by_claims
train
def filter_users_by_claims(self, claims): """Return all users matching the specified email.""" email = claims.get('email') if not email: return self.UserModel.objects.none() return self.UserModel.objects.filter(email__iexact=email)
python
{ "resource": "" }
q36164
OIDCAuthenticationBackend.verify_claims
train
def verify_claims(self, claims): """Verify the provided claims to decide if authentication should be allowed.""" # Verify claims required by default configuration scopes = self.get_settings('OIDC_RP_SCOPES', 'openid email') if 'email' in scopes.split(): return 'email' in cla...
python
{ "resource": "" }
q36165
OIDCAuthenticationBackend.create_user
train
def create_user(self, claims): """Return object for a newly created user account.""" email = claims.get('email') username = self.get_username(claims) return self.UserModel.objects.create_user(username, email)
python
{ "resource": "" }
q36166
OIDCAuthenticationBackend.get_username
train
def get_username(self, claims): """Generate username based on claims.""" # bluntly stolen from django-browserid # https://github.com/mozilla/django-browserid/blob/master/django_browserid/auth.py username_algo = self.get_settings('OIDC_USERNAME_ALGO', None) if username_algo: ...
python
{ "resource": "" }
q36167
OIDCAuthenticationBackend._verify_jws
train
def _verify_jws(self, payload, key): """Verify the given JWS payload with the given key and return the payload""" jws = JWS.from_compact(payload) try: alg = jws.signature.combined.alg.name except KeyError: msg = 'No alg value found in header' raise Su...
python
{ "resource": "" }
q36168
OIDCAuthenticationBackend.retrieve_matching_jwk
train
def retrieve_matching_jwk(self, token): """Get the signing key by exploring the JWKS endpoint of the OP.""" response_jwks = requests.get( self.OIDC_OP_JWKS_ENDPOINT, verify=self.get_settings('OIDC_VERIFY_SSL', True) ) response_jwks.raise_for_status() jwks ...
python
{ "resource": "" }
q36169
OIDCAuthenticationBackend.get_payload_data
train
def get_payload_data(self, token, key): """Helper method to get the payload of the JWT token.""" if self.get_settings('OIDC_ALLOW_UNSECURED_JWT', False): header, payload_data, signature = token.split(b'.') header = json.loads(smart_text(b64decode(header))) # If confi...
python
{ "resource": "" }
q36170
OIDCAuthenticationBackend.verify_token
train
def verify_token(self, token, **kwargs): """Validate the token signature.""" nonce = kwargs.get('nonce') token = force_bytes(token) if self.OIDC_RP_SIGN_ALGO.startswith('RS'): if self.OIDC_RP_IDP_SIGN_KEY is not None: key = self.OIDC_RP_IDP_SIGN_KEY ...
python
{ "resource": "" }
q36171
OIDCAuthenticationBackend.get_token
train
def get_token(self, payload): """Return token object as a dictionary.""" auth = None if self.get_settings('OIDC_TOKEN_USE_BASIC_AUTH', False): # When Basic auth is defined, create the Auth Header and remove secret from payload. user = payload.get('client_id') ...
python
{ "resource": "" }
q36172
OIDCAuthenticationBackend.get_userinfo
train
def get_userinfo(self, access_token, id_token, payload): """Return user details dictionary. The id_token and payload are not used in the default implementation, but may be used when overriding this method""" user_response = requests.get( self.OIDC_OP_USER_ENDPOINT, heade...
python
{ "resource": "" }
q36173
OIDCAuthenticationBackend.authenticate
train
def authenticate(self, request, **kwargs): """Authenticates a user based on the OIDC code flow.""" self.request = request if not self.request: return None state = self.request.GET.get('state') code = self.request.GET.get('code') nonce = kwargs.pop('nonce', N...
python
{ "resource": "" }
q36174
OIDCAuthenticationBackend.store_tokens
train
def store_tokens(self, access_token, id_token): """Store OIDC tokens.""" session = self.request.session if self.get_settings('OIDC_STORE_ACCESS_TOKEN', False): session['oidc_access_token'] = access_token if self.get_settings('OIDC_STORE_ID_TOKEN', False): sessio...
python
{ "resource": "" }
q36175
OIDCAuthenticationBackend.get_or_create_user
train
def get_or_create_user(self, access_token, id_token, payload): """Returns a User instance if 1 user is found. Creates a user if not found and configured to do so. Returns nothing if multiple users are matched.""" user_info = self.get_userinfo(access_token, id_token, payload) email = us...
python
{ "resource": "" }
q36176
SessionRefresh.exempt_urls
train
def exempt_urls(self): """Generate and return a set of url paths to exempt from SessionRefresh This takes the value of ``settings.OIDC_EXEMPT_URLS`` and appends three urls that mozilla-django-oidc uses. These values can be view names or absolute url paths. :returns: list of url...
python
{ "resource": "" }
q36177
SessionRefresh.is_refreshable_url
train
def is_refreshable_url(self, request): """Takes a request and returns whether it triggers a refresh examination :arg HttpRequest request: :returns: boolean """ # Do not attempt to refresh the session if the OIDC backend is not used backend_session = request.session.get...
python
{ "resource": "" }
q36178
ReverseFileSearcher._read
train
def _read(self): """ Reads and returns a buffer reversely from current file-pointer position. :rtype : str """ filepos = self._fp.tell() if filepos < 1: return "" destpos = max(filepos - self._chunk_size, 0) self._fp.seek(destpos) buf ...
python
{ "resource": "" }
q36179
ReverseFileSearcher.find
train
def find(self): """ Returns the position of the first occurence of needle. If the needle was not found, -1 is returned. :rtype : int """ lastbuf = "" while 0 < self._fp.tell(): buf = self._read() bufpos = (buf + lastbuf).rfind(self._needle...
python
{ "resource": "" }
q36180
LogReader.search
train
def search(self, text): """ Find text in log file from current position returns a tuple containing: absolute position, position in result buffer, result buffer (the actual file contents) """ key = hash(text) searcher = self._searchers....
python
{ "resource": "" }
q36181
get_interface_addresses
train
def get_interface_addresses(): """ Get addresses of available network interfaces. See netifaces on pypi for details. Returns a list of dicts """ addresses = [] ifaces = netifaces.interfaces() for iface in ifaces: addrs = netifaces.ifaddresses(iface) families = addrs.key...
python
{ "resource": "" }
q36182
NetIOCounters._get_net_io_counters
train
def _get_net_io_counters(self): """ Fetch io counters from psutil and transform it to dicts with the additional attributes defaulted """ counters = psutil.net_io_counters(pernic=self.pernic) res = {} for name, io in counters.iteritems(): res[name] = i...
python
{ "resource": "" }
q36183
URL.build
train
def build( cls, *, scheme="", user="", password=None, host="", port=None, path="", query=None, query_string="", fragment="", encoded=False ): """Creates and returns a new URL""" if not host and scheme: ...
python
{ "resource": "" }
q36184
URL.is_default_port
train
def is_default_port(self): """A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. """ if self.port is None: return False default = DEFAULT_PORTS.get(self....
python
{ "resource": "" }
q36185
URL.origin
train
def origin(self): """Return an URL with scheme, host and port parts only. user, password, path, query and fragment are removed. """ # TODO: add a keyword-only option for keeping user/pass maybe? if not self.is_absolute(): raise ValueError("URL should be absolute") ...
python
{ "resource": "" }
q36186
URL.relative
train
def relative(self): """Return a relative part of the URL. scheme, user, password, host and port are removed. """ if not self.is_absolute(): raise ValueError("URL should be absolute") val = self._val._replace(scheme="", netloc="") return URL(val, encoded=True...
python
{ "resource": "" }
q36187
URL.host
train
def host(self): """Decoded host part of URL. None for relative URLs. """ raw = self.raw_host if raw is None: return None if "%" in raw: # Hack for scoped IPv6 addresses like # fe80::2%Проверка # presence of '%' sign means ...
python
{ "resource": "" }
q36188
URL.port
train
def port(self): """Port part of URL, with scheme-based fallback. None for relative URLs or URLs without explicit port and scheme without default port substitution. """ return self._val.port or DEFAULT_PORTS.get(self._val.scheme)
python
{ "resource": "" }
q36189
URL.raw_path
train
def raw_path(self): """Encoded path of URL. / for absolute URLs without path part. """ ret = self._val.path if not ret and self.is_absolute(): ret = "/" return ret
python
{ "resource": "" }
q36190
URL.query
train
def query(self): """A MultiDictProxy representing parsed query parameters in decoded representation. Empty value if URL has no query part. """ ret = MultiDict(parse_qsl(self.raw_query_string, keep_blank_values=True)) return MultiDictProxy(ret)
python
{ "resource": "" }
q36191
URL.path_qs
train
def path_qs(self): """Decoded path of URL with query.""" if not self.query_string: return self.path return "{}?{}".format(self.path, self.query_string)
python
{ "resource": "" }
q36192
URL.raw_path_qs
train
def raw_path_qs(self): """Encoded path of URL with query.""" if not self.raw_query_string: return self.raw_path return "{}?{}".format(self.raw_path, self.raw_query_string)
python
{ "resource": "" }
q36193
URL.parent
train
def parent(self): """A new URL with last part of path removed and cleaned up query and fragment. """ path = self.raw_path if not path or path == "/": if self.raw_fragment or self.raw_query_string: return URL(self._val._replace(query="", fragment=""), ...
python
{ "resource": "" }
q36194
URL.raw_name
train
def raw_name(self): """The last part of raw_parts.""" parts = self.raw_parts if self.is_absolute(): parts = parts[1:] if not parts: return "" else: return parts[-1] else: return parts[-1]
python
{ "resource": "" }
q36195
URL._validate_authority_uri_abs_path
train
def _validate_authority_uri_abs_path(host, path): """Ensure that path in URL with authority starts with a leading slash. Raise ValueError if not. """ if len(host) > 0 and len(path) > 0 and not path.startswith("/"): raise ValueError( "Path in a URL with author...
python
{ "resource": "" }
q36196
URL.with_scheme
train
def with_scheme(self, scheme): """Return a new URL with scheme replaced.""" # N.B. doesn't cleanup query/fragment if not isinstance(scheme, str): raise TypeError("Invalid scheme type") if not self.is_absolute(): raise ValueError("scheme replacement is not allowed ...
python
{ "resource": "" }
q36197
URL.with_user
train
def with_user(self, user): """Return a new URL with user replaced. Autoencode user if needed. Clear user/password if user is None. """ # N.B. doesn't cleanup query/fragment val = self._val if user is None: password = None elif isinstance(use...
python
{ "resource": "" }
q36198
URL.with_host
train
def with_host(self, host): """Return a new URL with host replaced. Autoencode host if needed. Changing host for relative URLs is not allowed, use .join() instead. """ # N.B. doesn't cleanup query/fragment if not isinstance(host, str): raise TypeErro...
python
{ "resource": "" }
q36199
URL.with_port
train
def with_port(self, port): """Return a new URL with port replaced. Clear port to default if None is passed. """ # N.B. doesn't cleanup query/fragment if port is not None and not isinstance(port, int): raise TypeError("port should be int or None, got {}".format(type(...
python
{ "resource": "" }