id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,300
quodlibet/mutagen
mutagen/apev2.py
APEv2.__parse_tag
def __parse_tag(self, tag, count): """Raises IOError and APEBadItemError""" fileobj = cBytesIO(tag) for i in xrange(count): tag_data = fileobj.read(8) # someone writes wrong item counts if not tag_data: break if len(tag_data) != 8: raise error size = cdata.uint32_le(tag_data[:4]) flags = cdata.uint32_le(tag_data[4:8]) # Bits 1 and 2 bits are flags, 0-3 # Bit 0 is read/write flag, ignored kind = (flags & 6) >> 1 if kind == 3: raise APEBadItemError("value type must be 0, 1, or 2") key = value = fileobj.read(1) if not key: raise APEBadItemError while key[-1:] != b'\x00' and value: value = fileobj.read(1) if not value: raise APEBadItemError key += value if key[-1:] == b"\x00": key = key[:-1] if PY3: try: key = key.decode("ascii") except UnicodeError as err: reraise(APEBadItemError, err, sys.exc_info()[2]) value = fileobj.read(size) if len(value) != size: raise APEBadItemError value = _get_value_type(kind)._new(value) self[key] = value
python
def __parse_tag(self, tag, count): fileobj = cBytesIO(tag) for i in xrange(count): tag_data = fileobj.read(8) # someone writes wrong item counts if not tag_data: break if len(tag_data) != 8: raise error size = cdata.uint32_le(tag_data[:4]) flags = cdata.uint32_le(tag_data[4:8]) # Bits 1 and 2 bits are flags, 0-3 # Bit 0 is read/write flag, ignored kind = (flags & 6) >> 1 if kind == 3: raise APEBadItemError("value type must be 0, 1, or 2") key = value = fileobj.read(1) if not key: raise APEBadItemError while key[-1:] != b'\x00' and value: value = fileobj.read(1) if not value: raise APEBadItemError key += value if key[-1:] == b"\x00": key = key[:-1] if PY3: try: key = key.decode("ascii") except UnicodeError as err: reraise(APEBadItemError, err, sys.exc_info()[2]) value = fileobj.read(size) if len(value) != size: raise APEBadItemError value = _get_value_type(kind)._new(value) self[key] = value
[ "def", "__parse_tag", "(", "self", ",", "tag", ",", "count", ")", ":", "fileobj", "=", "cBytesIO", "(", "tag", ")", "for", "i", "in", "xrange", "(", "count", ")", ":", "tag_data", "=", "fileobj", ".", "read", "(", "8", ")", "# someone writes wrong item...
Raises IOError and APEBadItemError
[ "Raises", "IOError", "and", "APEBadItemError" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/apev2.py#L306-L349
232,301
quodlibet/mutagen
mutagen/apev2.py
APEv2.save
def save(self, filething=None): """Save changes to a file. If no filename is given, the one most recently loaded is used. Tags are always written at the end of the file, and include a header and a footer. """ fileobj = filething.fileobj data = _APEv2Data(fileobj) if data.is_at_start: delete_bytes(fileobj, data.end - data.start, data.start) elif data.start is not None: fileobj.seek(data.start) # Delete an ID3v1 tag if present, too. fileobj.truncate() fileobj.seek(0, 2) tags = [] for key, value in self.items(): # Packed format for an item: # 4B: Value length # 4B: Value type # Key name # 1B: Null # Key value value_data = value._write() if not isinstance(key, bytes): key = key.encode("utf-8") tag_data = bytearray() tag_data += struct.pack("<2I", len(value_data), value.kind << 1) tag_data += key + b"\0" + value_data tags.append(bytes(tag_data)) # "APE tags items should be sorted ascending by size... This is # not a MUST, but STRONGLY recommended. Actually the items should # be sorted by importance/byte, but this is not feasible." tags.sort(key=lambda tag: (len(tag), tag)) num_tags = len(tags) tags = b"".join(tags) header = bytearray(b"APETAGEX") # version, tag size, item count, flags header += struct.pack("<4I", 2000, len(tags) + 32, num_tags, HAS_HEADER | IS_HEADER) header += b"\0" * 8 fileobj.write(header) fileobj.write(tags) footer = bytearray(b"APETAGEX") footer += struct.pack("<4I", 2000, len(tags) + 32, num_tags, HAS_HEADER) footer += b"\0" * 8 fileobj.write(footer)
python
def save(self, filething=None): fileobj = filething.fileobj data = _APEv2Data(fileobj) if data.is_at_start: delete_bytes(fileobj, data.end - data.start, data.start) elif data.start is not None: fileobj.seek(data.start) # Delete an ID3v1 tag if present, too. fileobj.truncate() fileobj.seek(0, 2) tags = [] for key, value in self.items(): # Packed format for an item: # 4B: Value length # 4B: Value type # Key name # 1B: Null # Key value value_data = value._write() if not isinstance(key, bytes): key = key.encode("utf-8") tag_data = bytearray() tag_data += struct.pack("<2I", len(value_data), value.kind << 1) tag_data += key + b"\0" + value_data tags.append(bytes(tag_data)) # "APE tags items should be sorted ascending by size... This is # not a MUST, but STRONGLY recommended. Actually the items should # be sorted by importance/byte, but this is not feasible." tags.sort(key=lambda tag: (len(tag), tag)) num_tags = len(tags) tags = b"".join(tags) header = bytearray(b"APETAGEX") # version, tag size, item count, flags header += struct.pack("<4I", 2000, len(tags) + 32, num_tags, HAS_HEADER | IS_HEADER) header += b"\0" * 8 fileobj.write(header) fileobj.write(tags) footer = bytearray(b"APETAGEX") footer += struct.pack("<4I", 2000, len(tags) + 32, num_tags, HAS_HEADER) footer += b"\0" * 8 fileobj.write(footer)
[ "def", "save", "(", "self", ",", "filething", "=", "None", ")", ":", "fileobj", "=", "filething", ".", "fileobj", "data", "=", "_APEv2Data", "(", "fileobj", ")", "if", "data", ".", "is_at_start", ":", "delete_bytes", "(", "fileobj", ",", "data", ".", "...
Save changes to a file. If no filename is given, the one most recently loaded is used. Tags are always written at the end of the file, and include a header and a footer.
[ "Save", "changes", "to", "a", "file", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/apev2.py#L427-L485
232,302
quodlibet/mutagen
mutagen/asf/__init__.py
ASFTags.as_dict
def as_dict(self): """Return a copy of the comment data in a real dict.""" d = {} for key, value in self: d.setdefault(key, []).append(value) return d
python
def as_dict(self): d = {} for key, value in self: d.setdefault(key, []).append(value) return d
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "{", "}", "for", "key", ",", "value", "in", "self", ":", "d", ".", "setdefault", "(", "key", ",", "[", "]", ")", ".", "append", "(", "value", ")", "return", "d" ]
Return a copy of the comment data in a real dict.
[ "Return", "a", "copy", "of", "the", "comment", "data", "in", "a", "real", "dict", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/asf/__init__.py#L168-L174
232,303
quodlibet/mutagen
mutagen/id3/_frames.py
Frame._get_v23_frame
def _get_v23_frame(self, **kwargs): """Returns a frame copy which is suitable for writing into a v2.3 tag. kwargs get passed to the specs. """ new_kwargs = {} for checker in self._framespec: name = checker.name value = getattr(self, name) new_kwargs[name] = checker._validate23(self, value, **kwargs) for checker in self._optionalspec: name = checker.name if hasattr(self, name): value = getattr(self, name) new_kwargs[name] = checker._validate23(self, value, **kwargs) return type(self)(**new_kwargs)
python
def _get_v23_frame(self, **kwargs): new_kwargs = {} for checker in self._framespec: name = checker.name value = getattr(self, name) new_kwargs[name] = checker._validate23(self, value, **kwargs) for checker in self._optionalspec: name = checker.name if hasattr(self, name): value = getattr(self, name) new_kwargs[name] = checker._validate23(self, value, **kwargs) return type(self)(**new_kwargs)
[ "def", "_get_v23_frame", "(", "self", ",", "*", "*", "kwargs", ")", ":", "new_kwargs", "=", "{", "}", "for", "checker", "in", "self", ".", "_framespec", ":", "name", "=", "checker", ".", "name", "value", "=", "getattr", "(", "self", ",", "name", ")",...
Returns a frame copy which is suitable for writing into a v2.3 tag. kwargs get passed to the specs.
[ "Returns", "a", "frame", "copy", "which", "is", "suitable", "for", "writing", "into", "a", "v2", ".", "3", "tag", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_frames.py#L125-L143
232,304
quodlibet/mutagen
mutagen/id3/_frames.py
Frame._readData
def _readData(self, id3, data): """Raises ID3JunkFrameError; Returns leftover data""" for reader in self._framespec: if len(data) or reader.handle_nodata: try: value, data = reader.read(id3, self, data) except SpecError as e: raise ID3JunkFrameError(e) else: raise ID3JunkFrameError("no data left") self._setattr(reader.name, value) for reader in self._optionalspec: if len(data) or reader.handle_nodata: try: value, data = reader.read(id3, self, data) except SpecError as e: raise ID3JunkFrameError(e) else: break self._setattr(reader.name, value) return data
python
def _readData(self, id3, data): for reader in self._framespec: if len(data) or reader.handle_nodata: try: value, data = reader.read(id3, self, data) except SpecError as e: raise ID3JunkFrameError(e) else: raise ID3JunkFrameError("no data left") self._setattr(reader.name, value) for reader in self._optionalspec: if len(data) or reader.handle_nodata: try: value, data = reader.read(id3, self, data) except SpecError as e: raise ID3JunkFrameError(e) else: break self._setattr(reader.name, value) return data
[ "def", "_readData", "(", "self", ",", "id3", ",", "data", ")", ":", "for", "reader", "in", "self", ".", "_framespec", ":", "if", "len", "(", "data", ")", "or", "reader", ".", "handle_nodata", ":", "try", ":", "value", ",", "data", "=", "reader", "....
Raises ID3JunkFrameError; Returns leftover data
[ "Raises", "ID3JunkFrameError", ";", "Returns", "leftover", "data" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_frames.py#L173-L196
232,305
quodlibet/mutagen
mutagen/id3/_frames.py
Frame._fromData
def _fromData(cls, header, tflags, data): """Construct this ID3 frame from raw string data. Raises: ID3JunkFrameError in case parsing failed NotImplementedError in case parsing isn't implemented ID3EncryptionUnsupportedError in case the frame is encrypted. """ if header.version >= header._V24: if tflags & (Frame.FLAG24_COMPRESS | Frame.FLAG24_DATALEN): # The data length int is syncsafe in 2.4 (but not 2.3). # However, we don't actually need the data length int, # except to work around a QL 0.12 bug, and in that case # all we need are the raw bytes. datalen_bytes = data[:4] data = data[4:] if tflags & Frame.FLAG24_UNSYNCH or header.f_unsynch: try: data = unsynch.decode(data) except ValueError: # Some things write synch-unsafe data with either the frame # or global unsynch flag set. Try to load them as is. # https://github.com/quodlibet/mutagen/issues/210 # https://github.com/quodlibet/mutagen/issues/223 pass if tflags & Frame.FLAG24_ENCRYPT: raise ID3EncryptionUnsupportedError if tflags & Frame.FLAG24_COMPRESS: try: data = zlib.decompress(data) except zlib.error: # the initial mutagen that went out with QL 0.12 did not # write the 4 bytes of uncompressed size. Compensate. data = datalen_bytes + data try: data = zlib.decompress(data) except zlib.error as err: raise ID3JunkFrameError( 'zlib: %s: %r' % (err, data)) elif header.version >= header._V23: if tflags & Frame.FLAG23_COMPRESS: usize, = unpack('>L', data[:4]) data = data[4:] if tflags & Frame.FLAG23_ENCRYPT: raise ID3EncryptionUnsupportedError if tflags & Frame.FLAG23_COMPRESS: try: data = zlib.decompress(data) except zlib.error as err: raise ID3JunkFrameError('zlib: %s: %r' % (err, data)) frame = cls() frame._readData(header, data) return frame
python
def _fromData(cls, header, tflags, data): if header.version >= header._V24: if tflags & (Frame.FLAG24_COMPRESS | Frame.FLAG24_DATALEN): # The data length int is syncsafe in 2.4 (but not 2.3). # However, we don't actually need the data length int, # except to work around a QL 0.12 bug, and in that case # all we need are the raw bytes. datalen_bytes = data[:4] data = data[4:] if tflags & Frame.FLAG24_UNSYNCH or header.f_unsynch: try: data = unsynch.decode(data) except ValueError: # Some things write synch-unsafe data with either the frame # or global unsynch flag set. Try to load them as is. # https://github.com/quodlibet/mutagen/issues/210 # https://github.com/quodlibet/mutagen/issues/223 pass if tflags & Frame.FLAG24_ENCRYPT: raise ID3EncryptionUnsupportedError if tflags & Frame.FLAG24_COMPRESS: try: data = zlib.decompress(data) except zlib.error: # the initial mutagen that went out with QL 0.12 did not # write the 4 bytes of uncompressed size. Compensate. data = datalen_bytes + data try: data = zlib.decompress(data) except zlib.error as err: raise ID3JunkFrameError( 'zlib: %s: %r' % (err, data)) elif header.version >= header._V23: if tflags & Frame.FLAG23_COMPRESS: usize, = unpack('>L', data[:4]) data = data[4:] if tflags & Frame.FLAG23_ENCRYPT: raise ID3EncryptionUnsupportedError if tflags & Frame.FLAG23_COMPRESS: try: data = zlib.decompress(data) except zlib.error as err: raise ID3JunkFrameError('zlib: %s: %r' % (err, data)) frame = cls() frame._readData(header, data) return frame
[ "def", "_fromData", "(", "cls", ",", "header", ",", "tflags", ",", "data", ")", ":", "if", "header", ".", "version", ">=", "header", ".", "_V24", ":", "if", "tflags", "&", "(", "Frame", ".", "FLAG24_COMPRESS", "|", "Frame", ".", "FLAG24_DATALEN", ")", ...
Construct this ID3 frame from raw string data. Raises: ID3JunkFrameError in case parsing failed NotImplementedError in case parsing isn't implemented ID3EncryptionUnsupportedError in case the frame is encrypted.
[ "Construct", "this", "ID3", "frame", "from", "raw", "string", "data", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_frames.py#L236-L292
232,306
quodlibet/mutagen
mutagen/mp3/_util.py
LAMEHeader.parse_version
def parse_version(cls, fileobj): """Returns a version string and True if a LAMEHeader follows. The passed file object will be positioned right before the lame header if True. Raises LAMEError if there is no lame version info. """ # http://wiki.hydrogenaud.io/index.php?title=LAME_version_string data = fileobj.read(20) if len(data) != 20: raise LAMEError("Not a lame header") if not data.startswith((b"LAME", b"L3.99")): raise LAMEError("Not a lame header") data = data.lstrip(b"EMAL") major, data = data[0:1], data[1:].lstrip(b".") minor = b"" for c in iterbytes(data): if not c.isdigit(): break minor += c data = data[len(minor):] try: major = int(major.decode("ascii")) minor = int(minor.decode("ascii")) except ValueError: raise LAMEError # the extended header was added sometimes in the 3.90 cycle # e.g. "LAME3.90 (alpha)" should still stop here. # (I have seen such a file) if (major, minor) < (3, 90) or ( (major, minor) == (3, 90) and data[-11:-10] == b"("): flag = data.strip(b"\x00").rstrip().decode("ascii") return (major, minor), u"%d.%d%s" % (major, minor, flag), False if len(data) < 11: raise LAMEError("Invalid version: too long") flag = data[:-11].rstrip(b"\x00") flag_string = u"" patch = u"" if flag == b"a": flag_string = u" (alpha)" elif flag == b"b": flag_string = u" (beta)" elif flag == b"r": patch = u".1+" elif flag == b" ": if (major, minor) > (3, 96): patch = u".0" else: patch = u".0+" elif flag == b"" or flag == b".": patch = u".0+" else: flag_string = u" (?)" # extended header, seek back to 9 bytes for the caller fileobj.seek(-11, 1) return (major, minor), \ u"%d.%d%s%s" % (major, minor, patch, flag_string), True
python
def parse_version(cls, fileobj): # http://wiki.hydrogenaud.io/index.php?title=LAME_version_string data = fileobj.read(20) if len(data) != 20: raise LAMEError("Not a lame header") if not data.startswith((b"LAME", b"L3.99")): raise LAMEError("Not a lame header") data = data.lstrip(b"EMAL") major, data = data[0:1], data[1:].lstrip(b".") minor = b"" for c in iterbytes(data): if not c.isdigit(): break minor += c data = data[len(minor):] try: major = int(major.decode("ascii")) minor = int(minor.decode("ascii")) except ValueError: raise LAMEError # the extended header was added sometimes in the 3.90 cycle # e.g. "LAME3.90 (alpha)" should still stop here. # (I have seen such a file) if (major, minor) < (3, 90) or ( (major, minor) == (3, 90) and data[-11:-10] == b"("): flag = data.strip(b"\x00").rstrip().decode("ascii") return (major, minor), u"%d.%d%s" % (major, minor, flag), False if len(data) < 11: raise LAMEError("Invalid version: too long") flag = data[:-11].rstrip(b"\x00") flag_string = u"" patch = u"" if flag == b"a": flag_string = u" (alpha)" elif flag == b"b": flag_string = u" (beta)" elif flag == b"r": patch = u".1+" elif flag == b" ": if (major, minor) > (3, 96): patch = u".0" else: patch = u".0+" elif flag == b"" or flag == b".": patch = u".0+" else: flag_string = u" (?)" # extended header, seek back to 9 bytes for the caller fileobj.seek(-11, 1) return (major, minor), \ u"%d.%d%s%s" % (major, minor, patch, flag_string), True
[ "def", "parse_version", "(", "cls", ",", "fileobj", ")", ":", "# http://wiki.hydrogenaud.io/index.php?title=LAME_version_string", "data", "=", "fileobj", ".", "read", "(", "20", ")", "if", "len", "(", "data", ")", "!=", "20", ":", "raise", "LAMEError", "(", "\...
Returns a version string and True if a LAMEHeader follows. The passed file object will be positioned right before the lame header if True. Raises LAMEError if there is no lame version info.
[ "Returns", "a", "version", "string", "and", "True", "if", "a", "LAMEHeader", "follows", ".", "The", "passed", "file", "object", "will", "be", "positioned", "right", "before", "the", "lame", "header", "if", "True", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp3/_util.py#L271-L337
232,307
quodlibet/mutagen
mutagen/mp3/_util.py
XingHeader.get_encoder_settings
def get_encoder_settings(self): """Returns the guessed encoder settings""" if self.lame_header is None: return u"" return self.lame_header.guess_settings(*self.lame_version)
python
def get_encoder_settings(self): if self.lame_header is None: return u"" return self.lame_header.guess_settings(*self.lame_version)
[ "def", "get_encoder_settings", "(", "self", ")", ":", "if", "self", ".", "lame_header", "is", "None", ":", "return", "u\"\"", "return", "self", ".", "lame_header", ".", "guess_settings", "(", "*", "self", ".", "lame_version", ")" ]
Returns the guessed encoder settings
[ "Returns", "the", "guessed", "encoder", "settings" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp3/_util.py#L426-L431
232,308
quodlibet/mutagen
mutagen/mp3/_util.py
XingHeader.get_offset
def get_offset(cls, info): """Calculate the offset to the Xing header from the start of the MPEG header including sync based on the MPEG header's content. """ assert info.layer == 3 if info.version == 1: if info.mode != 3: return 36 else: return 21 else: if info.mode != 3: return 21 else: return 13
python
def get_offset(cls, info): assert info.layer == 3 if info.version == 1: if info.mode != 3: return 36 else: return 21 else: if info.mode != 3: return 21 else: return 13
[ "def", "get_offset", "(", "cls", ",", "info", ")", ":", "assert", "info", ".", "layer", "==", "3", "if", "info", ".", "version", "==", "1", ":", "if", "info", ".", "mode", "!=", "3", ":", "return", "36", "else", ":", "return", "21", "else", ":", ...
Calculate the offset to the Xing header from the start of the MPEG header including sync based on the MPEG header's content.
[ "Calculate", "the", "offset", "to", "the", "Xing", "header", "from", "the", "start", "of", "the", "MPEG", "header", "including", "sync", "based", "on", "the", "MPEG", "header", "s", "content", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp3/_util.py#L434-L450
232,309
quodlibet/mutagen
mutagen/_senf/_environ.py
get_windows_env_var
def get_windows_env_var(key): """Get an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) buf = ctypes.create_unicode_buffer(32767) stored = winapi.GetEnvironmentVariableW(key, buf, 32767) if stored == 0: raise ctypes.WinError() return buf[:stored]
python
def get_windows_env_var(key): if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) buf = ctypes.create_unicode_buffer(32767) stored = winapi.GetEnvironmentVariableW(key, buf, 32767) if stored == 0: raise ctypes.WinError() return buf[:stored]
[ "def", "get_windows_env_var", "(", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "text_type", ")", ":", "raise", "TypeError", "(", "\"%r not of type %r\"", "%", "(", "key", ",", "text_type", ")", ")", "buf", "=", "ctypes", ".", "create_unico...
Get an env var. Raises: WindowsError
[ "Get", "an", "env", "var", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_environ.py#L35-L50
232,310
quodlibet/mutagen
mutagen/_senf/_environ.py
set_windows_env_var
def set_windows_env_var(key, value): """Set an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) if not isinstance(value, text_type): raise TypeError("%r not of type %r" % (value, text_type)) status = winapi.SetEnvironmentVariableW(key, value) if status == 0: raise ctypes.WinError()
python
def set_windows_env_var(key, value): if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) if not isinstance(value, text_type): raise TypeError("%r not of type %r" % (value, text_type)) status = winapi.SetEnvironmentVariableW(key, value) if status == 0: raise ctypes.WinError()
[ "def", "set_windows_env_var", "(", "key", ",", "value", ")", ":", "if", "not", "isinstance", "(", "key", ",", "text_type", ")", ":", "raise", "TypeError", "(", "\"%r not of type %r\"", "%", "(", "key", ",", "text_type", ")", ")", "if", "not", "isinstance",...
Set an env var. Raises: WindowsError
[ "Set", "an", "env", "var", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_environ.py#L53-L68
232,311
quodlibet/mutagen
mutagen/_senf/_environ.py
del_windows_env_var
def del_windows_env_var(key): """Delete an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) status = winapi.SetEnvironmentVariableW(key, None) if status == 0: raise ctypes.WinError()
python
def del_windows_env_var(key): if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) status = winapi.SetEnvironmentVariableW(key, None) if status == 0: raise ctypes.WinError()
[ "def", "del_windows_env_var", "(", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "text_type", ")", ":", "raise", "TypeError", "(", "\"%r not of type %r\"", "%", "(", "key", ",", "text_type", ")", ")", "status", "=", "winapi", ".", "SetEnviro...
Delete an env var. Raises: WindowsError
[ "Delete", "an", "env", "var", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_environ.py#L71-L83
232,312
quodlibet/mutagen
mutagen/_senf/_environ.py
read_windows_environ
def read_windows_environ(): """Returns a unicode dict of the Windows environment. Raises: WindowsEnvironError """ res = winapi.GetEnvironmentStringsW() if not res: raise ctypes.WinError() res = ctypes.cast(res, ctypes.POINTER(ctypes.c_wchar)) done = [] current = u"" i = 0 while 1: c = res[i] i += 1 if c == u"\x00": if not current: break done.append(current) current = u"" continue current += c dict_ = {} for entry in done: try: key, value = entry.split(u"=", 1) except ValueError: continue key = _norm_key(key) dict_[key] = value status = winapi.FreeEnvironmentStringsW(res) if status == 0: raise ctypes.WinError() return dict_
python
def read_windows_environ(): res = winapi.GetEnvironmentStringsW() if not res: raise ctypes.WinError() res = ctypes.cast(res, ctypes.POINTER(ctypes.c_wchar)) done = [] current = u"" i = 0 while 1: c = res[i] i += 1 if c == u"\x00": if not current: break done.append(current) current = u"" continue current += c dict_ = {} for entry in done: try: key, value = entry.split(u"=", 1) except ValueError: continue key = _norm_key(key) dict_[key] = value status = winapi.FreeEnvironmentStringsW(res) if status == 0: raise ctypes.WinError() return dict_
[ "def", "read_windows_environ", "(", ")", ":", "res", "=", "winapi", ".", "GetEnvironmentStringsW", "(", ")", "if", "not", "res", ":", "raise", "ctypes", ".", "WinError", "(", ")", "res", "=", "ctypes", ".", "cast", "(", "res", ",", "ctypes", ".", "POIN...
Returns a unicode dict of the Windows environment. Raises: WindowsEnvironError
[ "Returns", "a", "unicode", "dict", "of", "the", "Windows", "environment", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_environ.py#L86-L126
232,313
quodlibet/mutagen
mutagen/_senf/_environ.py
getenv
def getenv(key, value=None): """Like `os.getenv` but returns unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (object): The value to return if the env var does not exist Returns: `fsnative` or `object`: The env var or the passed value if it doesn't exist """ key = path2fsn(key) if is_win and PY2: return environ.get(key, value) return os.getenv(key, value)
python
def getenv(key, value=None): key = path2fsn(key) if is_win and PY2: return environ.get(key, value) return os.getenv(key, value)
[ "def", "getenv", "(", "key", ",", "value", "=", "None", ")", ":", "key", "=", "path2fsn", "(", "key", ")", "if", "is_win", "and", "PY2", ":", "return", "environ", ".", "get", "(", "key", ",", "value", ")", "return", "os", ".", "getenv", "(", "key...
Like `os.getenv` but returns unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (object): The value to return if the env var does not exist Returns: `fsnative` or `object`: The env var or the passed value if it doesn't exist
[ "Like", "os", ".", "getenv", "but", "returns", "unicode", "under", "Windows", "+", "Python", "2" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_environ.py#L210-L224
232,314
quodlibet/mutagen
mutagen/_senf/_environ.py
unsetenv
def unsetenv(key): """Like `os.unsetenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to unset """ key = path2fsn(key) if is_win: # python 3 has no unsetenv under Windows -> use our ctypes one as well try: del_windows_env_var(key) except WindowsError: pass else: os.unsetenv(key)
python
def unsetenv(key): key = path2fsn(key) if is_win: # python 3 has no unsetenv under Windows -> use our ctypes one as well try: del_windows_env_var(key) except WindowsError: pass else: os.unsetenv(key)
[ "def", "unsetenv", "(", "key", ")", ":", "key", "=", "path2fsn", "(", "key", ")", "if", "is_win", ":", "# python 3 has no unsetenv under Windows -> use our ctypes one as well", "try", ":", "del_windows_env_var", "(", "key", ")", "except", "WindowsError", ":", "pass"...
Like `os.unsetenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to unset
[ "Like", "os", ".", "unsetenv", "but", "takes", "unicode", "under", "Windows", "+", "Python", "2" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_environ.py#L227-L242
232,315
quodlibet/mutagen
mutagen/_senf/_environ.py
putenv
def putenv(key, value): """Like `os.putenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (pathlike): The value to set Raises: ValueError """ key = path2fsn(key) value = path2fsn(value) if is_win and PY2: try: set_windows_env_var(key, value) except WindowsError: # py3 + win fails here raise ValueError else: try: os.putenv(key, value) except OSError: # win + py3 raise here for invalid keys which is probably a bug. # ValueError seems better raise ValueError
python
def putenv(key, value): key = path2fsn(key) value = path2fsn(value) if is_win and PY2: try: set_windows_env_var(key, value) except WindowsError: # py3 + win fails here raise ValueError else: try: os.putenv(key, value) except OSError: # win + py3 raise here for invalid keys which is probably a bug. # ValueError seems better raise ValueError
[ "def", "putenv", "(", "key", ",", "value", ")", ":", "key", "=", "path2fsn", "(", "key", ")", "value", "=", "path2fsn", "(", "value", ")", "if", "is_win", "and", "PY2", ":", "try", ":", "set_windows_env_var", "(", "key", ",", "value", ")", "except", ...
Like `os.putenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (pathlike): The value to set Raises: ValueError
[ "Like", "os", ".", "putenv", "but", "takes", "unicode", "under", "Windows", "+", "Python", "2" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_environ.py#L245-L270
232,316
quodlibet/mutagen
mutagen/wavpack.py
_WavPackHeader.from_fileobj
def from_fileobj(cls, fileobj): """A new _WavPackHeader or raises WavPackHeaderError""" header = fileobj.read(32) if len(header) != 32 or not header.startswith(b"wvpk"): raise WavPackHeaderError("not a WavPack header: %r" % header) block_size = cdata.uint_le(header[4:8]) version = cdata.ushort_le(header[8:10]) track_no = ord(header[10:11]) index_no = ord(header[11:12]) samples = cdata.uint_le(header[12:16]) if samples == 2 ** 32 - 1: samples = -1 block_index = cdata.uint_le(header[16:20]) block_samples = cdata.uint_le(header[20:24]) flags = cdata.uint_le(header[24:28]) crc = cdata.uint_le(header[28:32]) return _WavPackHeader(block_size, version, track_no, index_no, samples, block_index, block_samples, flags, crc)
python
def from_fileobj(cls, fileobj): header = fileobj.read(32) if len(header) != 32 or not header.startswith(b"wvpk"): raise WavPackHeaderError("not a WavPack header: %r" % header) block_size = cdata.uint_le(header[4:8]) version = cdata.ushort_le(header[8:10]) track_no = ord(header[10:11]) index_no = ord(header[11:12]) samples = cdata.uint_le(header[12:16]) if samples == 2 ** 32 - 1: samples = -1 block_index = cdata.uint_le(header[16:20]) block_samples = cdata.uint_le(header[20:24]) flags = cdata.uint_le(header[24:28]) crc = cdata.uint_le(header[28:32]) return _WavPackHeader(block_size, version, track_no, index_no, samples, block_index, block_samples, flags, crc)
[ "def", "from_fileobj", "(", "cls", ",", "fileobj", ")", ":", "header", "=", "fileobj", ".", "read", "(", "32", ")", "if", "len", "(", "header", ")", "!=", "32", "or", "not", "header", ".", "startswith", "(", "b\"wvpk\"", ")", ":", "raise", "WavPackHe...
A new _WavPackHeader or raises WavPackHeaderError
[ "A", "new", "_WavPackHeader", "or", "raises", "WavPackHeaderError" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/wavpack.py#L51-L71
232,317
quodlibet/mutagen
mutagen/id3/_tags.py
determine_bpi
def determine_bpi(data, frames, EMPTY=b"\x00" * 10): """Takes id3v2.4 frame data and determines if ints or bitpaddedints should be used for parsing. Needed because iTunes used to write normal ints for frame sizes. """ # count number of tags found as BitPaddedInt and how far past o = 0 asbpi = 0 while o < len(data) - 10: part = data[o:o + 10] if part == EMPTY: bpioff = -((len(data) - o) % 10) break name, size, flags = struct.unpack('>4sLH', part) size = BitPaddedInt(size) o += 10 + size if PY3: try: name = name.decode("ascii") except UnicodeDecodeError: continue if name in frames: asbpi += 1 else: bpioff = o - len(data) # count number of tags found as int and how far past o = 0 asint = 0 while o < len(data) - 10: part = data[o:o + 10] if part == EMPTY: intoff = -((len(data) - o) % 10) break name, size, flags = struct.unpack('>4sLH', part) o += 10 + size if PY3: try: name = name.decode("ascii") except UnicodeDecodeError: continue if name in frames: asint += 1 else: intoff = o - len(data) # if more tags as int, or equal and bpi is past and int is not if asint > asbpi or (asint == asbpi and (bpioff >= 1 and intoff <= 1)): return int return BitPaddedInt
python
def determine_bpi(data, frames, EMPTY=b"\x00" * 10): # count number of tags found as BitPaddedInt and how far past o = 0 asbpi = 0 while o < len(data) - 10: part = data[o:o + 10] if part == EMPTY: bpioff = -((len(data) - o) % 10) break name, size, flags = struct.unpack('>4sLH', part) size = BitPaddedInt(size) o += 10 + size if PY3: try: name = name.decode("ascii") except UnicodeDecodeError: continue if name in frames: asbpi += 1 else: bpioff = o - len(data) # count number of tags found as int and how far past o = 0 asint = 0 while o < len(data) - 10: part = data[o:o + 10] if part == EMPTY: intoff = -((len(data) - o) % 10) break name, size, flags = struct.unpack('>4sLH', part) o += 10 + size if PY3: try: name = name.decode("ascii") except UnicodeDecodeError: continue if name in frames: asint += 1 else: intoff = o - len(data) # if more tags as int, or equal and bpi is past and int is not if asint > asbpi or (asint == asbpi and (bpioff >= 1 and intoff <= 1)): return int return BitPaddedInt
[ "def", "determine_bpi", "(", "data", ",", "frames", ",", "EMPTY", "=", "b\"\\x00\"", "*", "10", ")", ":", "# count number of tags found as BitPaddedInt and how far past", "o", "=", "0", "asbpi", "=", "0", "while", "o", "<", "len", "(", "data", ")", "-", "10"...
Takes id3v2.4 frame data and determines if ints or bitpaddedints should be used for parsing. Needed because iTunes used to write normal ints for frame sizes.
[ "Takes", "id3v2", ".", "4", "frame", "data", "and", "determines", "if", "ints", "or", "bitpaddedints", "should", "be", "used", "for", "parsing", ".", "Needed", "because", "iTunes", "used", "to", "write", "normal", "ints", "for", "frame", "sizes", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L117-L167
232,318
quodlibet/mutagen
mutagen/id3/_tags.py
read_frames
def read_frames(id3, data, frames): """Does not error out""" assert id3.version >= ID3Header._V22 result = [] unsupported_frames = [] if id3.version < ID3Header._V24 and id3.f_unsynch: try: data = unsynch.decode(data) except ValueError: pass if id3.version >= ID3Header._V23: if id3.version < ID3Header._V24: bpi = int else: bpi = determine_bpi(data, frames) while data: header = data[:10] try: name, size, flags = struct.unpack('>4sLH', header) except struct.error: break # not enough header if name.strip(b'\x00') == b'': break size = bpi(size) framedata = data[10:10 + size] data = data[10 + size:] if size == 0: continue # drop empty frames if PY3: try: name = name.decode('ascii') except UnicodeDecodeError: continue try: # someone writes 2.3 frames with 2.2 names if name[-1] == "\x00": tag = Frames_2_2[name[:-1]] name = tag.__base__.__name__ tag = frames[name] except KeyError: if is_valid_frame_id(name): unsupported_frames.append(header + framedata) else: try: result.append(tag._fromData(id3, flags, framedata)) except NotImplementedError: unsupported_frames.append(header + framedata) except ID3JunkFrameError: pass elif id3.version >= ID3Header._V22: while data: header = data[0:6] try: name, size = struct.unpack('>3s3s', header) except struct.error: break # not enough header size, = struct.unpack('>L', b'\x00' + size) if name.strip(b'\x00') == b'': break framedata = data[6:6 + size] data = data[6 + size:] if size == 0: continue # drop empty frames if PY3: try: name = name.decode('ascii') except UnicodeDecodeError: continue try: tag = frames[name] except KeyError: if is_valid_frame_id(name): unsupported_frames.append(header + framedata) else: try: result.append( tag._fromData(id3, 0, framedata)) except (ID3EncryptionUnsupportedError, NotImplementedError): unsupported_frames.append(header + framedata) except ID3JunkFrameError: pass return result, unsupported_frames, data
python
def read_frames(id3, data, frames): assert id3.version >= ID3Header._V22 result = [] unsupported_frames = [] if id3.version < ID3Header._V24 and id3.f_unsynch: try: data = unsynch.decode(data) except ValueError: pass if id3.version >= ID3Header._V23: if id3.version < ID3Header._V24: bpi = int else: bpi = determine_bpi(data, frames) while data: header = data[:10] try: name, size, flags = struct.unpack('>4sLH', header) except struct.error: break # not enough header if name.strip(b'\x00') == b'': break size = bpi(size) framedata = data[10:10 + size] data = data[10 + size:] if size == 0: continue # drop empty frames if PY3: try: name = name.decode('ascii') except UnicodeDecodeError: continue try: # someone writes 2.3 frames with 2.2 names if name[-1] == "\x00": tag = Frames_2_2[name[:-1]] name = tag.__base__.__name__ tag = frames[name] except KeyError: if is_valid_frame_id(name): unsupported_frames.append(header + framedata) else: try: result.append(tag._fromData(id3, flags, framedata)) except NotImplementedError: unsupported_frames.append(header + framedata) except ID3JunkFrameError: pass elif id3.version >= ID3Header._V22: while data: header = data[0:6] try: name, size = struct.unpack('>3s3s', header) except struct.error: break # not enough header size, = struct.unpack('>L', b'\x00' + size) if name.strip(b'\x00') == b'': break framedata = data[6:6 + size] data = data[6 + size:] if size == 0: continue # drop empty frames if PY3: try: name = name.decode('ascii') except UnicodeDecodeError: continue try: tag = frames[name] except KeyError: if is_valid_frame_id(name): unsupported_frames.append(header + framedata) else: try: result.append( tag._fromData(id3, 0, framedata)) except (ID3EncryptionUnsupportedError, NotImplementedError): unsupported_frames.append(header + framedata) except ID3JunkFrameError: pass return result, unsupported_frames, data
[ "def", "read_frames", "(", "id3", ",", "data", ",", "frames", ")", ":", "assert", "id3", ".", "version", ">=", "ID3Header", ".", "_V22", "result", "=", "[", "]", "unsupported_frames", "=", "[", "]", "if", "id3", ".", "version", "<", "ID3Header", ".", ...
Does not error out
[ "Does", "not", "error", "out" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L543-L638
232,319
quodlibet/mutagen
mutagen/id3/_tags.py
ID3Tags.setall
def setall(self, key, values): """Delete frames of the given type and add frames in 'values'. Args: key (text): key for frames to delete values (list[Frame]): frames to add """ self.delall(key) for tag in values: self[tag.HashKey] = tag
python
def setall(self, key, values): self.delall(key) for tag in values: self[tag.HashKey] = tag
[ "def", "setall", "(", "self", ",", "key", ",", "values", ")", ":", "self", ".", "delall", "(", "key", ")", "for", "tag", "in", "values", ":", "self", "[", "tag", ".", "HashKey", "]", "=", "tag" ]
Delete frames of the given type and add frames in 'values'. Args: key (text): key for frames to delete values (list[Frame]): frames to add
[ "Delete", "frames", "of", "the", "given", "type", "and", "add", "frames", "in", "values", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L241-L251
232,320
quodlibet/mutagen
mutagen/id3/_tags.py
ID3Tags._add
def _add(self, frame, strict): """Add a frame. Args: frame (Frame): the frame to add strict (bool): if this should raise in case it can't be added and frames shouldn't be merged. """ if not isinstance(frame, Frame): raise TypeError("%r not a Frame instance" % frame) orig_frame = frame frame = frame._upgrade_frame() if frame is None: if not strict: return raise TypeError( "Can't upgrade %r frame" % type(orig_frame).__name__) hash_key = frame.HashKey if strict or hash_key not in self: self[hash_key] = frame return # Try to merge frames, or change the new one. Since changing # the new one can lead to new conflicts, try until everything is # either merged or added. while True: old_frame = self[hash_key] new_frame = old_frame._merge_frame(frame) new_hash = new_frame.HashKey if new_hash == hash_key: self[hash_key] = new_frame break else: assert new_frame is frame if new_hash not in self: self[new_hash] = new_frame break hash_key = new_hash
python
def _add(self, frame, strict): if not isinstance(frame, Frame): raise TypeError("%r not a Frame instance" % frame) orig_frame = frame frame = frame._upgrade_frame() if frame is None: if not strict: return raise TypeError( "Can't upgrade %r frame" % type(orig_frame).__name__) hash_key = frame.HashKey if strict or hash_key not in self: self[hash_key] = frame return # Try to merge frames, or change the new one. Since changing # the new one can lead to new conflicts, try until everything is # either merged or added. while True: old_frame = self[hash_key] new_frame = old_frame._merge_frame(frame) new_hash = new_frame.HashKey if new_hash == hash_key: self[hash_key] = new_frame break else: assert new_frame is frame if new_hash not in self: self[new_hash] = new_frame break hash_key = new_hash
[ "def", "_add", "(", "self", ",", "frame", ",", "strict", ")", ":", "if", "not", "isinstance", "(", "frame", ",", "Frame", ")", ":", "raise", "TypeError", "(", "\"%r not a Frame instance\"", "%", "frame", ")", "orig_frame", "=", "frame", "frame", "=", "fr...
Add a frame. Args: frame (Frame): the frame to add strict (bool): if this should raise in case it can't be added and frames shouldn't be merged.
[ "Add", "a", "frame", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L286-L326
232,321
quodlibet/mutagen
mutagen/id3/_tags.py
ID3Tags.__update_common
def __update_common(self): """Updates done by both v23 and v24 update""" if "TCON" in self: # Get rid of "(xx)Foobr" format. self["TCON"].genres = self["TCON"].genres mimes = {"PNG": "image/png", "JPG": "image/jpeg"} for pic in self.getall("APIC"): if pic.mime in mimes: newpic = APIC( encoding=pic.encoding, mime=mimes[pic.mime], type=pic.type, desc=pic.desc, data=pic.data) self.add(newpic)
python
def __update_common(self): if "TCON" in self: # Get rid of "(xx)Foobr" format. self["TCON"].genres = self["TCON"].genres mimes = {"PNG": "image/png", "JPG": "image/jpeg"} for pic in self.getall("APIC"): if pic.mime in mimes: newpic = APIC( encoding=pic.encoding, mime=mimes[pic.mime], type=pic.type, desc=pic.desc, data=pic.data) self.add(newpic)
[ "def", "__update_common", "(", "self", ")", ":", "if", "\"TCON\"", "in", "self", ":", "# Get rid of \"(xx)Foobr\" format.", "self", "[", "\"TCON\"", "]", ".", "genres", "=", "self", "[", "\"TCON\"", "]", ".", "genres", "mimes", "=", "{", "\"PNG\"", ":", "\...
Updates done by both v23 and v24 update
[ "Updates", "done", "by", "both", "v23", "and", "v24", "update" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L346-L359
232,322
quodlibet/mutagen
mutagen/id3/_tags.py
ID3Tags.update_to_v24
def update_to_v24(self): """Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag. """ self.__update_common() # TDAT, TYER, and TIME have been turned into TDRC. try: date = text_type(self.get("TYER", "")) if date.strip(u"\x00"): self.pop("TYER") dat = text_type(self.get("TDAT", "")) if dat.strip("\x00"): self.pop("TDAT") date = "%s-%s-%s" % (date, dat[2:], dat[:2]) time = text_type(self.get("TIME", "")) if time.strip("\x00"): self.pop("TIME") date += "T%s:%s:00" % (time[:2], time[2:]) if "TDRC" not in self: self.add(TDRC(encoding=0, text=date)) except UnicodeDecodeError: # Old ID3 tags have *lots* of Unicode problems, so if TYER # is bad, just chuck the frames. pass # TORY can be the first part of a TDOR. if "TORY" in self: f = self.pop("TORY") if "TDOR" not in self: try: self.add(TDOR(encoding=0, text=str(f))) except UnicodeDecodeError: pass # IPLS is now TIPL. if "IPLS" in self: f = self.pop("IPLS") if "TIPL" not in self: self.add(TIPL(encoding=f.encoding, people=f.people)) # These can't be trivially translated to any ID3v2.4 tags, or # should have been removed already. for key in ["RVAD", "EQUA", "TRDA", "TSIZ", "TDAT", "TIME"]: if key in self: del(self[key]) # Recurse into chapters for f in self.getall("CHAP"): f.sub_frames.update_to_v24() for f in self.getall("CTOC"): f.sub_frames.update_to_v24()
python
def update_to_v24(self): self.__update_common() # TDAT, TYER, and TIME have been turned into TDRC. try: date = text_type(self.get("TYER", "")) if date.strip(u"\x00"): self.pop("TYER") dat = text_type(self.get("TDAT", "")) if dat.strip("\x00"): self.pop("TDAT") date = "%s-%s-%s" % (date, dat[2:], dat[:2]) time = text_type(self.get("TIME", "")) if time.strip("\x00"): self.pop("TIME") date += "T%s:%s:00" % (time[:2], time[2:]) if "TDRC" not in self: self.add(TDRC(encoding=0, text=date)) except UnicodeDecodeError: # Old ID3 tags have *lots* of Unicode problems, so if TYER # is bad, just chuck the frames. pass # TORY can be the first part of a TDOR. if "TORY" in self: f = self.pop("TORY") if "TDOR" not in self: try: self.add(TDOR(encoding=0, text=str(f))) except UnicodeDecodeError: pass # IPLS is now TIPL. if "IPLS" in self: f = self.pop("IPLS") if "TIPL" not in self: self.add(TIPL(encoding=f.encoding, people=f.people)) # These can't be trivially translated to any ID3v2.4 tags, or # should have been removed already. for key in ["RVAD", "EQUA", "TRDA", "TSIZ", "TDAT", "TIME"]: if key in self: del(self[key]) # Recurse into chapters for f in self.getall("CHAP"): f.sub_frames.update_to_v24() for f in self.getall("CTOC"): f.sub_frames.update_to_v24()
[ "def", "update_to_v24", "(", "self", ")", ":", "self", ".", "__update_common", "(", ")", "# TDAT, TYER, and TIME have been turned into TDRC.", "try", ":", "date", "=", "text_type", "(", "self", ".", "get", "(", "\"TYER\"", ",", "\"\"", ")", ")", "if", "date", ...
Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag.
[ "Convert", "older", "tags", "into", "an", "ID3v2", ".", "4", "tag", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L361-L416
232,323
quodlibet/mutagen
mutagen/id3/_tags.py
ID3Tags._copy
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
def _copy(self): items = self.items() subs = {} for f in (self.getall("CHAP") + self.getall("CTOC")): subs[f.HashKey] = f.sub_frames._copy() return (items, subs)
[ "def", "_copy", "(", "self", ")", ":", "items", "=", "self", ".", "items", "(", ")", "subs", "=", "{", "}", "for", "f", "in", "(", "self", ".", "getall", "(", "\"CHAP\"", ")", "+", "self", ".", "getall", "(", "\"CTOC\"", ")", ")", ":", "subs", ...
Creates a shallow copy of all tags
[ "Creates", "a", "shallow", "copy", "of", "all", "tags" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L482-L489
232,324
quodlibet/mutagen
mutagen/_tools/_util.py
SignalHandler.block
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("Aborted...")
python
def block(self): self._nosig = True yield self._nosig = False if self._interrupted: raise SystemExit("Aborted...")
[ "def", "block", "(", "self", ")", ":", "self", ".", "_nosig", "=", "True", "yield", "self", ".", "_nosig", "=", "False", "if", "self", ".", "_interrupted", ":", "raise", "SystemExit", "(", "\"Aborted...\"", ")" ]
While this context manager is active any signals for aborting the process will be queued and exit the program once the context is left.
[ "While", "this", "context", "manager", "is", "active", "any", "signals", "for", "aborting", "the", "process", "will", "be", "queued", "and", "exit", "the", "program", "once", "the", "context", "is", "left", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_tools/_util.py#L78-L88
232,325
quodlibet/mutagen
mutagen/_vorbis.py
is_valid_key
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("needs to be str not bytes") for c in key: if c < " " or c > "}" or c == "=": return False else: return bool(key)
python
def is_valid_key(key): if PY3 and isinstance(key, bytes): raise TypeError("needs to be str not bytes") for c in key: if c < " " or c > "}" or c == "=": return False else: return bool(key)
[ "def", "is_valid_key", "(", "key", ")", ":", "if", "PY3", "and", "isinstance", "(", "key", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"needs to be str not bytes\"", ")", "for", "c", "in", "key", ":", "if", "c", "<", "\" \"", "or", "c", ">", ...
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
[ "Return", "true", "if", "a", "string", "is", "a", "valid", "Vorbis", "comment", "key", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_vorbis.py#L26-L42
232,326
quodlibet/mutagen
mutagen/_vorbis.py
VComment.load
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. framing (bool): if true, fail if a framing bit is not present Framing bits are required by the Vorbis comment specification, but are not used in FLAC Vorbis comment blocks. """ try: vendor_length = cdata.uint_le(fileobj.read(4)) self.vendor = fileobj.read(vendor_length).decode('utf-8', errors) count = cdata.uint_le(fileobj.read(4)) for i in xrange(count): length = cdata.uint_le(fileobj.read(4)) try: string = fileobj.read(length).decode('utf-8', errors) except (OverflowError, MemoryError): raise error("cannot read %d bytes, too large" % length) try: tag, value = string.split('=', 1) except ValueError as err: if errors == "ignore": continue elif errors == "replace": tag, value = u"unknown%d" % i, string else: reraise(VorbisEncodingError, err, sys.exc_info()[2]) try: tag = tag.encode('ascii', errors) except UnicodeEncodeError: raise VorbisEncodingError("invalid tag name %r" % tag) else: # string keys in py3k if PY3: tag = tag.decode("ascii") if is_valid_key(tag): self.append((tag, value)) if framing and not bytearray(fileobj.read(1))[0] & 0x01: raise VorbisUnsetFrameError("framing bit was unset") except (cdata.error, TypeError): raise error("file is not a valid Vorbis comment")
python
def load(self, fileobj, errors='replace', framing=True): try: vendor_length = cdata.uint_le(fileobj.read(4)) self.vendor = fileobj.read(vendor_length).decode('utf-8', errors) count = cdata.uint_le(fileobj.read(4)) for i in xrange(count): length = cdata.uint_le(fileobj.read(4)) try: string = fileobj.read(length).decode('utf-8', errors) except (OverflowError, MemoryError): raise error("cannot read %d bytes, too large" % length) try: tag, value = string.split('=', 1) except ValueError as err: if errors == "ignore": continue elif errors == "replace": tag, value = u"unknown%d" % i, string else: reraise(VorbisEncodingError, err, sys.exc_info()[2]) try: tag = tag.encode('ascii', errors) except UnicodeEncodeError: raise VorbisEncodingError("invalid tag name %r" % tag) else: # string keys in py3k if PY3: tag = tag.decode("ascii") if is_valid_key(tag): self.append((tag, value)) if framing and not bytearray(fileobj.read(1))[0] & 0x01: raise VorbisUnsetFrameError("framing bit was unset") except (cdata.error, TypeError): raise error("file is not a valid Vorbis comment")
[ "def", "load", "(", "self", ",", "fileobj", ",", "errors", "=", "'replace'", ",", "framing", "=", "True", ")", ":", "try", ":", "vendor_length", "=", "cdata", ".", "uint_le", "(", "fileobj", ".", "read", "(", "4", ")", ")", "self", ".", "vendor", "...
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. framing (bool): if true, fail if a framing bit is not present Framing bits are required by the Vorbis comment specification, but are not used in FLAC Vorbis comment blocks.
[ "Parse", "a", "Vorbis", "comment", "from", "a", "file", "-", "like", "object", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_vorbis.py#L90-L136
232,327
quodlibet/mutagen
mutagen/_vorbis.py
VComment.validate
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 string. """ if not isinstance(self.vendor, text_type): if PY3: raise ValueError("vendor needs to be str") try: self.vendor.decode('utf-8') except UnicodeDecodeError: raise ValueError for key, value in self: try: if not is_valid_key(key): raise ValueError("%r is not a valid key" % key) except TypeError: raise ValueError("%r is not a valid key" % key) if not isinstance(value, text_type): if PY3: err = "%r needs to be str for key %r" % (value, key) raise ValueError(err) try: value.decode("utf-8") except Exception: err = "%r is not a valid value for key %r" % (value, key) raise ValueError(err) return True
python
def validate(self): if not isinstance(self.vendor, text_type): if PY3: raise ValueError("vendor needs to be str") try: self.vendor.decode('utf-8') except UnicodeDecodeError: raise ValueError for key, value in self: try: if not is_valid_key(key): raise ValueError("%r is not a valid key" % key) except TypeError: raise ValueError("%r is not a valid key" % key) if not isinstance(value, text_type): if PY3: err = "%r needs to be str for key %r" % (value, key) raise ValueError(err) try: value.decode("utf-8") except Exception: err = "%r is not a valid value for key %r" % (value, key) raise ValueError(err) return True
[ "def", "validate", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "vendor", ",", "text_type", ")", ":", "if", "PY3", ":", "raise", "ValueError", "(", "\"vendor needs to be str\"", ")", "try", ":", "self", ".", "vendor", ".", "decode"...
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 string.
[ "Validate", "keys", "and", "values", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_vorbis.py#L138-L175
232,328
quodlibet/mutagen
mutagen/id3/_id3v1.py
ParseID3v1
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`]): dict mapping frame IDs to Frame objects """ if v2_version not in (3, 4): raise ValueError("Only 3 and 4 possible for v2_version") try: data = data[data.index(b"TAG"):] except ValueError: return None if 128 < len(data) or len(data) < 124: return None # Issue #69 - Previous versions of Mutagen, when encountering # out-of-spec TDRC and TYER frames of less than four characters, # wrote only the characters available - e.g. "1" or "" - into the # year field. To parse those, reduce the size of the year field. # Amazingly, "0s" works as a struct format string. unpack_fmt = "3s30s30s30s%ds29sBB" % (len(data) - 124) try: tag, title, artist, album, year, comment, track, genre = unpack( unpack_fmt, data) except StructError: return None if tag != b"TAG": return None def fix(data): return data.split(b"\x00")[0].strip().decode('latin1') title, artist, album, year, comment = map( fix, [title, artist, album, year, comment]) frame_class = { "TIT2": TIT2, "TPE1": TPE1, "TALB": TALB, "TYER": TYER, "TDRC": TDRC, "COMM": COMM, "TRCK": TRCK, "TCON": TCON, } for key in frame_class: if known_frames is not None: if key in known_frames: frame_class[key] = known_frames[key] else: frame_class[key] = None frames = {} if title and frame_class["TIT2"]: frames["TIT2"] = frame_class["TIT2"](encoding=0, text=title) if artist and frame_class["TPE1"]: frames["TPE1"] = frame_class["TPE1"](encoding=0, text=[artist]) if album and frame_class["TALB"]: frames["TALB"] = frame_class["TALB"](encoding=0, text=album) if year: if v2_version == 3 and frame_class["TYER"]: frames["TYER"] = frame_class["TYER"](encoding=0, text=year) elif frame_class["TDRC"]: frames["TDRC"] = frame_class["TDRC"](encoding=0, text=year) if comment and frame_class["COMM"]: frames["COMM"] = frame_class["COMM"]( encoding=0, lang="eng", desc="ID3v1 Comment", text=comment) # Don't read a track number if it looks like the comment was # padded with spaces instead of nulls (thanks, WinAmp). if (track and frame_class["TRCK"] and ((track != 32) or (data[-3] == b'\x00'[0]))): frames["TRCK"] = TRCK(encoding=0, text=str(track)) if genre != 255 and frame_class["TCON"]: frames["TCON"] = TCON(encoding=0, text=str(genre)) return frames
python
def ParseID3v1(data, v2_version=4, known_frames=None): if v2_version not in (3, 4): raise ValueError("Only 3 and 4 possible for v2_version") try: data = data[data.index(b"TAG"):] except ValueError: return None if 128 < len(data) or len(data) < 124: return None # Issue #69 - Previous versions of Mutagen, when encountering # out-of-spec TDRC and TYER frames of less than four characters, # wrote only the characters available - e.g. "1" or "" - into the # year field. To parse those, reduce the size of the year field. # Amazingly, "0s" works as a struct format string. unpack_fmt = "3s30s30s30s%ds29sBB" % (len(data) - 124) try: tag, title, artist, album, year, comment, track, genre = unpack( unpack_fmt, data) except StructError: return None if tag != b"TAG": return None def fix(data): return data.split(b"\x00")[0].strip().decode('latin1') title, artist, album, year, comment = map( fix, [title, artist, album, year, comment]) frame_class = { "TIT2": TIT2, "TPE1": TPE1, "TALB": TALB, "TYER": TYER, "TDRC": TDRC, "COMM": COMM, "TRCK": TRCK, "TCON": TCON, } for key in frame_class: if known_frames is not None: if key in known_frames: frame_class[key] = known_frames[key] else: frame_class[key] = None frames = {} if title and frame_class["TIT2"]: frames["TIT2"] = frame_class["TIT2"](encoding=0, text=title) if artist and frame_class["TPE1"]: frames["TPE1"] = frame_class["TPE1"](encoding=0, text=[artist]) if album and frame_class["TALB"]: frames["TALB"] = frame_class["TALB"](encoding=0, text=album) if year: if v2_version == 3 and frame_class["TYER"]: frames["TYER"] = frame_class["TYER"](encoding=0, text=year) elif frame_class["TDRC"]: frames["TDRC"] = frame_class["TDRC"](encoding=0, text=year) if comment and frame_class["COMM"]: frames["COMM"] = frame_class["COMM"]( encoding=0, lang="eng", desc="ID3v1 Comment", text=comment) # Don't read a track number if it looks like the comment was # padded with spaces instead of nulls (thanks, WinAmp). if (track and frame_class["TRCK"] and ((track != 32) or (data[-3] == b'\x00'[0]))): frames["TRCK"] = TRCK(encoding=0, text=str(track)) if genre != 255 and frame_class["TCON"]: frames["TCON"] = TCON(encoding=0, text=str(genre)) return frames
[ "def", "ParseID3v1", "(", "data", ",", "v2_version", "=", "4", ",", "known_frames", "=", "None", ")", ":", "if", "v2_version", "not", "in", "(", "3", ",", "4", ")", ":", "raise", "ValueError", "(", "\"Only 3 and 4 possible for v2_version\"", ")", "try", ":...
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`]): dict mapping frame IDs to Frame objects
[ "Parse", "an", "ID3v1", "tag", "returning", "a", "list", "of", "ID3v2", "frames" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_id3v1.py#L76-L160
232,329
quodlibet/mutagen
mutagen/id3/_id3v1.py
MakeID3v1
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: text = b"" v1[name] = text + (b"\x00" * (30 - len(text))) if "COMM" in id3: cmnt = id3["COMM"].text[0].encode('latin1', 'replace')[:28] else: cmnt = b"" v1["comment"] = cmnt + (b"\x00" * (29 - len(cmnt))) if "TRCK" in id3: try: v1["track"] = chr_(+id3["TRCK"]) except ValueError: v1["track"] = b"\x00" else: v1["track"] = b"\x00" if "TCON" in id3: try: genre = id3["TCON"].genres[0] except IndexError: pass else: if genre in TCON.GENRES: v1["genre"] = chr_(TCON.GENRES.index(genre)) if "genre" not in v1: v1["genre"] = b"\xff" if "TDRC" in id3: year = text_type(id3["TDRC"]).encode('ascii') elif "TYER" in id3: year = text_type(id3["TYER"]).encode('ascii') else: year = b"" v1["year"] = (year + b"\x00\x00\x00\x00")[:4] return ( b"TAG" + v1["title"] + v1["artist"] + v1["album"] + v1["year"] + v1["comment"] + v1["track"] + v1["genre"] )
python
def MakeID3v1(id3): 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: text = b"" v1[name] = text + (b"\x00" * (30 - len(text))) if "COMM" in id3: cmnt = id3["COMM"].text[0].encode('latin1', 'replace')[:28] else: cmnt = b"" v1["comment"] = cmnt + (b"\x00" * (29 - len(cmnt))) if "TRCK" in id3: try: v1["track"] = chr_(+id3["TRCK"]) except ValueError: v1["track"] = b"\x00" else: v1["track"] = b"\x00" if "TCON" in id3: try: genre = id3["TCON"].genres[0] except IndexError: pass else: if genre in TCON.GENRES: v1["genre"] = chr_(TCON.GENRES.index(genre)) if "genre" not in v1: v1["genre"] = b"\xff" if "TDRC" in id3: year = text_type(id3["TDRC"]).encode('ascii') elif "TYER" in id3: year = text_type(id3["TYER"]).encode('ascii') else: year = b"" v1["year"] = (year + b"\x00\x00\x00\x00")[:4] return ( b"TAG" + v1["title"] + v1["artist"] + v1["album"] + v1["year"] + v1["comment"] + v1["track"] + v1["genre"] )
[ "def", "MakeID3v1", "(", "id3", ")", ":", "v1", "=", "{", "}", "for", "v2id", ",", "name", "in", "{", "\"TIT2\"", ":", "\"title\"", ",", "\"TPE1\"", ":", "\"artist\"", ",", "\"TALB\"", ":", "\"album\"", "}", ".", "items", "(", ")", ":", "if", "v2id...
Return an ID3v1.1 tag string from a dict of ID3v2.4 frames.
[ "Return", "an", "ID3v1", ".", "1", "tag", "string", "from", "a", "dict", "of", "ID3v2", ".", "4", "frames", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_id3v1.py#L163-L218
232,330
quodlibet/mutagen
mutagen/oggvorbis.py
OggVorbisInfo._post_tags
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
def _post_tags(self, fileobj): page = OggPage.find_last(fileobj, self.serial, finishing=True) if page is None: raise OggVorbisHeaderError self.length = page.position / float(self.sample_rate)
[ "def", "_post_tags", "(", "self", ",", "fileobj", ")", ":", "page", "=", "OggPage", ".", "find_last", "(", "fileobj", ",", "self", ".", "serial", ",", "finishing", "=", "True", ")", "if", "page", "is", "None", ":", "raise", "OggVorbisHeaderError", "self"...
Raises ogg.error
[ "Raises", "ogg", ".", "error" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/oggvorbis.py#L83-L89
232,331
quodlibet/mutagen
mutagen/aiff.py
IFFChunk.write
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
def write(self, data): if len(data) > self.data_size: raise ValueError self.__fileobj.seek(self.data_offset) self.__fileobj.write(data)
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "len", "(", "data", ")", ">", "self", ".", "data_size", ":", "raise", "ValueError", "self", ".", "__fileobj", ".", "seek", "(", "self", ".", "data_offset", ")", "self", ".", "__fileobj", ".", ...
Write the chunk data
[ "Write", "the", "chunk", "data" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/aiff.py#L104-L111
232,332
quodlibet/mutagen
mutagen/aiff.py
IFFChunk.resize
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
def resize(self, new_data_size): resize_bytes( self.__fileobj, self.data_size, new_data_size, self.data_offset) self._update_size(new_data_size)
[ "def", "resize", "(", "self", ",", "new_data_size", ")", ":", "resize_bytes", "(", "self", ".", "__fileobj", ",", "self", ".", "data_size", ",", "new_data_size", ",", "self", ".", "data_offset", ")", "self", ".", "_update_size", "(", "new_data_size", ")" ]
Resize the file and update the chunk sizes
[ "Resize", "the", "file", "and", "update", "the", "chunk", "sizes" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/aiff.py#L133-L138
232,333
quodlibet/mutagen
mutagen/aiff.py
IFFFile.insert_chunk
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 = IFFChunk(self.__fileobj, self[u'FORM']) self[u'FORM']._update_size(self[u'FORM'].data_size + chunk.size) self.__chunks[id_] = chunk self.__next_offset = chunk.offset + chunk.size
python
def insert_chunk(self, id_): 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 = IFFChunk(self.__fileobj, self[u'FORM']) self[u'FORM']._update_size(self[u'FORM'].data_size + chunk.size) self.__chunks[id_] = chunk self.__next_offset = chunk.offset + chunk.size
[ "def", "insert_chunk", "(", "self", ",", "id_", ")", ":", "assert_valid_chunk_id", "(", "id_", ")", "self", ".", "__fileobj", ".", "seek", "(", "self", ".", "__next_offset", ")", "self", ".", "__fileobj", ".", "write", "(", "pack", "(", "'>4si'", ",", ...
Insert a new chunk at the end of the IFF file
[ "Insert", "a", "new", "chunk", "at", "the", "end", "of", "the", "IFF", "file" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/aiff.py#L200-L212
232,334
quodlibet/mutagen
mutagen/aiff.py
_IFFID3.save
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: data = self._prepare_data( fileobj, chunk.data_offset, chunk.data_size, v2_version, v23_sep, padding) except ID3Error as e: reraise(error, e, sys.exc_info()[2]) new_size = len(data) new_size += new_size % 2 # pad byte assert new_size % 2 == 0 chunk.resize(new_size) data += (new_size - len(data)) * b'\x00' assert new_size == len(data) chunk.write(data)
python
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None): 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: data = self._prepare_data( fileobj, chunk.data_offset, chunk.data_size, v2_version, v23_sep, padding) except ID3Error as e: reraise(error, e, sys.exc_info()[2]) new_size = len(data) new_size += new_size % 2 # pad byte assert new_size % 2 == 0 chunk.resize(new_size) data += (new_size - len(data)) * b'\x00' assert new_size == len(data) chunk.write(data)
[ "def", "save", "(", "self", ",", "filething", "=", "None", ",", "v2_version", "=", "4", ",", "v23_sep", "=", "'/'", ",", "padding", "=", "None", ")", ":", "fileobj", "=", "filething", ".", "fileobj", "iff_file", "=", "IFFFile", "(", "fileobj", ")", "...
Save ID3v2 data to the AIFF file
[ "Save", "ID3v2", "data", "to", "the", "AIFF", "file" ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/aiff.py#L274-L299
232,335
quodlibet/mutagen
mutagen/aiff.py
AIFF.load
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) else: self.tags.filename = self.filename fileobj.seek(0, 0) self.info = AIFFInfo(fileobj)
python
def load(self, filething, **kwargs): fileobj = filething.fileobj try: self.tags = _IFFID3(fileobj, **kwargs) except ID3NoHeaderError: self.tags = None except ID3Error as e: raise error(e) else: self.tags.filename = self.filename fileobj.seek(0, 0) self.info = AIFFInfo(fileobj)
[ "def", "load", "(", "self", ",", "filething", ",", "*", "*", "kwargs", ")", ":", "fileobj", "=", "filething", ".", "fileobj", "try", ":", "self", ".", "tags", "=", "_IFFID3", "(", "fileobj", ",", "*", "*", "kwargs", ")", "except", "ID3NoHeaderError", ...
Load stream and tag information from a file.
[ "Load", "stream", "and", "tag", "information", "from", "a", "file", "." ]
e393df5971ba41ba5a50de9c2c9e7e5484d82c4e
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/aiff.py#L351-L366
232,336
jazzband/sorl-thumbnail
sorl/thumbnail/engines/wand_engine.py
Engine.is_valid_image
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.MissingDelegateError): return False
python
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.MissingDelegateError): return False
[ "def", "is_valid_image", "(", "self", ",", "raw_data", ")", ":", "try", ":", "Image", "(", "blob", "=", "raw_data", ")", "return", "True", "except", "(", "exceptions", ".", "CorruptImageError", ",", "exceptions", ".", "MissingDelegateError", ")", ":", "retur...
Wand library makes sure when opening any image that is fine, when the image is corrupted raises an exception.
[ "Wand", "library", "makes", "sure", "when", "opening", "any", "image", "that", "is", "fine", "when", "the", "image", "is", "corrupted", "raises", "an", "exception", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/wand_engine.py#L18-L28
232,337
jazzband/sorl-thumbnail
sorl/thumbnail/parsers.py
parse_cropbox
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
def parse_cropbox(cropbox): if isinstance(cropbox, six.text_type): return tuple([int(x.strip()) for x in cropbox.split(',')]) else: return tuple(cropbox)
[ "def", "parse_cropbox", "(", "cropbox", ")", ":", "if", "isinstance", "(", "cropbox", ",", "six", ".", "text_type", ")", ":", "return", "tuple", "(", "[", "int", "(", "x", ".", "strip", "(", ")", ")", "for", "x", "in", "cropbox", ".", "split", "(",...
Returns x, y, x2, y2 tuple for cropping.
[ "Returns", "x", "y", "x2", "y2", "tuple", "for", "cropping", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/parsers.py#L99-L106
232,338
jazzband/sorl-thumbnail
sorl/thumbnail/engines/convert_engine.py
Engine.get_image
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
def get_image(self, source): with NamedTemporaryFile(mode='wb', delete=False) as fp: fp.write(source.read()) return {'source': fp.name, 'options': OrderedDict(), 'size': None}
[ "def", "get_image", "(", "self", ",", "source", ")", ":", "with", "NamedTemporaryFile", "(", "mode", "=", "'wb'", ",", "delete", "=", "False", ")", "as", "fp", ":", "fp", ".", "write", "(", "source", ".", "read", "(", ")", ")", "return", "{", "'sou...
Returns the backend image objects from a ImageFile instance
[ "Returns", "the", "backend", "image", "objects", "from", "a", "ImageFile", "instance" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/convert_engine.py#L74-L80
232,339
jazzband/sorl-thumbnail
sorl/thumbnail/engines/convert_engine.py
Engine.is_valid_image
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_IDENTIFY.split(' ') args.append(fp.name + '[0]') p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = p.wait() return retcode == 0
python
def is_valid_image(self, raw_data): with NamedTemporaryFile(mode='wb') as fp: fp.write(raw_data) fp.flush() args = settings.THUMBNAIL_IDENTIFY.split(' ') args.append(fp.name + '[0]') p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = p.wait() return retcode == 0
[ "def", "is_valid_image", "(", "self", ",", "raw_data", ")", ":", "with", "NamedTemporaryFile", "(", "mode", "=", "'wb'", ")", "as", "fp", ":", "fp", ".", "write", "(", "raw_data", ")", "fp", ".", "flush", "(", ")", "args", "=", "settings", ".", "THUM...
This is not very good for imagemagick because it will say anything is valid that it can use as input.
[ "This", "is", "not", "very", "good", "for", "imagemagick", "because", "it", "will", "say", "anything", "is", "valid", "that", "it", "can", "use", "as", "input", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/convert_engine.py#L95-L107
232,340
jazzband/sorl-thumbnail
sorl/thumbnail/engines/convert_engine.py
Engine._crop
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
def _crop(self, image, width, height, x_offset, y_offset): image['options']['crop'] = '%sx%s+%s+%s' % (width, height, x_offset, y_offset) image['size'] = (width, height) # update image size return image
[ "def", "_crop", "(", "self", ",", "image", ",", "width", ",", "height", ",", "x_offset", ",", "y_offset", ")", ":", "image", "[", "'options'", "]", "[", "'crop'", "]", "=", "'%sx%s+%s+%s'", "%", "(", "width", ",", "height", ",", "x_offset", ",", "y_o...
Crops the image
[ "Crops", "the", "image" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/convert_engine.py#L166-L172
232,341
jazzband/sorl-thumbnail
sorl/thumbnail/engines/convert_engine.py
Engine._scale
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
def _scale(self, image, width, height): image['options']['scale'] = '%sx%s!' % (width, height) image['size'] = (width, height) # update image size return image
[ "def", "_scale", "(", "self", ",", "image", ",", "width", ",", "height", ")", ":", "image", "[", "'options'", "]", "[", "'scale'", "]", "=", "'%sx%s!'", "%", "(", "width", ",", "height", ")", "image", "[", "'size'", "]", "=", "(", "width", ",", "...
Does the resizing of the image
[ "Does", "the", "resizing", "of", "the", "image" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/convert_engine.py#L182-L188
232,342
jazzband/sorl-thumbnail
sorl/thumbnail/engines/convert_engine.py
Engine._padding
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']['extent'] = '%sx%s' % (geometry[0], geometry[1]) return image
python
def _padding(self, image, geometry, options): # The order is important. The gravity option should come before extent. image['options']['background'] = options.get('padding_color') image['options']['gravity'] = 'center' image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1]) return image
[ "def", "_padding", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "# The order is important. The gravity option should come before extent.", "image", "[", "'options'", "]", "[", "'background'", "]", "=", "options", ".", "get", "(", "'padding_c...
Pads the image
[ "Pads", "the", "image" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/convert_engine.py#L190-L198
232,343
jazzband/sorl-thumbnail
sorl/thumbnail/helpers.py
tokey
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
def tokey(*args): salt = '||'.join([force_text(arg) for arg in args]) hash_ = hashlib.md5(encode(salt)) return hash_.hexdigest()
[ "def", "tokey", "(", "*", "args", ")", ":", "salt", "=", "'||'", ".", "join", "(", "[", "force_text", "(", "arg", ")", "for", "arg", "in", "args", "]", ")", "hash_", "=", "hashlib", ".", "md5", "(", "encode", "(", "salt", ")", ")", "return", "h...
Computes a unique key from arguments given.
[ "Computes", "a", "unique", "key", "from", "arguments", "given", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/helpers.py#L42-L48
232,344
jazzband/sorl-thumbnail
sorl/thumbnail/helpers.py
get_module_class
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: "%s"' % (mod_name, e))) return getattr(mod, cls_name)
python
def get_module_class(class_path): mod_name, cls_name = class_path.rsplit('.', 1) try: mod = import_module(mod_name) except ImportError as e: raise ImproperlyConfigured(('Error importing module %s: "%s"' % (mod_name, e))) return getattr(mod, cls_name)
[ "def", "get_module_class", "(", "class_path", ")", ":", "mod_name", ",", "cls_name", "=", "class_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "mod", "=", "import_module", "(", "mod_name", ")", "except", "ImportError", "as", "e", ":", "rai...
imports and returns module class from ``path.to.module.Class`` argument
[ "imports", "and", "returns", "module", "class", "from", "path", ".", "to", ".", "module", ".", "Class", "argument" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/helpers.py#L61-L73
232,345
jazzband/sorl-thumbnail
sorl/thumbnail/shortcuts.py
get_thumbnail
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
def get_thumbnail(file_, geometry_string, **options): return default.backend.get_thumbnail(file_, geometry_string, **options)
[ "def", "get_thumbnail", "(", "file_", ",", "geometry_string", ",", "*", "*", "options", ")", ":", "return", "default", ".", "backend", ".", "get_thumbnail", "(", "file_", ",", "geometry_string", ",", "*", "*", "options", ")" ]
A shortcut for the Backend ``get_thumbnail`` method
[ "A", "shortcut", "for", "the", "Backend", "get_thumbnail", "method" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/shortcuts.py#L4-L8
232,346
jazzband/sorl-thumbnail
sorl/thumbnail/templatetags/thumbnail.py
safe_filter
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) except Exception as err: if sorl_settings.THUMBNAIL_DEBUG: raise logger.error('Thumbnail filter failed: %s' % str(err), exc_info=sys.exc_info()) return error_output return wrapper return inner
python
def safe_filter(error_output=''): def inner(f): @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Exception as err: if sorl_settings.THUMBNAIL_DEBUG: raise logger.error('Thumbnail filter failed: %s' % str(err), exc_info=sys.exc_info()) return error_output return wrapper return inner
[ "def", "safe_filter", "(", "error_output", "=", "''", ")", ":", "def", "inner", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "*", "args",...
A safe filter decorator only raising errors when ``THUMBNAIL_DEBUG`` is ``True`` otherwise returning ``error_output``.
[ "A", "safe", "filter", "decorator", "only", "raising", "errors", "when", "THUMBNAIL_DEBUG", "is", "True", "otherwise", "returning", "error_output", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/templatetags/thumbnail.py#L28-L48
232,347
jazzband/sorl-thumbnail
sorl/thumbnail/templatetags/thumbnail.py
resolution
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 = source.replace('%(height)s', '(?P<height>[0-9]+)') source = re.compile(source) try: resolution = decimal.Decimal(resolution_string.strip('x')) info = source.match(file_).groupdict() info = {dimension: int(int(size) * resolution) for (dimension, size) in info.items()} return dummy_source % info except (AttributeError, TypeError, KeyError): # If we can't manipulate the dummy we shouldn't change it at all return file_ filename, extension = os.path.splitext(file_) return '%s@%s%s' % (filename, resolution_string, extension)
python
def resolution(file_, resolution_string): if sorl_settings.THUMBNAIL_DUMMY: dummy_source = sorl_settings.THUMBNAIL_DUMMY_SOURCE source = dummy_source.replace('%(width)s', '(?P<width>[0-9]+)') source = source.replace('%(height)s', '(?P<height>[0-9]+)') source = re.compile(source) try: resolution = decimal.Decimal(resolution_string.strip('x')) info = source.match(file_).groupdict() info = {dimension: int(int(size) * resolution) for (dimension, size) in info.items()} return dummy_source % info except (AttributeError, TypeError, KeyError): # If we can't manipulate the dummy we shouldn't change it at all return file_ filename, extension = os.path.splitext(file_) return '%s@%s%s' % (filename, resolution_string, extension)
[ "def", "resolution", "(", "file_", ",", "resolution_string", ")", ":", "if", "sorl_settings", ".", "THUMBNAIL_DUMMY", ":", "dummy_source", "=", "sorl_settings", ".", "THUMBNAIL_DUMMY_SOURCE", "source", "=", "dummy_source", ".", "replace", "(", "'%(width)s'", ",", ...
A filter to return the URL for the provided resolution of the thumbnail.
[ "A", "filter", "to", "return", "the", "URL", "for", "the", "provided", "resolution", "of", "the", "thumbnail", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/templatetags/thumbnail.py#L171-L190
232,348
jazzband/sorl-thumbnail
sorl/thumbnail/templatetags/thumbnail.py
is_portrait
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 image_file.is_portrait()
python
def is_portrait(file_): 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 image_file.is_portrait()
[ "def", "is_portrait", "(", "file_", ")", ":", "if", "sorl_settings", ".", "THUMBNAIL_DUMMY", ":", "return", "sorl_settings", ".", "THUMBNAIL_DUMMY_RATIO", "<", "1", "if", "not", "file_", ":", "return", "False", "image_file", "=", "default", ".", "kvstore", "."...
A very handy filter to determine if an image is portrait or landscape.
[ "A", "very", "handy", "filter", "to", "determine", "if", "an", "image", "is", "portrait", "or", "landscape", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/templatetags/thumbnail.py#L200-L209
232,349
jazzband/sorl-thumbnail
sorl/thumbnail/templatetags/thumbnail.py
margin
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_)) x, y = parse_geometry(geometry_string, image_file.ratio) ex = x - image_file.x margin[3] = ex / 2 margin[1] = ex / 2 if ex % 2: margin[1] += 1 ey = y - image_file.y margin[0] = ey / 2 margin[2] = ey / 2 if ey % 2: margin[2] += 1 return ' '.join(['%dpx' % n for n in margin])
python
def margin(file_, geometry_string): 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_)) x, y = parse_geometry(geometry_string, image_file.ratio) ex = x - image_file.x margin[3] = ex / 2 margin[1] = ex / 2 if ex % 2: margin[1] += 1 ey = y - image_file.y margin[0] = ey / 2 margin[2] = ey / 2 if ey % 2: margin[2] += 1 return ' '.join(['%dpx' % n for n in margin])
[ "def", "margin", "(", "file_", ",", "geometry_string", ")", ":", "if", "not", "file_", "or", "(", "sorl_settings", ".", "THUMBNAIL_DUMMY", "or", "isinstance", "(", "file_", ",", "DummyImageFile", ")", ")", ":", "return", "'auto'", "margin", "=", "[", "0", ...
Returns the calculated margin for an image and geometry
[ "Returns", "the", "calculated", "margin", "for", "an", "image", "and", "geometry" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/templatetags/thumbnail.py#L214-L241
232,350
jazzband/sorl-thumbnail
sorl/thumbnail/templatetags/thumbnail.py
text_filter
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: image = i[1] if image.startswith(settings.MEDIA_URL): image = image[len(settings.MEDIA_URL):] im = get_thumbnail(image, str(sorl_settings.THUMBNAIL_FILTER_WIDTH)) value = value.replace(i[1], im.url) return value
python
def text_filter(regex_base, value): 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: image = i[1] if image.startswith(settings.MEDIA_URL): image = image[len(settings.MEDIA_URL):] im = get_thumbnail(image, str(sorl_settings.THUMBNAIL_FILTER_WIDTH)) value = value.replace(i[1], im.url) return value
[ "def", "text_filter", "(", "regex_base", ",", "value", ")", ":", "regex", "=", "regex_base", "%", "{", "'re_cap'", ":", "r'[a-zA-Z0-9\\.\\,:;/_ \\(\\)\\-\\!\\?\"]+'", ",", "'re_img'", ":", "r'[a-zA-Z0-9\\.:/_\\-\\% ]+'", "}", "images", "=", "re", ".", "findall", "...
Helper method to regex replace images with captions in different markups
[ "Helper", "method", "to", "regex", "replace", "images", "with", "captions", "in", "different", "markups" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/templatetags/thumbnail.py#L264-L282
232,351
jazzband/sorl-thumbnail
sorl/thumbnail/fields.py
ImageField.delete_file
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 the file, and it's not the # default value for future objects, delete it from the backend. query = Q(**{self.name: file_.name}) & ~Q(pk=instance.pk) qs = sender._default_manager.filter(query) if (file_ and file_.name != self.default and not qs): default.backend.delete(file_) elif file_: # Otherwise, just close the file, so it doesn't tie up resources. file_.close()
python
def delete_file(self, instance, sender, **kwargs): file_ = getattr(instance, self.attname) # If no other object of this type references the file, and it's not the # default value for future objects, delete it from the backend. query = Q(**{self.name: file_.name}) & ~Q(pk=instance.pk) qs = sender._default_manager.filter(query) if (file_ and file_.name != self.default and not qs): default.backend.delete(file_) elif file_: # Otherwise, just close the file, so it doesn't tie up resources. file_.close()
[ "def", "delete_file", "(", "self", ",", "instance", ",", "sender", ",", "*", "*", "kwargs", ")", ":", "file_", "=", "getattr", "(", "instance", ",", "self", ".", "attname", ")", "# If no other object of this type references the file, and it's not the", "# default va...
Adds deletion of thumbnails and key value store references to the parent class implementation. Only called in Django < 1.2.5
[ "Adds", "deletion", "of", "thumbnails", "and", "key", "value", "store", "references", "to", "the", "parent", "class", "implementation", ".", "Only", "called", "in", "Django", "<", "1", ".", "2", ".", "5" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/fields.py#L15-L31
232,352
jazzband/sorl-thumbnail
sorl/thumbnail/engines/vipsthumbnail_engine.py
Engine.get_image_size
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=subprocess.PIPE) p.wait() m = size_re.match(str(p.stdout.read())) image['size'] = int(m.group('x')), int(m.group('y')) return image['size']
python
def get_image_size(self, image): if image['size'] is None: args = settings.THUMBNAIL_VIPSHEADER.split(' ') args.append(image['source']) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() m = size_re.match(str(p.stdout.read())) image['size'] = int(m.group('x')), int(m.group('y')) return image['size']
[ "def", "get_image_size", "(", "self", ",", "image", ")", ":", "if", "image", "[", "'size'", "]", "is", "None", ":", "args", "=", "settings", ".", "THUMBNAIL_VIPSHEADER", ".", "split", "(", "' '", ")", "args", ".", "append", "(", "image", "[", "'source'...
Returns the image width and height as a tuple
[ "Returns", "the", "image", "width", "and", "height", "as", "a", "tuple" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/vipsthumbnail_engine.py#L75-L86
232,353
jazzband/sorl-thumbnail
sorl/thumbnail/base.py
ThumbnailBackend.get_thumbnail
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 file [%s] at [%s]', file_, geometry_string) if file_: source = ImageFile(file_) else: raise ValueError('falsey file_ argument in get_thumbnail()') # preserve image filetype if settings.THUMBNAIL_PRESERVE_FORMAT: options.setdefault('format', self._get_format(source)) for key, value in self.default_options.items(): options.setdefault(key, value) # For the future I think it is better to add options only if they # differ from the default settings as below. This will ensure the same # filenames being generated for new options at default. for key, attr in self.extra_options: value = getattr(settings, attr) if value != getattr(default_settings, attr): options.setdefault(key, value) name = self._get_thumbnail_filename(source, geometry_string, options) thumbnail = ImageFile(name, default.storage) cached = default.kvstore.get(thumbnail) if cached: return cached # We have to check exists() because the Storage backend does not # overwrite in some implementations. if settings.THUMBNAIL_FORCE_OVERWRITE or not thumbnail.exists(): try: source_image = default.engine.get_image(source) except IOError as e: logger.exception(e) if settings.THUMBNAIL_DUMMY: return DummyImageFile(geometry_string) else: # if S3Storage says file doesn't exist remotely, don't try to # create it and exit early. # Will return working empty image type; 404'd image logger.warning( 'Remote file [%s] at [%s] does not exist', file_, geometry_string, ) return thumbnail # We might as well set the size since we have the image in memory image_info = default.engine.get_image_info(source_image) options['image_info'] = image_info size = default.engine.get_image_size(source_image) source.set_size(size) try: self._create_thumbnail(source_image, geometry_string, options, thumbnail) self._create_alternative_resolutions(source_image, geometry_string, options, thumbnail.name) finally: default.engine.cleanup(source_image) # If the thumbnail exists we don't create it, the other option is # to delete and write but this could lead to race conditions so I # will just leave that out for now. default.kvstore.get_or_set(source) default.kvstore.set(thumbnail, source) return thumbnail
python
def get_thumbnail(self, file_, geometry_string, **options): logger.debug('Getting thumbnail for file [%s] at [%s]', file_, geometry_string) if file_: source = ImageFile(file_) else: raise ValueError('falsey file_ argument in get_thumbnail()') # preserve image filetype if settings.THUMBNAIL_PRESERVE_FORMAT: options.setdefault('format', self._get_format(source)) for key, value in self.default_options.items(): options.setdefault(key, value) # For the future I think it is better to add options only if they # differ from the default settings as below. This will ensure the same # filenames being generated for new options at default. for key, attr in self.extra_options: value = getattr(settings, attr) if value != getattr(default_settings, attr): options.setdefault(key, value) name = self._get_thumbnail_filename(source, geometry_string, options) thumbnail = ImageFile(name, default.storage) cached = default.kvstore.get(thumbnail) if cached: return cached # We have to check exists() because the Storage backend does not # overwrite in some implementations. if settings.THUMBNAIL_FORCE_OVERWRITE or not thumbnail.exists(): try: source_image = default.engine.get_image(source) except IOError as e: logger.exception(e) if settings.THUMBNAIL_DUMMY: return DummyImageFile(geometry_string) else: # if S3Storage says file doesn't exist remotely, don't try to # create it and exit early. # Will return working empty image type; 404'd image logger.warning( 'Remote file [%s] at [%s] does not exist', file_, geometry_string, ) return thumbnail # We might as well set the size since we have the image in memory image_info = default.engine.get_image_info(source_image) options['image_info'] = image_info size = default.engine.get_image_size(source_image) source.set_size(size) try: self._create_thumbnail(source_image, geometry_string, options, thumbnail) self._create_alternative_resolutions(source_image, geometry_string, options, thumbnail.name) finally: default.engine.cleanup(source_image) # If the thumbnail exists we don't create it, the other option is # to delete and write but this could lead to race conditions so I # will just leave that out for now. default.kvstore.get_or_set(source) default.kvstore.set(thumbnail, source) return thumbnail
[ "def", "get_thumbnail", "(", "self", ",", "file_", ",", "geometry_string", ",", "*", "*", "options", ")", ":", "logger", ".", "debug", "(", "'Getting thumbnail for file [%s] at [%s]'", ",", "file_", ",", "geometry_string", ")", "if", "file_", ":", "source", "=...
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.
[ "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...
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/base.py#L69-L142
232,354
jazzband/sorl-thumbnail
sorl/thumbnail/base.py
ThumbnailBackend.delete
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
def delete(self, file_, delete_file=True): image_file = ImageFile(file_) if delete_file: image_file.delete() default.kvstore.delete(image_file)
[ "def", "delete", "(", "self", ",", "file_", ",", "delete_file", "=", "True", ")", ":", "image_file", "=", "ImageFile", "(", "file_", ")", "if", "delete_file", ":", "image_file", ".", "delete", "(", ")", "default", ".", "kvstore", ".", "delete", "(", "i...
Deletes file_ references in Key Value store and optionally the file_ it self.
[ "Deletes", "file_", "references", "in", "Key", "Value", "store", "and", "optionally", "the", "file_", "it", "self", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/base.py#L144-L152
232,355
jazzband/sorl-thumbnail
sorl/thumbnail/base.py
ThumbnailBackend._create_thumbnail
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) ratio = default.engine.get_image_ratio(source_image, options) geometry = parse_geometry(geometry_string, ratio) image = default.engine.create(source_image, geometry, options) default.engine.write(image, options, thumbnail) # It's much cheaper to set the size here size = default.engine.get_image_size(image) thumbnail.set_size(size)
python
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail): logger.debug('Creating thumbnail file [%s] at [%s] with [%s]', thumbnail.name, geometry_string, options) ratio = default.engine.get_image_ratio(source_image, options) geometry = parse_geometry(geometry_string, ratio) image = default.engine.create(source_image, geometry, options) default.engine.write(image, options, thumbnail) # It's much cheaper to set the size here size = default.engine.get_image_size(image) thumbnail.set_size(size)
[ "def", "_create_thumbnail", "(", "self", ",", "source_image", ",", "geometry_string", ",", "options", ",", "thumbnail", ")", ":", "logger", ".", "debug", "(", "'Creating thumbnail file [%s] at [%s] with [%s]'", ",", "thumbnail", ".", "name", ",", "geometry_string", ...
Creates the thumbnail by using default.engine
[ "Creates", "the", "thumbnail", "by", "using", "default", ".", "engine" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/base.py#L154-L167
232,356
jazzband/sorl-thumbnail
sorl/thumbnail/base.py
ThumbnailBackend._create_alternative_resolutions
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_ratio(source_image, options) geometry = parse_geometry(geometry_string, ratio) file_name, dot_file_ext = os.path.splitext(name) for resolution in settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS: resolution_geometry = (int(geometry[0] * resolution), int(geometry[1] * resolution)) resolution_options = options.copy() if 'crop' in options and isinstance(options['crop'], string_types): crop = options['crop'].split(" ") for i in range(len(crop)): s = re.match(r"(\d+)px", crop[i]) if s: crop[i] = "%spx" % int(int(s.group(1)) * resolution) resolution_options['crop'] = " ".join(crop) image = default.engine.create(source_image, resolution_geometry, options) thumbnail_name = '%(file_name)s%(suffix)s%(file_ext)s' % { 'file_name': file_name, 'suffix': '@%sx' % resolution, 'file_ext': dot_file_ext } thumbnail = ImageFile(thumbnail_name, default.storage) default.engine.write(image, resolution_options, thumbnail) size = default.engine.get_image_size(image) thumbnail.set_size(size)
python
def _create_alternative_resolutions(self, source_image, geometry_string, options, name): ratio = default.engine.get_image_ratio(source_image, options) geometry = parse_geometry(geometry_string, ratio) file_name, dot_file_ext = os.path.splitext(name) for resolution in settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS: resolution_geometry = (int(geometry[0] * resolution), int(geometry[1] * resolution)) resolution_options = options.copy() if 'crop' in options and isinstance(options['crop'], string_types): crop = options['crop'].split(" ") for i in range(len(crop)): s = re.match(r"(\d+)px", crop[i]) if s: crop[i] = "%spx" % int(int(s.group(1)) * resolution) resolution_options['crop'] = " ".join(crop) image = default.engine.create(source_image, resolution_geometry, options) thumbnail_name = '%(file_name)s%(suffix)s%(file_ext)s' % { 'file_name': file_name, 'suffix': '@%sx' % resolution, 'file_ext': dot_file_ext } thumbnail = ImageFile(thumbnail_name, default.storage) default.engine.write(image, resolution_options, thumbnail) size = default.engine.get_image_size(image) thumbnail.set_size(size)
[ "def", "_create_alternative_resolutions", "(", "self", ",", "source_image", ",", "geometry_string", ",", "options", ",", "name", ")", ":", "ratio", "=", "default", ".", "engine", ".", "get_image_ratio", "(", "source_image", ",", "options", ")", "geometry", "=", ...
Creates the thumbnail by using default.engine with multiple output sizes. Appends @<ratio>x to the file name.
[ "Creates", "the", "thumbnail", "by", "using", "default", ".", "engine", "with", "multiple", "output", "sizes", ".", "Appends" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/base.py#L169-L199
232,357
jazzband/sorl-thumbnail
sorl/thumbnail/base.py
ThumbnailBackend._get_thumbnail_filename
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' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
python
def _get_thumbnail_filename(self, source, geometry_string, options): 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' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
[ "def", "_get_thumbnail_filename", "(", "self", ",", "source", ",", "geometry_string", ",", "options", ")", ":", "key", "=", "tokey", "(", "source", ".", "key", ",", "geometry_string", ",", "serialize", "(", "options", ")", ")", "# make some subdirs", "path", ...
Computes the destination filename.
[ "Computes", "the", "destination", "filename", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/base.py#L201-L208
232,358
jazzband/sorl-thumbnail
sorl/thumbnail/engines/pil_engine.py
round_corner
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
def round_corner(radius, fill): 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
[ "def", "round_corner", "(", "radius", ",", "fill", ")", ":", "corner", "=", "Image", ".", "new", "(", "'L'", ",", "(", "radius", ",", "radius", ")", ",", "0", ")", "# (0, 0, 0, 0))", "draw", "=", "ImageDraw", ".", "Draw", "(", "corner", ")", "draw", ...
Draw a round corner
[ "Draw", "a", "round", "corner" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/pil_engine.py#L17-L22
232,359
jazzband/sorl-thumbnail
sorl/thumbnail/engines/pil_engine.py
round_rectangle
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)) # Rotate the corner and paste it rectangle.paste(corner.rotate(180), (width - radius, height - radius)) rectangle.paste(corner.rotate(270), (width - radius, 0)) return rectangle
python
def round_rectangle(size, radius, fill): 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)) # Rotate the corner and paste it rectangle.paste(corner.rotate(180), (width - radius, height - radius)) rectangle.paste(corner.rotate(270), (width - radius, 0)) return rectangle
[ "def", "round_rectangle", "(", "size", ",", "radius", ",", "fill", ")", ":", "width", ",", "height", "=", "size", "rectangle", "=", "Image", ".", "new", "(", "'L'", ",", "size", ",", "255", ")", "# fill", "corner", "=", "round_corner", "(", "radius", ...
Draw a rounded rectangle
[ "Draw", "a", "rounded", "rectangle" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/pil_engine.py#L25-L35
232,360
jazzband/sorl-thumbnail
sorl/thumbnail/engines/pil_engine.py
Engine._get_image_entropy
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
def _get_image_entropy(self, 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])
[ "def", "_get_image_entropy", "(", "self", ",", "image", ")", ":", "hist", "=", "image", ".", "histogram", "(", ")", "hist_size", "=", "sum", "(", "hist", ")", "hist", "=", "[", "float", "(", "h", ")", "/", "hist_size", "for", "h", "in", "hist", "]"...
calculate the entropy of an image
[ "calculate", "the", "entropy", "of", "an", "image" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/pil_engine.py#L265-L270
232,361
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.create
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) image = self.remove_border(image, options) image = self.scale(image, geometry, options) image = self.crop(image, geometry, options) image = self.rounded(image, geometry, options) image = self.blur(image, geometry, options) image = self.padding(image, geometry, options) return image
python
def create(self, image, geometry, options): image = self.cropbox(image, geometry, options) image = self.orientation(image, geometry, options) image = self.colorspace(image, geometry, options) image = self.remove_border(image, options) image = self.scale(image, geometry, options) image = self.crop(image, geometry, options) image = self.rounded(image, geometry, options) image = self.blur(image, geometry, options) image = self.padding(image, geometry, options) return image
[ "def", "create", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "image", "=", "self", ".", "cropbox", "(", "image", ",", "geometry", ",", "options", ")", "image", "=", "self", ".", "orientation", "(", "image", ",", "geometry", ...
Processing conductor, returns the thumbnail as an image engine instance
[ "Processing", "conductor", "returns", "the", "thumbnail", "as", "an", "image", "engine", "instance" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L15-L28
232,362
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.cropbox
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
def cropbox(self, image, geometry, options): cropbox = options['cropbox'] if not cropbox: return image x, y, x2, y2 = parse_cropbox(cropbox) return self._cropbox(image, x, y, x2, y2)
[ "def", "cropbox", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "cropbox", "=", "options", "[", "'cropbox'", "]", "if", "not", "cropbox", ":", "return", "image", "x", ",", "y", ",", "x2", ",", "y2", "=", "parse_cropbox", "(", ...
Wrapper for ``_cropbox``
[ "Wrapper", "for", "_cropbox" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L30-L38
232,363
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.orientation
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
def orientation(self, image, geometry, options): if options.get('orientation', settings.THUMBNAIL_ORIENTATION): return self._orientation(image) self.reoriented = True return image
[ "def", "orientation", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "if", "options", ".", "get", "(", "'orientation'", ",", "settings", ".", "THUMBNAIL_ORIENTATION", ")", ":", "return", "self", ".", "_orientation", "(", "image", ")"...
Wrapper for ``_orientation``
[ "Wrapper", "for", "_orientation" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L40-L47
232,364
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.colorspace
def colorspace(self, image, geometry, options): """ Wrapper for ``_colorspace`` """ colorspace = options['colorspace'] return self._colorspace(image, colorspace)
python
def colorspace(self, image, geometry, options): colorspace = options['colorspace'] return self._colorspace(image, colorspace)
[ "def", "colorspace", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "colorspace", "=", "options", "[", "'colorspace'", "]", "return", "self", ".", "_colorspace", "(", "image", ",", "colorspace", ")" ]
Wrapper for ``_colorspace``
[ "Wrapper", "for", "_colorspace" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L56-L61
232,365
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.scale
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: width = toint(x_image * factor) height = toint(y_image * factor) image = self._scale(image, width, height) return image
python
def scale(self, image, geometry, options): 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: width = toint(x_image * factor) height = toint(y_image * factor) image = self._scale(image, width, height) return image
[ "def", "scale", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "upscale", "=", "options", "[", "'upscale'", "]", "x_image", ",", "y_image", "=", "map", "(", "float", ",", "self", ".", "get_image_size", "(", "image", ")", ")", "...
Wrapper for ``_scale``
[ "Wrapper", "for", "_scale" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L76-L89
232,366
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.crop
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 different from regular cropping # to warrent it's own function return self._entropy_crop(image, geometry[0], geometry[1], x_image, y_image) # Handle any other crop option with the backend crop function. geometry = (min(x_image, geometry[0]), min(y_image, geometry[1])) x_offset, y_offset = parse_crop(crop, (x_image, y_image), geometry) return self._crop(image, geometry[0], geometry[1], x_offset, y_offset)
python
def crop(self, image, geometry, options): 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 different from regular cropping # to warrent it's own function return self._entropy_crop(image, geometry[0], geometry[1], x_image, y_image) # Handle any other crop option with the backend crop function. geometry = (min(x_image, geometry[0]), min(y_image, geometry[1])) x_offset, y_offset = parse_crop(crop, (x_image, y_image), geometry) return self._crop(image, geometry[0], geometry[1], x_offset, y_offset)
[ "def", "crop", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "crop", "=", "options", "[", "'crop'", "]", "x_image", ",", "y_image", "=", "self", ".", "get_image_size", "(", "image", ")", "if", "not", "crop", "or", "crop", "=="...
Wrapper for ``_crop``
[ "Wrapper", "for", "_crop" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L91-L108
232,367
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.rounded
def rounded(self, image, geometry, options): """ Wrapper for ``_rounded`` """ r = options['rounded'] if not r: return image return self._rounded(image, int(r))
python
def rounded(self, image, geometry, options): r = options['rounded'] if not r: return image return self._rounded(image, int(r))
[ "def", "rounded", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "r", "=", "options", "[", "'rounded'", "]", "if", "not", "r", ":", "return", "image", "return", "self", ".", "_rounded", "(", "image", ",", "int", "(", "r", ")"...
Wrapper for ``_rounded``
[ "Wrapper", "for", "_rounded" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L110-L117
232,368
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.blur
def blur(self, image, geometry, options): """ Wrapper for ``_blur`` """ if options.get('blur'): return self._blur(image, int(options.get('blur'))) return image
python
def blur(self, image, geometry, options): if options.get('blur'): return self._blur(image, int(options.get('blur'))) return image
[ "def", "blur", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "if", "options", ".", "get", "(", "'blur'", ")", ":", "return", "self", ".", "_blur", "(", "image", ",", "int", "(", "options", ".", "get", "(", "'blur'", ")", "...
Wrapper for ``_blur``
[ "Wrapper", "for", "_blur" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L119-L125
232,369
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.padding
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
def padding(self, image, geometry, options): if options.get('padding') and self.get_image_size(image) != geometry: return self._padding(image, geometry, options) return image
[ "def", "padding", "(", "self", ",", "image", ",", "geometry", ",", "options", ")", ":", "if", "options", ".", "get", "(", "'padding'", ")", "and", "self", ".", "get_image_size", "(", "image", ")", "!=", "geometry", ":", "return", "self", ".", "_padding...
Wrapper for ``_padding``
[ "Wrapper", "for", "_padding" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L127-L133
232,370
jazzband/sorl-thumbnail
sorl/thumbnail/engines/base.py
EngineBase.get_image_ratio
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 else: x, y = self.get_image_size(image) return float(x) / y
python
def get_image_ratio(self, image, options): cropbox = options['cropbox'] if cropbox: x, y, x2, y2 = parse_cropbox(cropbox) x = x2 - x y = y2 - y else: x, y = self.get_image_size(image) return float(x) / y
[ "def", "get_image_ratio", "(", "self", ",", "image", ",", "options", ")", ":", "cropbox", "=", "options", "[", "'cropbox'", "]", "if", "cropbox", ":", "x", ",", "y", ",", "x2", ",", "y2", "=", "parse_cropbox", "(", "cropbox", ")", "x", "=", "x2", "...
Calculates the image ratio. If cropbox option is used, the ratio may have changed.
[ "Calculates", "the", "image", "ratio", ".", "If", "cropbox", "option", "is", "used", "the", "ratio", "may", "have", "changed", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/base.py#L155-L169
232,371
jazzband/sorl-thumbnail
sorl/thumbnail/kvstores/base.py
KVStoreBase.set
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.get(source): # make sure the source is in kvstore raise ThumbnailError('Cannot add thumbnails for source: `%s` ' 'that is not in kvstore.' % source.name) # Update the list of thumbnails for source. thumbnails = self._get(source.key, identity='thumbnails') or [] thumbnails = set(thumbnails) thumbnails.add(image_file.key) self._set(source.key, list(thumbnails), identity='thumbnails')
python
def set(self, image_file, source=None): 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.get(source): # make sure the source is in kvstore raise ThumbnailError('Cannot add thumbnails for source: `%s` ' 'that is not in kvstore.' % source.name) # Update the list of thumbnails for source. thumbnails = self._get(source.key, identity='thumbnails') or [] thumbnails = set(thumbnails) thumbnails.add(image_file.key) self._set(source.key, list(thumbnails), identity='thumbnails')
[ "def", "set", "(", "self", ",", "image_file", ",", "source", "=", "None", ")", ":", "image_file", ".", "set_size", "(", ")", "# make sure its got a size", "self", ".", "_set", "(", "image_file", ".", "key", ",", "image_file", ")", "if", "source", "is", "...
Updates store for the `image_file`. Makes sure the `image_file` has a size set.
[ "Updates", "store", "for", "the", "image_file", ".", "Makes", "sure", "the", "image_file", "has", "a", "size", "set", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/kvstores/base.py#L28-L46
232,372
jazzband/sorl-thumbnail
sorl/thumbnail/kvstores/base.py
KVStoreBase.delete
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_thumbnails: self.delete_thumbnails(image_file) self._delete(image_file.key)
python
def delete(self, image_file, delete_thumbnails=True): if delete_thumbnails: self.delete_thumbnails(image_file) self._delete(image_file.key)
[ "def", "delete", "(", "self", ",", "image_file", ",", "delete_thumbnails", "=", "True", ")", ":", "if", "delete_thumbnails", ":", "self", ".", "delete_thumbnails", "(", "image_file", ")", "self", ".", "_delete", "(", "image_file", ".", "key", ")" ]
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.
[ "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", "se...
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/kvstores/base.py#L55-L63
232,373
jazzband/sorl-thumbnail
sorl/thumbnail/kvstores/base.py
KVStoreBase.delete_thumbnails
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 # thumbnail ImageFiles. for key in thumbnail_keys: thumbnail = self._get(key) if thumbnail: self.delete(thumbnail, False) thumbnail.delete() # delete the actual file # Delete the thumbnails key from store self._delete(image_file.key, identity='thumbnails')
python
def delete_thumbnails(self, image_file): thumbnail_keys = self._get(image_file.key, identity='thumbnails') if thumbnail_keys: # Delete all thumbnail keys from store and delete the # thumbnail ImageFiles. for key in thumbnail_keys: thumbnail = self._get(key) if thumbnail: self.delete(thumbnail, False) thumbnail.delete() # delete the actual file # Delete the thumbnails key from store self._delete(image_file.key, identity='thumbnails')
[ "def", "delete_thumbnails", "(", "self", ",", "image_file", ")", ":", "thumbnail_keys", "=", "self", ".", "_get", "(", "image_file", ".", "key", ",", "identity", "=", "'thumbnails'", ")", "if", "thumbnail_keys", ":", "# Delete all thumbnail keys from store and delet...
Deletes references to thumbnails as well as thumbnail ``image_files``.
[ "Deletes", "references", "to", "thumbnails", "as", "well", "as", "thumbnail", "image_files", "." ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/kvstores/base.py#L65-L81
232,374
jazzband/sorl-thumbnail
sorl/thumbnail/kvstores/base.py
KVStoreBase.clear
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) if all_keys: self._delete_raw(*all_keys)
python
def clear(self): all_keys = self._find_keys_raw(settings.THUMBNAIL_KEY_PREFIX) if all_keys: self._delete_raw(*all_keys)
[ "def", "clear", "(", "self", ")", ":", "all_keys", "=", "self", ".", "_find_keys_raw", "(", "settings", ".", "THUMBNAIL_KEY_PREFIX", ")", "if", "all_keys", ":", "self", ".", "_delete_raw", "(", "*", "all_keys", ")" ]
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.
[ "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", "in...
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/kvstores/base.py#L131-L139
232,375
jazzband/sorl-thumbnail
sorl/thumbnail/kvstores/base.py
KVStoreBase._get
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 deserialize(value)
python
def _get(self, key, identity='image'): value = self._get_raw(add_prefix(key, identity)) if not value: return None if identity == 'image': return deserialize_image_file(value) return deserialize(value)
[ "def", "_get", "(", "self", ",", "key", ",", "identity", "=", "'image'", ")", ":", "value", "=", "self", ".", "_get_raw", "(", "add_prefix", "(", "key", ",", "identity", ")", ")", "if", "not", "value", ":", "return", "None", "if", "identity", "==", ...
Deserializing, prefix wrapper for _get_raw
[ "Deserializing", "prefix", "wrapper", "for", "_get_raw" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/kvstores/base.py#L141-L153
232,376
jazzband/sorl-thumbnail
sorl/thumbnail/kvstores/base.py
KVStoreBase._set
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
def _set(self, key, value, identity='image'): if identity == 'image': s = serialize_image_file(value) else: s = serialize(value) self._set_raw(add_prefix(key, identity), s)
[ "def", "_set", "(", "self", ",", "key", ",", "value", ",", "identity", "=", "'image'", ")", ":", "if", "identity", "==", "'image'", ":", "s", "=", "serialize_image_file", "(", "value", ")", "else", ":", "s", "=", "serialize", "(", "value", ")", "self...
Serializing, prefix wrapper for _set_raw
[ "Serializing", "prefix", "wrapper", "for", "_set_raw" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/kvstores/base.py#L155-L163
232,377
jazzband/sorl-thumbnail
sorl/thumbnail/kvstores/base.py
KVStoreBase._find_keys
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
def _find_keys(self, identity='image'): prefix = add_prefix('', identity) raw_keys = self._find_keys_raw(prefix) or [] for raw_key in raw_keys: yield del_prefix(raw_key)
[ "def", "_find_keys", "(", "self", ",", "identity", "=", "'image'", ")", ":", "prefix", "=", "add_prefix", "(", "''", ",", "identity", ")", "raw_keys", "=", "self", ".", "_find_keys_raw", "(", "prefix", ")", "or", "[", "]", "for", "raw_key", "in", "raw_...
Finds and returns all keys for identity,
[ "Finds", "and", "returns", "all", "keys", "for", "identity" ]
22ccd9781462a820f963f57018ad3dcef85053ed
https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/kvstores/base.py#L171-L178
232,378
slaypni/fastdtw
fastdtw/fastdtw.py
dtw
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 between x[i] and y[j]. If dist is an int of value p > 0, then the p-norm will be used. If dist is a function then dist(x[i], y[j]) will be used. If dist is None then abs(x[i] - y[j]) will be used. Returns ------- distance : float the approximate distance between the 2 time series path : list list of indexes for the inputs x and y Examples -------- >>> import numpy as np >>> import fastdtw >>> x = np.array([1, 2, 3, 4, 5], dtype='float') >>> y = np.array([2, 3, 4], dtype='float') >>> fastdtw.dtw(x, y) (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)]) ''' x, y, dist = __prep_inputs(x, y, dist) return __dtw(x, y, None, dist)
python
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 between x[i] and y[j]. If dist is an int of value p > 0, then the p-norm will be used. If dist is a function then dist(x[i], y[j]) will be used. If dist is None then abs(x[i] - y[j]) will be used. Returns ------- distance : float the approximate distance between the 2 time series path : list list of indexes for the inputs x and y Examples -------- >>> import numpy as np >>> import fastdtw >>> x = np.array([1, 2, 3, 4, 5], dtype='float') >>> y = np.array([2, 3, 4], dtype='float') >>> fastdtw.dtw(x, y) (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)]) ''' x, y, dist = __prep_inputs(x, y, dist) return __dtw(x, y, None, dist)
[ "def", "dtw", "(", "x", ",", "y", ",", "dist", "=", "None", ")", ":", "x", ",", "y", ",", "dist", "=", "__prep_inputs", "(", "x", ",", "y", ",", "dist", ")", "return", "__dtw", "(", "x", ",", "y", ",", "None", ",", "dist", ")" ]
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 between x[i] and y[j]. If dist is an int of value p > 0, then the p-norm will be used. If dist is a function then dist(x[i], y[j]) will be used. If dist is None then abs(x[i] - y[j]) will be used. Returns ------- distance : float the approximate distance between the 2 time series path : list list of indexes for the inputs x and y Examples -------- >>> import numpy as np >>> import fastdtw >>> x = np.array([1, 2, 3, 4, 5], dtype='float') >>> y = np.array([2, 3, 4], dtype='float') >>> fastdtw.dtw(x, y) (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)])
[ "return", "the", "distance", "between", "2", "time", "series", "without", "approximation" ]
019ce2bdf41f65346a323378f4d292f14de526b8
https://github.com/slaypni/fastdtw/blob/019ce2bdf41f65346a323378f4d292f14de526b8/fastdtw/fastdtw.py#L98-L130
232,379
mozilla/mozilla-django-oidc
mozilla_django_oidc/views.py
get_next_url
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 next url :returns: safe url or None """ next_url = request.GET.get(redirect_field_name) if next_url: kwargs = { 'url': next_url, 'require_https': import_from_settings( 'OIDC_REDIRECT_REQUIRE_HTTPS', request.is_secure()) } hosts = list(import_from_settings('OIDC_REDIRECT_ALLOWED_HOSTS', [])) hosts.append(request.get_host()) kwargs['allowed_hosts'] = hosts is_safe = is_safe_url(**kwargs) if is_safe: return next_url return None
python
def get_next_url(request, redirect_field_name): next_url = request.GET.get(redirect_field_name) if next_url: kwargs = { 'url': next_url, 'require_https': import_from_settings( 'OIDC_REDIRECT_REQUIRE_HTTPS', request.is_secure()) } hosts = list(import_from_settings('OIDC_REDIRECT_ALLOWED_HOSTS', [])) hosts.append(request.get_host()) kwargs['allowed_hosts'] = hosts is_safe = is_safe_url(**kwargs) if is_safe: return next_url return None
[ "def", "get_next_url", "(", "request", ",", "redirect_field_name", ")", ":", "next_url", "=", "request", ".", "GET", ".", "get", "(", "redirect_field_name", ")", "if", "next_url", ":", "kwargs", "=", "{", "'url'", ":", "next_url", ",", "'require_https'", ":"...
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 next url :returns: safe url or None
[ "Retrieves", "next", "url", "from", "request" ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/views.py#L98-L125
232,380
mozilla/mozilla-django-oidc
mozilla_django_oidc/views.py
OIDCAuthenticationCallbackView.get
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! Something important failed. # Make sure the user doesn't get to continue to be logged in # otherwise the refresh middleware will force the user to # redirect to authorize again if the session refresh has # expired. if is_authenticated(request.user): auth.logout(request) assert not is_authenticated(request.user) elif 'code' in request.GET and 'state' in request.GET: kwargs = { 'request': request, 'nonce': nonce, } if 'oidc_state' not in request.session: return self.login_failure() if request.GET['state'] != request.session['oidc_state']: msg = 'Session `oidc_state` does not match the OIDC callback state' raise SuspiciousOperation(msg) self.user = auth.authenticate(**kwargs) if self.user and self.user.is_active: return self.login_success() return self.login_failure()
python
def get(self, request): 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! Something important failed. # Make sure the user doesn't get to continue to be logged in # otherwise the refresh middleware will force the user to # redirect to authorize again if the session refresh has # expired. if is_authenticated(request.user): auth.logout(request) assert not is_authenticated(request.user) elif 'code' in request.GET and 'state' in request.GET: kwargs = { 'request': request, 'nonce': nonce, } if 'oidc_state' not in request.session: return self.login_failure() if request.GET['state'] != request.session['oidc_state']: msg = 'Session `oidc_state` does not match the OIDC callback state' raise SuspiciousOperation(msg) self.user = auth.authenticate(**kwargs) if self.user and self.user.is_active: return self.login_success() return self.login_failure()
[ "def", "get", "(", "self", ",", "request", ")", ":", "nonce", "=", "request", ".", "session", ".", "get", "(", "'oidc_nonce'", ")", "if", "nonce", ":", "# Make sure that nonce is not used twice", "del", "request", ".", "session", "[", "'oidc_nonce'", "]", "i...
Callback handler for OIDC authorization code flow
[ "Callback", "handler", "for", "OIDC", "authorization", "code", "flow" ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/views.py#L61-L95
232,381
mozilla/mozilla-django-oidc
mozilla_django_oidc/views.py
OIDCAuthenticationRequestView.get
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_CALLBACK_URL', 'oidc_authentication_callback') params = { 'response_type': 'code', 'scope': self.get_settings('OIDC_RP_SCOPES', 'openid email'), 'client_id': self.OIDC_RP_CLIENT_ID, 'redirect_uri': absolutify( request, reverse(reverse_url) ), 'state': state, } params.update(self.get_extra_params(request)) if self.get_settings('OIDC_USE_NONCE', True): nonce = get_random_string(self.get_settings('OIDC_NONCE_SIZE', 32)) params.update({ 'nonce': nonce }) request.session['oidc_nonce'] = nonce request.session['oidc_state'] = state request.session['oidc_login_next'] = get_next_url(request, redirect_field_name) query = urlencode(params) redirect_url = '{url}?{query}'.format(url=self.OIDC_OP_AUTH_ENDPOINT, query=query) return HttpResponseRedirect(redirect_url)
python
def get(self, request): 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_CALLBACK_URL', 'oidc_authentication_callback') params = { 'response_type': 'code', 'scope': self.get_settings('OIDC_RP_SCOPES', 'openid email'), 'client_id': self.OIDC_RP_CLIENT_ID, 'redirect_uri': absolutify( request, reverse(reverse_url) ), 'state': state, } params.update(self.get_extra_params(request)) if self.get_settings('OIDC_USE_NONCE', True): nonce = get_random_string(self.get_settings('OIDC_NONCE_SIZE', 32)) params.update({ 'nonce': nonce }) request.session['oidc_nonce'] = nonce request.session['oidc_state'] = state request.session['oidc_login_next'] = get_next_url(request, redirect_field_name) query = urlencode(params) redirect_url = '{url}?{query}'.format(url=self.OIDC_OP_AUTH_ENDPOINT, query=query) return HttpResponseRedirect(redirect_url)
[ "def", "get", "(", "self", ",", "request", ")", ":", "state", "=", "get_random_string", "(", "self", ".", "get_settings", "(", "'OIDC_STATE_SIZE'", ",", "32", ")", ")", "redirect_field_name", "=", "self", ".", "get_settings", "(", "'OIDC_REDIRECT_FIELD_NAME'", ...
OIDC client authentication initialization HTTP endpoint
[ "OIDC", "client", "authentication", "initialization", "HTTP", "endpoint" ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/views.py#L143-L175
232,382
mozilla/mozilla-django-oidc
mozilla_django_oidc/contrib/drf.py
get_oidc_backend
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_settings('OIDC_DRF_AUTH_BACKEND', None) if backend_setting: backend = import_string(backend_setting)() if not isinstance(backend, OIDCAuthenticationBackend): msg = 'Class configured in OIDC_DRF_AUTH_BACKEND ' \ 'does not extend OIDCAuthenticationBackend!' raise ImproperlyConfigured(msg) return backend # if the backend setting is not set, look through the list of configured # backends for one that is an OIDCAuthenticationBackend. backends = [b for b in get_backends() if isinstance(b, OIDCAuthenticationBackend)] if not backends: msg = 'No backends extending OIDCAuthenticationBackend found - ' \ 'add one to AUTHENTICATION_BACKENDS or set OIDC_DRF_AUTH_BACKEND!' raise ImproperlyConfigured(msg) if len(backends) > 1: raise ImproperlyConfigured('More than one OIDCAuthenticationBackend found!') return backends[0]
python
def get_oidc_backend(): # 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_settings('OIDC_DRF_AUTH_BACKEND', None) if backend_setting: backend = import_string(backend_setting)() if not isinstance(backend, OIDCAuthenticationBackend): msg = 'Class configured in OIDC_DRF_AUTH_BACKEND ' \ 'does not extend OIDCAuthenticationBackend!' raise ImproperlyConfigured(msg) return backend # if the backend setting is not set, look through the list of configured # backends for one that is an OIDCAuthenticationBackend. backends = [b for b in get_backends() if isinstance(b, OIDCAuthenticationBackend)] if not backends: msg = 'No backends extending OIDCAuthenticationBackend found - ' \ 'add one to AUTHENTICATION_BACKENDS or set OIDC_DRF_AUTH_BACKEND!' raise ImproperlyConfigured(msg) if len(backends) > 1: raise ImproperlyConfigured('More than one OIDCAuthenticationBackend found!') return backends[0]
[ "def", "get_oidc_backend", "(", ")", ":", "# 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_settings", "(", "'OIDC_...
Get the Django auth backend that uses OIDC.
[ "Get", "the", "Django", "auth", "backend", "that", "uses", "OIDC", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/contrib/drf.py#L21-L48
232,383
mozilla/mozilla-django-oidc
mozilla_django_oidc/contrib/drf.py
OIDCAuthentication.get_access_token
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 header: return None header = header.decode(authentication.HTTP_HEADER_ENCODING) auth = header.split() if auth[0].lower() != 'bearer': return None if len(auth) == 1: msg = 'Invalid "bearer" header: No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid "bearer" header: Credentials string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) return auth[1]
python
def get_access_token(self, request): header = authentication.get_authorization_header(request) if not header: return None header = header.decode(authentication.HTTP_HEADER_ENCODING) auth = header.split() if auth[0].lower() != 'bearer': return None if len(auth) == 1: msg = 'Invalid "bearer" header: No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid "bearer" header: Credentials string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) return auth[1]
[ "def", "get_access_token", "(", "self", ",", "request", ")", ":", "header", "=", "authentication", ".", "get_authorization_header", "(", "request", ")", "if", "not", "header", ":", "return", "None", "header", "=", "header", ".", "decode", "(", "authentication"...
Get the access token based on a request. Returns None if no authentication details were provided. Raises AuthenticationFailed if the token is incorrect.
[ "Get", "the", "access", "token", "based", "on", "a", "request", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/contrib/drf.py#L96-L120
232,384
mozilla/mozilla-django-oidc
mozilla_django_oidc/utils.py
import_from_settings
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 ImproperlyConfigured('Setting {0} not found'.format(attr))
python
def import_from_settings(attr, *args): try: if args: return getattr(settings, attr, args[0]) return getattr(settings, attr) except AttributeError: raise ImproperlyConfigured('Setting {0} not found'.format(attr))
[ "def", "import_from_settings", "(", "attr", ",", "*", "args", ")", ":", "try", ":", "if", "args", ":", "return", "getattr", "(", "settings", ",", "attr", ",", "args", "[", "0", "]", ")", "return", "getattr", "(", "settings", ",", "attr", ")", "except...
Load an attribute from the django settings. :raises: ImproperlyConfigured
[ "Load", "an", "attribute", "from", "the", "django", "settings", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/utils.py#L21-L33
232,385
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
default_username_algo
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 protects against data leakage because usernames are often # treated as public identifiers (so we can't use the email address). username = base64.urlsafe_b64encode( hashlib.sha1(force_bytes(email)).digest() ).rstrip(b'=') return smart_text(username)
python
def default_username_algo(email): # bluntly stolen from django-browserid # store the username as a base64 encoded sha224 of the email address # this protects against data leakage because usernames are often # treated as public identifiers (so we can't use the email address). username = base64.urlsafe_b64encode( hashlib.sha1(force_bytes(email)).digest() ).rstrip(b'=') return smart_text(username)
[ "def", "default_username_algo", "(", "email", ")", ":", "# bluntly stolen from django-browserid", "# store the username as a base64 encoded sha224 of the email address", "# this protects against data leakage because usernames are often", "# treated as public identifiers (so we can't use the email ...
Generate username for the Django user. :arg str/unicode email: the email address to use to generate a username :returns: str/unicode
[ "Generate", "username", "for", "the", "Django", "user", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L30-L46
232,386
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.filter_users_by_claims
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
def filter_users_by_claims(self, claims): email = claims.get('email') if not email: return self.UserModel.objects.none() return self.UserModel.objects.filter(email__iexact=email)
[ "def", "filter_users_by_claims", "(", "self", ",", "claims", ")", ":", "email", "=", "claims", ".", "get", "(", "'email'", ")", "if", "not", "email", ":", "return", "self", ".", "UserModel", ".", "objects", ".", "none", "(", ")", "return", "self", ".",...
Return all users matching the specified email.
[ "Return", "all", "users", "matching", "the", "specified", "email", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L73-L78
232,387
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.verify_claims
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 claims LOGGER.warning('Custom OIDC_RP_SCOPES defined. ' 'You need to override `verify_claims` for custom claims verification.') return True
python
def verify_claims(self, claims): # Verify claims required by default configuration scopes = self.get_settings('OIDC_RP_SCOPES', 'openid email') if 'email' in scopes.split(): return 'email' in claims LOGGER.warning('Custom OIDC_RP_SCOPES defined. ' 'You need to override `verify_claims` for custom claims verification.') return True
[ "def", "verify_claims", "(", "self", ",", "claims", ")", ":", "# Verify claims required by default configuration", "scopes", "=", "self", ".", "get_settings", "(", "'OIDC_RP_SCOPES'", ",", "'openid email'", ")", "if", "'email'", "in", "scopes", ".", "split", "(", ...
Verify the provided claims to decide if authentication should be allowed.
[ "Verify", "the", "provided", "claims", "to", "decide", "if", "authentication", "should", "be", "allowed", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L80-L91
232,388
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.create_user
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
def create_user(self, claims): email = claims.get('email') username = self.get_username(claims) return self.UserModel.objects.create_user(username, email)
[ "def", "create_user", "(", "self", ",", "claims", ")", ":", "email", "=", "claims", ".", "get", "(", "'email'", ")", "username", "=", "self", ".", "get_username", "(", "claims", ")", "return", "self", ".", "UserModel", ".", "objects", ".", "create_user",...
Return object for a newly created user account.
[ "Return", "object", "for", "a", "newly", "created", "user", "account", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L93-L97
232,389
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.get_username
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: if isinstance(username_algo, six.string_types): username_algo = import_string(username_algo) return username_algo(claims.get('email')) return default_username_algo(claims.get('email'))
python
def get_username(self, 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: if isinstance(username_algo, six.string_types): username_algo = import_string(username_algo) return username_algo(claims.get('email')) return default_username_algo(claims.get('email'))
[ "def", "get_username", "(", "self", ",", "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"...
Generate username based on claims.
[ "Generate", "username", "based", "on", "claims", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L99-L110
232,390
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend._verify_jws
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 SuspiciousOperation(msg) if alg != self.OIDC_RP_SIGN_ALGO: msg = "The provider algorithm {!r} does not match the client's " \ "OIDC_RP_SIGN_ALGO.".format(alg) raise SuspiciousOperation(msg) if isinstance(key, six.string_types): # Use smart_bytes here since the key string comes from settings. jwk = JWK.load(smart_bytes(key)) else: # The key is a json returned from the IDP JWKS endpoint. jwk = JWK.from_json(key) if not jws.verify(jwk): msg = 'JWS token verification failed.' raise SuspiciousOperation(msg) return jws.payload
python
def _verify_jws(self, payload, key): jws = JWS.from_compact(payload) try: alg = jws.signature.combined.alg.name except KeyError: msg = 'No alg value found in header' raise SuspiciousOperation(msg) if alg != self.OIDC_RP_SIGN_ALGO: msg = "The provider algorithm {!r} does not match the client's " \ "OIDC_RP_SIGN_ALGO.".format(alg) raise SuspiciousOperation(msg) if isinstance(key, six.string_types): # Use smart_bytes here since the key string comes from settings. jwk = JWK.load(smart_bytes(key)) else: # The key is a json returned from the IDP JWKS endpoint. jwk = JWK.from_json(key) if not jws.verify(jwk): msg = 'JWS token verification failed.' raise SuspiciousOperation(msg) return jws.payload
[ "def", "_verify_jws", "(", "self", ",", "payload", ",", "key", ")", ":", "jws", "=", "JWS", ".", "from_compact", "(", "payload", ")", "try", ":", "alg", "=", "jws", ".", "signature", ".", "combined", ".", "alg", ".", "name", "except", "KeyError", ":"...
Verify the given JWS payload with the given key and return the payload
[ "Verify", "the", "given", "JWS", "payload", "with", "the", "given", "key", "and", "return", "the", "payload" ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L116-L142
232,391
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.retrieve_matching_jwk
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 = response_jwks.json() # Compute the current header from the given token to find a match jws = JWS.from_compact(token) json_header = jws.signature.protected header = Header.json_loads(json_header) key = None for jwk in jwks['keys']: if jwk['kid'] != smart_text(header.kid): continue if 'alg' in jwk and jwk['alg'] != smart_text(header.alg): raise SuspiciousOperation('alg values do not match.') key = jwk if key is None: raise SuspiciousOperation('Could not find a valid JWKS.') return key
python
def retrieve_matching_jwk(self, token): response_jwks = requests.get( self.OIDC_OP_JWKS_ENDPOINT, verify=self.get_settings('OIDC_VERIFY_SSL', True) ) response_jwks.raise_for_status() jwks = response_jwks.json() # Compute the current header from the given token to find a match jws = JWS.from_compact(token) json_header = jws.signature.protected header = Header.json_loads(json_header) key = None for jwk in jwks['keys']: if jwk['kid'] != smart_text(header.kid): continue if 'alg' in jwk and jwk['alg'] != smart_text(header.alg): raise SuspiciousOperation('alg values do not match.') key = jwk if key is None: raise SuspiciousOperation('Could not find a valid JWKS.') return key
[ "def", "retrieve_matching_jwk", "(", "self", ",", "token", ")", ":", "response_jwks", "=", "requests", ".", "get", "(", "self", ".", "OIDC_OP_JWKS_ENDPOINT", ",", "verify", "=", "self", ".", "get_settings", "(", "'OIDC_VERIFY_SSL'", ",", "True", ")", ")", "r...
Get the signing key by exploring the JWKS endpoint of the OP.
[ "Get", "the", "signing", "key", "by", "exploring", "the", "JWKS", "endpoint", "of", "the", "OP", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L144-L167
232,392
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.get_payload_data
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 config allows unsecured JWTs check the header and return the decoded payload if 'alg' in header and header['alg'] == 'none': return b64decode(payload_data) # By default fallback to verify JWT signatures return self._verify_jws(token, key)
python
def get_payload_data(self, token, key): if self.get_settings('OIDC_ALLOW_UNSECURED_JWT', False): header, payload_data, signature = token.split(b'.') header = json.loads(smart_text(b64decode(header))) # If config allows unsecured JWTs check the header and return the decoded payload if 'alg' in header and header['alg'] == 'none': return b64decode(payload_data) # By default fallback to verify JWT signatures return self._verify_jws(token, key)
[ "def", "get_payload_data", "(", "self", ",", "token", ",", "key", ")", ":", "if", "self", ".", "get_settings", "(", "'OIDC_ALLOW_UNSECURED_JWT'", ",", "False", ")", ":", "header", ",", "payload_data", ",", "signature", "=", "token", ".", "split", "(", "b'....
Helper method to get the payload of the JWT token.
[ "Helper", "method", "to", "get", "the", "payload", "of", "the", "JWT", "token", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L169-L180
232,393
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.verify_token
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 else: key = self.retrieve_matching_jwk(token) else: key = self.OIDC_RP_CLIENT_SECRET payload_data = self.get_payload_data(token, key) # The 'token' will always be a byte string since it's # the result of base64.urlsafe_b64decode(). # The payload is always the result of base64.urlsafe_b64decode(). # In Python 3 and 2, that's always a byte string. # In Python3.6, the json.loads() function can accept a byte string # as it will automagically decode it to a unicode string before # deserializing https://bugs.python.org/issue17909 payload = json.loads(payload_data.decode('utf-8')) token_nonce = payload.get('nonce') if self.get_settings('OIDC_USE_NONCE', True) and nonce != token_nonce: msg = 'JWT Nonce verification failed.' raise SuspiciousOperation(msg) return payload
python
def verify_token(self, token, **kwargs): 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 else: key = self.retrieve_matching_jwk(token) else: key = self.OIDC_RP_CLIENT_SECRET payload_data = self.get_payload_data(token, key) # The 'token' will always be a byte string since it's # the result of base64.urlsafe_b64decode(). # The payload is always the result of base64.urlsafe_b64decode(). # In Python 3 and 2, that's always a byte string. # In Python3.6, the json.loads() function can accept a byte string # as it will automagically decode it to a unicode string before # deserializing https://bugs.python.org/issue17909 payload = json.loads(payload_data.decode('utf-8')) token_nonce = payload.get('nonce') if self.get_settings('OIDC_USE_NONCE', True) and nonce != token_nonce: msg = 'JWT Nonce verification failed.' raise SuspiciousOperation(msg) return payload
[ "def", "verify_token", "(", "self", ",", "token", ",", "*", "*", "kwargs", ")", ":", "nonce", "=", "kwargs", ".", "get", "(", "'nonce'", ")", "token", "=", "force_bytes", "(", "token", ")", "if", "self", ".", "OIDC_RP_SIGN_ALGO", ".", "startswith", "("...
Validate the token signature.
[ "Validate", "the", "token", "signature", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L182-L210
232,394
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.get_token
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') pw = payload.get('client_secret') auth = HTTPBasicAuth(user, pw) del payload['client_secret'] response = requests.post( self.OIDC_OP_TOKEN_ENDPOINT, data=payload, auth=auth, verify=self.get_settings('OIDC_VERIFY_SSL', True)) response.raise_for_status() return response.json()
python
def get_token(self, payload): 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') pw = payload.get('client_secret') auth = HTTPBasicAuth(user, pw) del payload['client_secret'] response = requests.post( self.OIDC_OP_TOKEN_ENDPOINT, data=payload, auth=auth, verify=self.get_settings('OIDC_VERIFY_SSL', True)) response.raise_for_status() return response.json()
[ "def", "get_token", "(", "self", ",", "payload", ")", ":", "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", ...
Return token object as a dictionary.
[ "Return", "token", "object", "as", "a", "dictionary", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L212-L230
232,395
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.get_userinfo
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, headers={ 'Authorization': 'Bearer {0}'.format(access_token) }, verify=self.get_settings('OIDC_VERIFY_SSL', True)) user_response.raise_for_status() return user_response.json()
python
def get_userinfo(self, access_token, id_token, payload): user_response = requests.get( self.OIDC_OP_USER_ENDPOINT, headers={ 'Authorization': 'Bearer {0}'.format(access_token) }, verify=self.get_settings('OIDC_VERIFY_SSL', True)) user_response.raise_for_status() return user_response.json()
[ "def", "get_userinfo", "(", "self", ",", "access_token", ",", "id_token", ",", "payload", ")", ":", "user_response", "=", "requests", ".", "get", "(", "self", ".", "OIDC_OP_USER_ENDPOINT", ",", "headers", "=", "{", "'Authorization'", ":", "'Bearer {0}'", ".", ...
Return user details dictionary. The id_token and payload are not used in the default implementation, but may be used when overriding this method
[ "Return", "user", "details", "dictionary", ".", "The", "id_token", "and", "payload", "are", "not", "used", "in", "the", "default", "implementation", "but", "may", "be", "used", "when", "overriding", "this", "method" ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L232-L243
232,396
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.authenticate
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', None) if not code or not state: return None reverse_url = self.get_settings('OIDC_AUTHENTICATION_CALLBACK_URL', 'oidc_authentication_callback') token_payload = { 'client_id': self.OIDC_RP_CLIENT_ID, 'client_secret': self.OIDC_RP_CLIENT_SECRET, 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': absolutify( self.request, reverse(reverse_url) ), } # Get the token token_info = self.get_token(token_payload) id_token = token_info.get('id_token') access_token = token_info.get('access_token') # Validate the token payload = self.verify_token(id_token, nonce=nonce) if payload: self.store_tokens(access_token, id_token) try: return self.get_or_create_user(access_token, id_token, payload) except SuspiciousOperation as exc: LOGGER.warning('failed to get or create user: %s', exc) return None return None
python
def authenticate(self, request, **kwargs): 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', None) if not code or not state: return None reverse_url = self.get_settings('OIDC_AUTHENTICATION_CALLBACK_URL', 'oidc_authentication_callback') token_payload = { 'client_id': self.OIDC_RP_CLIENT_ID, 'client_secret': self.OIDC_RP_CLIENT_SECRET, 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': absolutify( self.request, reverse(reverse_url) ), } # Get the token token_info = self.get_token(token_payload) id_token = token_info.get('id_token') access_token = token_info.get('access_token') # Validate the token payload = self.verify_token(id_token, nonce=nonce) if payload: self.store_tokens(access_token, id_token) try: return self.get_or_create_user(access_token, id_token, payload) except SuspiciousOperation as exc: LOGGER.warning('failed to get or create user: %s', exc) return None return None
[ "def", "authenticate", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", "=", "request", "if", "not", "self", ".", "request", ":", "return", "None", "state", "=", "self", ".", "request", ".", "GET", ".", "get", ...
Authenticates a user based on the OIDC code flow.
[ "Authenticates", "a", "user", "based", "on", "the", "OIDC", "code", "flow", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L245-L289
232,397
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.store_tokens
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): session['oidc_id_token'] = id_token
python
def store_tokens(self, access_token, id_token): 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): session['oidc_id_token'] = id_token
[ "def", "store_tokens", "(", "self", ",", "access_token", ",", "id_token", ")", ":", "session", "=", "self", ".", "request", ".", "session", "if", "self", ".", "get_settings", "(", "'OIDC_STORE_ACCESS_TOKEN'", ",", "False", ")", ":", "session", "[", "'oidc_ac...
Store OIDC tokens.
[ "Store", "OIDC", "tokens", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L291-L299
232,398
mozilla/mozilla-django-oidc
mozilla_django_oidc/auth.py
OIDCAuthenticationBackend.get_or_create_user
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 = user_info.get('email') claims_verified = self.verify_claims(user_info) if not claims_verified: msg = 'Claims verification failed' raise SuspiciousOperation(msg) # email based filtering users = self.filter_users_by_claims(user_info) if len(users) == 1: return self.update_user(users[0], user_info) elif len(users) > 1: # In the rare case that two user accounts have the same email address, # bail. Randomly selecting one seems really wrong. msg = 'Multiple users returned' raise SuspiciousOperation(msg) elif self.get_settings('OIDC_CREATE_USER', True): user = self.create_user(user_info) return user else: LOGGER.debug('Login failed: No user with email %s found, and ' 'OIDC_CREATE_USER is False', email) return None
python
def get_or_create_user(self, access_token, id_token, payload): user_info = self.get_userinfo(access_token, id_token, payload) email = user_info.get('email') claims_verified = self.verify_claims(user_info) if not claims_verified: msg = 'Claims verification failed' raise SuspiciousOperation(msg) # email based filtering users = self.filter_users_by_claims(user_info) if len(users) == 1: return self.update_user(users[0], user_info) elif len(users) > 1: # In the rare case that two user accounts have the same email address, # bail. Randomly selecting one seems really wrong. msg = 'Multiple users returned' raise SuspiciousOperation(msg) elif self.get_settings('OIDC_CREATE_USER', True): user = self.create_user(user_info) return user else: LOGGER.debug('Login failed: No user with email %s found, and ' 'OIDC_CREATE_USER is False', email) return None
[ "def", "get_or_create_user", "(", "self", ",", "access_token", ",", "id_token", ",", "payload", ")", ":", "user_info", "=", "self", ".", "get_userinfo", "(", "access_token", ",", "id_token", ",", "payload", ")", "email", "=", "user_info", ".", "get", "(", ...
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.
[ "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", "." ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/auth.py#L301-L330
232,399
mozilla/mozilla-django-oidc
mozilla_django_oidc/middleware.py
SessionRefresh.exempt_urls
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 paths (for example "/oidc/callback/") """ exempt_urls = list(self.get_settings('OIDC_EXEMPT_URLS', [])) exempt_urls.extend([ 'oidc_authentication_init', 'oidc_authentication_callback', 'oidc_logout', ]) return set([ url if url.startswith('/') else reverse(url) for url in exempt_urls ])
python
def exempt_urls(self): exempt_urls = list(self.get_settings('OIDC_EXEMPT_URLS', [])) exempt_urls.extend([ 'oidc_authentication_init', 'oidc_authentication_callback', 'oidc_logout', ]) return set([ url if url.startswith('/') else reverse(url) for url in exempt_urls ])
[ "def", "exempt_urls", "(", "self", ")", ":", "exempt_urls", "=", "list", "(", "self", ".", "get_settings", "(", "'OIDC_EXEMPT_URLS'", ",", "[", "]", ")", ")", "exempt_urls", ".", "extend", "(", "[", "'oidc_authentication_init'", ",", "'oidc_authentication_callba...
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 paths (for example "/oidc/callback/")
[ "Generate", "and", "return", "a", "set", "of", "url", "paths", "to", "exempt", "from", "SessionRefresh" ]
e780130deacccbafc85a92f48d1407e042f5f955
https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/middleware.py#L45-L65