id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
175,462 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
_customTableRegistry = {}
def tagToIdentifier(tag):
"""Convert a table tag to a valid (but UGLY) python identifier,
as well as a filename that's guaranteed to be unique even on a
caseless file system. Each character is mapped to two characters.
Lowercase letters get an underscore before the letter, uppercase
letters get an underscore after the letter. Trailing spaces are
trimmed. Illegal characters are escaped as two hex bytes. If the
result starts with a number (as the result of a hex escape), an
extra underscore is prepended. Examples::
>>> tagToIdentifier('glyf')
'_g_l_y_f'
>>> tagToIdentifier('cvt ')
'_c_v_t'
>>> tagToIdentifier('OS/2')
'O_S_2f_2'
"""
import re
tag = Tag(tag)
if tag == "GlyphOrder":
return tag
assert len(tag) == 4, "tag should be 4 characters long"
while len(tag) > 1 and tag[-1] == " ":
tag = tag[:-1]
ident = ""
for c in tag:
ident = ident + _escapechar(c)
if re.match("[0-9]", ident):
ident = "_" + ident
return ident
The provided code snippet includes necessary dependencies for implementing the `registerCustomTableClass` function. Write a Python function `def registerCustomTableClass(tag, moduleName, className=None)` to solve the following problem:
Register a custom packer/unpacker class for a table. The 'moduleName' must be an importable module. If no 'className' is given, it is derived from the tag, for example it will be ``table_C_U_S_T_`` for a 'CUST' tag. The registered table class should be a subclass of :py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable`
Here is the function:
def registerCustomTableClass(tag, moduleName, className=None):
"""Register a custom packer/unpacker class for a table.
The 'moduleName' must be an importable module. If no 'className'
is given, it is derived from the tag, for example it will be
``table_C_U_S_T_`` for a 'CUST' tag.
The registered table class should be a subclass of
:py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable`
"""
if className is None:
className = "table_" + tagToIdentifier(tag)
_customTableRegistry[tag] = (moduleName, className) | Register a custom packer/unpacker class for a table. The 'moduleName' must be an importable module. If no 'className' is given, it is derived from the tag, for example it will be ``table_C_U_S_T_`` for a 'CUST' tag. The registered table class should be a subclass of :py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable` |
175,463 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
_customTableRegistry = {}
The provided code snippet includes necessary dependencies for implementing the `unregisterCustomTableClass` function. Write a Python function `def unregisterCustomTableClass(tag)` to solve the following problem:
Unregister the custom packer/unpacker class for a table.
Here is the function:
def unregisterCustomTableClass(tag):
"""Unregister the custom packer/unpacker class for a table."""
del _customTableRegistry[tag] | Unregister the custom packer/unpacker class for a table. |
175,464 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
def identifierToTag(ident):
"""the opposite of tagToIdentifier()"""
if ident == "GlyphOrder":
return ident
if len(ident) % 2 and ident[0] == "_":
ident = ident[1:]
assert not (len(ident) % 2)
tag = ""
for i in range(0, len(ident), 2):
if ident[i] == "_":
tag = tag + ident[i + 1]
elif ident[i + 1] == "_":
tag = tag + ident[i]
else:
# assume hex
tag = tag + chr(int(ident[i : i + 2], 16))
# append trailing spaces
tag = tag + (4 - len(tag)) * " "
return Tag(tag)
The provided code snippet includes necessary dependencies for implementing the `getClassTag` function. Write a Python function `def getClassTag(klass)` to solve the following problem:
Fetch the table tag for a class object.
Here is the function:
def getClassTag(klass):
"""Fetch the table tag for a class object."""
name = klass.__name__
assert name[:6] == "table_"
name = name[6:] # Chop 'table_'
return identifierToTag(name) | Fetch the table tag for a class object. |
175,465 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
def getTableClass(tag):
"""Fetch the packer/unpacker class for a table."""
tableClass = getCustomTableClass(tag)
if tableClass is not None:
return tableClass
module = getTableModule(tag)
if module is None:
from .tables.DefaultTable import DefaultTable
return DefaultTable
pyTag = tagToIdentifier(tag)
tableClass = getattr(module, "table_" + pyTag)
return tableClass
The provided code snippet includes necessary dependencies for implementing the `newTable` function. Write a Python function `def newTable(tag)` to solve the following problem:
Return a new instance of a table.
Here is the function:
def newTable(tag):
"""Return a new instance of a table."""
tableClass = getTableClass(tag)
return tableClass(tag) | Return a new instance of a table. |
175,466 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
def tagToIdentifier(tag):
"""Convert a table tag to a valid (but UGLY) python identifier,
as well as a filename that's guaranteed to be unique even on a
caseless file system. Each character is mapped to two characters.
Lowercase letters get an underscore before the letter, uppercase
letters get an underscore after the letter. Trailing spaces are
trimmed. Illegal characters are escaped as two hex bytes. If the
result starts with a number (as the result of a hex escape), an
extra underscore is prepended. Examples::
>>> tagToIdentifier('glyf')
'_g_l_y_f'
>>> tagToIdentifier('cvt ')
'_c_v_t'
>>> tagToIdentifier('OS/2')
'O_S_2f_2'
"""
import re
tag = Tag(tag)
if tag == "GlyphOrder":
return tag
assert len(tag) == 4, "tag should be 4 characters long"
while len(tag) > 1 and tag[-1] == " ":
tag = tag[:-1]
ident = ""
for c in tag:
ident = ident + _escapechar(c)
if re.match("[0-9]", ident):
ident = "_" + ident
return ident
class Tag(str):
def transcode(blob):
if isinstance(blob, bytes):
blob = blob.decode("latin-1")
return blob
def __new__(self, content):
return str.__new__(self, self.transcode(content))
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
return str.__eq__(self, self.transcode(other))
def __hash__(self):
return str.__hash__(self)
def tobytes(self):
return self.encode("latin-1")
The provided code snippet includes necessary dependencies for implementing the `tagToXML` function. Write a Python function `def tagToXML(tag)` to solve the following problem:
Similarly to tagToIdentifier(), this converts a TT tag to a valid XML element name. Since XML element names are case sensitive, this is a fairly simple/readable translation.
Here is the function:
def tagToXML(tag):
"""Similarly to tagToIdentifier(), this converts a TT tag
to a valid XML element name. Since XML element names are
case sensitive, this is a fairly simple/readable translation.
"""
import re
tag = Tag(tag)
if tag == "OS/2":
return "OS_2"
elif tag == "GlyphOrder":
return tag
if re.match("[A-Za-z_][A-Za-z_0-9]* *$", tag):
return tag.strip()
else:
return tagToIdentifier(tag) | Similarly to tagToIdentifier(), this converts a TT tag to a valid XML element name. Since XML element names are case sensitive, this is a fairly simple/readable translation. |
175,467 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
def identifierToTag(ident):
"""the opposite of tagToIdentifier()"""
if ident == "GlyphOrder":
return ident
if len(ident) % 2 and ident[0] == "_":
ident = ident[1:]
assert not (len(ident) % 2)
tag = ""
for i in range(0, len(ident), 2):
if ident[i] == "_":
tag = tag + ident[i + 1]
elif ident[i + 1] == "_":
tag = tag + ident[i]
else:
# assume hex
tag = tag + chr(int(ident[i : i + 2], 16))
# append trailing spaces
tag = tag + (4 - len(tag)) * " "
return Tag(tag)
class Tag(str):
def transcode(blob):
if isinstance(blob, bytes):
blob = blob.decode("latin-1")
return blob
def __new__(self, content):
return str.__new__(self, self.transcode(content))
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
return str.__eq__(self, self.transcode(other))
def __hash__(self):
return str.__hash__(self)
def tobytes(self):
return self.encode("latin-1")
The provided code snippet includes necessary dependencies for implementing the `xmlToTag` function. Write a Python function `def xmlToTag(tag)` to solve the following problem:
The opposite of tagToXML()
Here is the function:
def xmlToTag(tag):
"""The opposite of tagToXML()"""
if tag == "OS_2":
return Tag("OS/2")
if len(tag) == 8:
return identifierToTag(tag)
else:
return Tag(tag + " " * (4 - len(tag))) | The opposite of tagToXML() |
175,468 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
def sortedTagList(tagList, tableOrder=None):
"""Return a sorted copy of tagList, sorted according to the OpenType
specification, or according to a custom tableOrder. If given and not
None, tableOrder needs to be a list of tag names.
"""
tagList = sorted(tagList)
if tableOrder is None:
if "DSIG" in tagList:
# DSIG should be last (XXX spec reference?)
tagList.remove("DSIG")
tagList.append("DSIG")
if "CFF " in tagList:
tableOrder = OTFTableOrder
else:
tableOrder = TTFTableOrder
orderedTables = []
for tag in tableOrder:
if tag in tagList:
orderedTables.append(tag)
tagList.remove(tag)
orderedTables.extend(tagList)
return orderedTables
class SFNTReader(object):
def __new__(cls, *args, **kwargs):
"""Return an instance of the SFNTReader sub-class which is compatible
with the input file type.
"""
if args and cls is SFNTReader:
infile = args[0]
infile.seek(0)
sfntVersion = Tag(infile.read(4))
infile.seek(0)
if sfntVersion == "wOF2":
# return new WOFF2Reader object
from fontTools.ttLib.woff2 import WOFF2Reader
return object.__new__(WOFF2Reader)
# return default object
return object.__new__(cls)
def __init__(self, file, checkChecksums=0, fontNumber=-1):
self.file = file
self.checkChecksums = checkChecksums
self.flavor = None
self.flavorData = None
self.DirectoryEntry = SFNTDirectoryEntry
self.file.seek(0)
self.sfntVersion = self.file.read(4)
self.file.seek(0)
if self.sfntVersion == b"ttcf":
header = readTTCHeader(self.file)
numFonts = header.numFonts
if not 0 <= fontNumber < numFonts:
raise TTLibFileIsCollectionError(
"specify a font number between 0 and %d (inclusive)"
% (numFonts - 1)
)
self.numFonts = numFonts
self.file.seek(header.offsetTable[fontNumber])
data = self.file.read(sfntDirectorySize)
if len(data) != sfntDirectorySize:
raise TTLibError("Not a Font Collection (not enough data)")
sstruct.unpack(sfntDirectoryFormat, data, self)
elif self.sfntVersion == b"wOFF":
self.flavor = "woff"
self.DirectoryEntry = WOFFDirectoryEntry
data = self.file.read(woffDirectorySize)
if len(data) != woffDirectorySize:
raise TTLibError("Not a WOFF font (not enough data)")
sstruct.unpack(woffDirectoryFormat, data, self)
else:
data = self.file.read(sfntDirectorySize)
if len(data) != sfntDirectorySize:
raise TTLibError("Not a TrueType or OpenType font (not enough data)")
sstruct.unpack(sfntDirectoryFormat, data, self)
self.sfntVersion = Tag(self.sfntVersion)
if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):
raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")
tables = {}
for i in range(self.numTables):
entry = self.DirectoryEntry()
entry.fromFile(self.file)
tag = Tag(entry.tag)
tables[tag] = entry
self.tables = OrderedDict(sorted(tables.items(), key=lambda i: i[1].offset))
# Load flavor data if any
if self.flavor == "woff":
self.flavorData = WOFFFlavorData(self)
def has_key(self, tag):
return tag in self.tables
__contains__ = has_key
def keys(self):
return self.tables.keys()
def __getitem__(self, tag):
"""Fetch the raw table data."""
entry = self.tables[Tag(tag)]
data = entry.loadData(self.file)
if self.checkChecksums:
if tag == "head":
# Beh: we have to special-case the 'head' table.
checksum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
else:
checksum = calcChecksum(data)
if self.checkChecksums > 1:
# Be obnoxious, and barf when it's wrong
assert checksum == entry.checkSum, "bad checksum for '%s' table" % tag
elif checksum != entry.checkSum:
# Be friendly, and just log a warning.
log.warning("bad checksum for '%s' table", tag)
return data
def __delitem__(self, tag):
del self.tables[Tag(tag)]
def close(self):
self.file.close()
# We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able
# and deepcopy-able. When a TTFont is loaded as lazy=True, SFNTReader holds a
# reference to an external file object which is not pickleable. So in __getstate__
# we store the file name and current position, and in __setstate__ we reopen the
# same named file after unpickling.
def __getstate__(self):
if isinstance(self.file, BytesIO):
# BytesIO is already pickleable, return the state unmodified
return self.__dict__
# remove unpickleable file attribute, and only store its name and pos
state = self.__dict__.copy()
del state["file"]
state["_filename"] = self.file.name
state["_filepos"] = self.file.tell()
return state
def __setstate__(self, state):
if "file" not in state:
self.file = open(state.pop("_filename"), "rb")
self.file.seek(state.pop("_filepos"))
self.__dict__.update(state)
class SFNTWriter(object):
def __new__(cls, *args, **kwargs):
"""Return an instance of the SFNTWriter sub-class which is compatible
with the specified 'flavor'.
"""
flavor = None
if kwargs and "flavor" in kwargs:
flavor = kwargs["flavor"]
elif args and len(args) > 3:
flavor = args[3]
if cls is SFNTWriter:
if flavor == "woff2":
# return new WOFF2Writer object
from fontTools.ttLib.woff2 import WOFF2Writer
return object.__new__(WOFF2Writer)
# return default object
return object.__new__(cls)
def __init__(
self,
file,
numTables,
sfntVersion="\000\001\000\000",
flavor=None,
flavorData=None,
):
self.file = file
self.numTables = numTables
self.sfntVersion = Tag(sfntVersion)
self.flavor = flavor
self.flavorData = flavorData
if self.flavor == "woff":
self.directoryFormat = woffDirectoryFormat
self.directorySize = woffDirectorySize
self.DirectoryEntry = WOFFDirectoryEntry
self.signature = "wOFF"
# to calculate WOFF checksum adjustment, we also need the original SFNT offsets
self.origNextTableOffset = (
sfntDirectorySize + numTables * sfntDirectoryEntrySize
)
else:
assert not self.flavor, "Unknown flavor '%s'" % self.flavor
self.directoryFormat = sfntDirectoryFormat
self.directorySize = sfntDirectorySize
self.DirectoryEntry = SFNTDirectoryEntry
from fontTools.ttLib import getSearchRange
self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
numTables, 16
)
self.directoryOffset = self.file.tell()
self.nextTableOffset = (
self.directoryOffset
+ self.directorySize
+ numTables * self.DirectoryEntry.formatSize
)
# clear out directory area
self.file.seek(self.nextTableOffset)
# make sure we're actually where we want to be. (old cStringIO bug)
self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
self.tables = OrderedDict()
def setEntry(self, tag, entry):
if tag in self.tables:
raise TTLibError("cannot rewrite '%s' table" % tag)
self.tables[tag] = entry
def __setitem__(self, tag, data):
"""Write raw table data to disk."""
if tag in self.tables:
raise TTLibError("cannot rewrite '%s' table" % tag)
entry = self.DirectoryEntry()
entry.tag = tag
entry.offset = self.nextTableOffset
if tag == "head":
entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
self.headTable = data
entry.uncompressed = True
else:
entry.checkSum = calcChecksum(data)
entry.saveData(self.file, data)
if self.flavor == "woff":
entry.origOffset = self.origNextTableOffset
self.origNextTableOffset += (entry.origLength + 3) & ~3
self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3)
# Add NUL bytes to pad the table data to a 4-byte boundary.
# Don't depend on f.seek() as we need to add the padding even if no
# subsequent write follows (seek is lazy), ie. after the final table
# in the font.
self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
assert self.nextTableOffset == self.file.tell()
self.setEntry(tag, entry)
def __getitem__(self, tag):
return self.tables[tag]
def close(self):
"""All tables must have been written to disk. Now write the
directory.
"""
tables = sorted(self.tables.items())
if len(tables) != self.numTables:
raise TTLibError(
"wrong number of tables; expected %d, found %d"
% (self.numTables, len(tables))
)
if self.flavor == "woff":
self.signature = b"wOFF"
self.reserved = 0
self.totalSfntSize = 12
self.totalSfntSize += 16 * len(tables)
for tag, entry in tables:
self.totalSfntSize += (entry.origLength + 3) & ~3
data = self.flavorData if self.flavorData else WOFFFlavorData()
if data.majorVersion is not None and data.minorVersion is not None:
self.majorVersion = data.majorVersion
self.minorVersion = data.minorVersion
else:
if hasattr(self, "headTable"):
self.majorVersion, self.minorVersion = struct.unpack(
">HH", self.headTable[4:8]
)
else:
self.majorVersion = self.minorVersion = 0
if data.metaData:
self.metaOrigLength = len(data.metaData)
self.file.seek(0, 2)
self.metaOffset = self.file.tell()
compressedMetaData = compress(data.metaData)
self.metaLength = len(compressedMetaData)
self.file.write(compressedMetaData)
else:
self.metaOffset = self.metaLength = self.metaOrigLength = 0
if data.privData:
self.file.seek(0, 2)
off = self.file.tell()
paddedOff = (off + 3) & ~3
self.file.write("\0" * (paddedOff - off))
self.privOffset = self.file.tell()
self.privLength = len(data.privData)
self.file.write(data.privData)
else:
self.privOffset = self.privLength = 0
self.file.seek(0, 2)
self.length = self.file.tell()
else:
assert not self.flavor, "Unknown flavor '%s'" % self.flavor
pass
directory = sstruct.pack(self.directoryFormat, self)
self.file.seek(self.directoryOffset + self.directorySize)
seenHead = 0
for tag, entry in tables:
if tag == "head":
seenHead = 1
directory = directory + entry.toString()
if seenHead:
self.writeMasterChecksum(directory)
self.file.seek(self.directoryOffset)
self.file.write(directory)
def _calcMasterChecksum(self, directory):
# calculate checkSumAdjustment
tags = list(self.tables.keys())
checksums = []
for i in range(len(tags)):
checksums.append(self.tables[tags[i]].checkSum)
if self.DirectoryEntry != SFNTDirectoryEntry:
# Create a SFNT directory for checksum calculation purposes
from fontTools.ttLib import getSearchRange
self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
self.numTables, 16
)
directory = sstruct.pack(sfntDirectoryFormat, self)
tables = sorted(self.tables.items())
for tag, entry in tables:
sfntEntry = SFNTDirectoryEntry()
sfntEntry.tag = entry.tag
sfntEntry.checkSum = entry.checkSum
sfntEntry.offset = entry.origOffset
sfntEntry.length = entry.origLength
directory = directory + sfntEntry.toString()
directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize
assert directory_end == len(directory)
checksums.append(calcChecksum(directory))
checksum = sum(checksums) & 0xFFFFFFFF
# BiboAfba!
checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF
return checksumadjustment
def writeMasterChecksum(self, directory):
checksumadjustment = self._calcMasterChecksum(directory)
# write the checksum to the file
self.file.seek(self.tables["head"].offset + 8)
self.file.write(struct.pack(">L", checksumadjustment))
def reordersTables(self):
return False
The provided code snippet includes necessary dependencies for implementing the `reorderFontTables` function. Write a Python function `def reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False)` to solve the following problem:
Rewrite a font file, ordering the tables as recommended by the OpenType specification 1.4.
Here is the function:
def reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False):
"""Rewrite a font file, ordering the tables as recommended by the
OpenType specification 1.4.
"""
inFile.seek(0)
outFile.seek(0)
reader = SFNTReader(inFile, checkChecksums=checkChecksums)
writer = SFNTWriter(
outFile,
len(reader.tables),
reader.sfntVersion,
reader.flavor,
reader.flavorData,
)
tables = list(reader.keys())
for tag in sortedTagList(tables, tableOrder):
writer[tag] = reader[tag]
writer.close() | Rewrite a font file, ordering the tables as recommended by the OpenType specification 1.4. |
175,469 | from fontTools.config import Config
from fontTools.misc import xmlWriter
from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
from fontTools.ttLib.ttGlyphSet import _TTGlyph, _TTGlyphSetCFF, _TTGlyphSetGlyf
from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
from io import BytesIO, StringIO, UnsupportedOperation
import os
import logging
import traceback
def maxPowerOfTwo(x):
"""Return the highest exponent of two, so that
(2 ** exponent) <= x. Return 0 if x is 0.
"""
exponent = 0
while x:
x = x >> 1
exponent = exponent + 1
return max(exponent - 1, 0)
The provided code snippet includes necessary dependencies for implementing the `getSearchRange` function. Write a Python function `def getSearchRange(n, itemSize=16)` to solve the following problem:
Calculate searchRange, entrySelector, rangeShift.
Here is the function:
def getSearchRange(n, itemSize=16):
"""Calculate searchRange, entrySelector, rangeShift."""
# itemSize defaults to 16, for backward compatibility
# with upstream fonttools.
exponent = maxPowerOfTwo(n)
searchRange = (2**exponent) * itemSize
entrySelector = exponent
rangeShift = max(0, n * itemSize - searchRange)
return searchRange, entrySelector, rangeShift | Calculate searchRange, entrySelector, rangeShift. |
175,470 | from io import BytesIO
from fontTools.misc.macRes import ResourceReader, ResourceError
def getSFNTResIndices(path):
"""Determine whether a file has a 'sfnt' resource fork or not."""
try:
reader = ResourceReader(path)
indices = reader.getIndices("sfnt")
reader.close()
return indices
except ResourceError:
return []
The provided code snippet includes necessary dependencies for implementing the `openTTFonts` function. Write a Python function `def openTTFonts(path)` to solve the following problem:
Given a pathname, return a list of TTFont objects. In the case of a flat TTF/OTF file, the list will contain just one font object; but in the case of a Mac font suitcase it will contain as many font objects as there are sfnt resources in the file.
Here is the function:
def openTTFonts(path):
"""Given a pathname, return a list of TTFont objects. In the case
of a flat TTF/OTF file, the list will contain just one font object;
but in the case of a Mac font suitcase it will contain as many
font objects as there are sfnt resources in the file.
"""
from fontTools import ttLib
fonts = []
sfnts = getSFNTResIndices(path)
if not sfnts:
fonts.append(ttLib.TTFont(path))
else:
for index in sfnts:
fonts.append(ttLib.TTFont(path, index))
if not fonts:
raise ttLib.TTLibError("no fonts found in file '%s'" % path)
return fonts | Given a pathname, return a list of TTFont objects. In the case of a flat TTF/OTF file, the list will contain just one font object; but in the case of a Mac font suitcase it will contain as many font objects as there are sfnt resources in the file. |
175,471 | _accessstrings = {0: "", 1: "readonly", 2: "executeonly", 3: "noaccess"}
def _type1_Encoding_repr(encoding, access):
def _type1_CharString_repr(charstrings):
from fontTools.encodings.StandardEncoding import StandardEncoding
def _type1_item_repr(key, value):
psstring = ""
access = _accessstrings[value.access]
if access:
access = access + " "
if key == "CharStrings":
psstring = psstring + "/%s %s def\n" % (
key,
_type1_CharString_repr(value.value),
)
elif key == "Encoding":
psstring = psstring + _type1_Encoding_repr(value, access)
else:
psstring = psstring + "/%s %s %sdef\n" % (str(key), str(value), access)
return psstring | null |
175,472 | from .roundTools import otRound, nearestMultipleShortestRepr
import logging
def nearestMultipleShortestRepr(value: float, factor: float) -> str:
"""Round to nearest multiple of factor and return shortest decimal representation.
This chooses the float that is closer to a multiple of the given factor while
having the shortest decimal representation (the least number of fractional decimal
digits).
For example, given the following:
>>> nearestMultipleShortestRepr(-0.61883544921875, 1.0/(1<<14))
'-0.61884'
Useful when you need to serialize or print a fixed-point number (or multiples
thereof, such as F2Dot14 fractions of 180 degrees in COLRv1 PaintRotate) in
a human-readable form.
Args:
value (value): The value to be rounded and serialized.
factor (float): The value which the result is a close multiple of.
Returns:
str: A compact string representation of the value.
"""
if not value:
return "0.0"
value = otRound(value / factor) * factor
eps = 0.5 * factor
lo = value - eps
hi = value + eps
# If the range of valid choices spans an integer, return the integer.
if int(lo) != int(hi):
return str(float(round(value)))
fmt = "%.8f"
lo = fmt % lo
hi = fmt % hi
assert len(lo) == len(hi) and lo != hi
for i in range(len(lo)):
if lo[i] != hi[i]:
break
period = lo.find(".")
assert period < i
fmt = "%%.%df" % (i - period)
return fmt % value
The provided code snippet includes necessary dependencies for implementing the `fixedToStr` function. Write a Python function `def fixedToStr(value, precisionBits)` to solve the following problem:
Converts a fixed-point number to a string representing a decimal float. This chooses the float that has the shortest decimal representation (the least number of fractional decimal digits). For example, to convert a fixed-point number in a 2.14 format, use ``precisionBits=14``:: >>> fixedToStr(-10139, precisionBits=14) '-0.61884' This is pretty slow compared to the simple division used in ``fixedToFloat``. Use sporadically when you need to serialize or print the fixed-point number in a human-readable form. It uses nearestMultipleShortestRepr under the hood. Args: value (int): The fixed-point value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value.
Here is the function:
def fixedToStr(value, precisionBits):
"""Converts a fixed-point number to a string representing a decimal float.
This chooses the float that has the shortest decimal representation (the least
number of fractional decimal digits).
For example, to convert a fixed-point number in a 2.14 format, use
``precisionBits=14``::
>>> fixedToStr(-10139, precisionBits=14)
'-0.61884'
This is pretty slow compared to the simple division used in ``fixedToFloat``.
Use sporadically when you need to serialize or print the fixed-point number in
a human-readable form.
It uses nearestMultipleShortestRepr under the hood.
Args:
value (int): The fixed-point value to convert.
precisionBits (int): Number of precision bits, *up to a maximum of 16*.
Returns:
str: A string representation of the value.
"""
scale = 1 << precisionBits
return nearestMultipleShortestRepr(value / scale, factor=1.0 / scale) | Converts a fixed-point number to a string representing a decimal float. This chooses the float that has the shortest decimal representation (the least number of fractional decimal digits). For example, to convert a fixed-point number in a 2.14 format, use ``precisionBits=14``:: >>> fixedToStr(-10139, precisionBits=14) '-0.61884' This is pretty slow compared to the simple division used in ``fixedToFloat``. Use sporadically when you need to serialize or print the fixed-point number in a human-readable form. It uses nearestMultipleShortestRepr under the hood. Args: value (int): The fixed-point value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value. |
175,473 | from .roundTools import otRound, nearestMultipleShortestRepr
import logging
def otRound(value):
"""Round float value to nearest integer towards ``+Infinity``.
The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_)
defines the required method for converting floating point values to
fixed-point. In particular it specifies the following rounding strategy:
for fractional values of 0.5 and higher, take the next higher integer;
for other fractional values, truncate.
This function rounds the floating-point value according to this strategy
in preparation for conversion to fixed-point.
Args:
value (float): The input floating-point value.
Returns
float: The rounded value.
"""
# See this thread for how we ended up with this implementation:
# https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166
return int(math.floor(value + 0.5))
The provided code snippet includes necessary dependencies for implementing the `strToFixed` function. Write a Python function `def strToFixed(string, precisionBits)` to solve the following problem:
Converts a string representing a decimal float to a fixed-point number. Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: int: Fixed-point representation. Examples:: >>> ## to convert a float string to a 2.14 fixed-point number: >>> strToFixed('-0.61884', precisionBits=14) -10139
Here is the function:
def strToFixed(string, precisionBits):
"""Converts a string representing a decimal float to a fixed-point number.
Args:
string (str): A string representing a decimal float.
precisionBits (int): Number of precision bits, *up to a maximum of 16*.
Returns:
int: Fixed-point representation.
Examples::
>>> ## to convert a float string to a 2.14 fixed-point number:
>>> strToFixed('-0.61884', precisionBits=14)
-10139
"""
value = float(string)
return otRound(value * (1 << precisionBits)) | Converts a string representing a decimal float to a fixed-point number. Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: int: Fixed-point representation. Examples:: >>> ## to convert a float string to a 2.14 fixed-point number: >>> strToFixed('-0.61884', precisionBits=14) -10139 |
175,474 | from .roundTools import otRound, nearestMultipleShortestRepr
import logging
def otRound(value):
"""Round float value to nearest integer towards ``+Infinity``.
The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_)
defines the required method for converting floating point values to
fixed-point. In particular it specifies the following rounding strategy:
for fractional values of 0.5 and higher, take the next higher integer;
for other fractional values, truncate.
This function rounds the floating-point value according to this strategy
in preparation for conversion to fixed-point.
Args:
value (float): The input floating-point value.
Returns
float: The rounded value.
"""
# See this thread for how we ended up with this implementation:
# https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166
return int(math.floor(value + 0.5))
The provided code snippet includes necessary dependencies for implementing the `strToFixedToFloat` function. Write a Python function `def strToFixedToFloat(string, precisionBits)` to solve the following problem:
Convert a string to a decimal float with fixed-point rounding. This first converts string to a float, then turns it into a fixed-point number with ``precisionBits`` fractional binary digits, then back to a float again. This is simply a shorthand for fixedToFloat(floatToFixed(float(s))). Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits. Returns: float: The transformed and rounded value. Examples:: >>> import math >>> s = '-0.61884' >>> bits = 14 >>> f = strToFixedToFloat(s, precisionBits=bits) >>> math.isclose(f, -0.61883544921875) True >>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits) True
Here is the function:
def strToFixedToFloat(string, precisionBits):
"""Convert a string to a decimal float with fixed-point rounding.
This first converts string to a float, then turns it into a fixed-point
number with ``precisionBits`` fractional binary digits, then back to a
float again.
This is simply a shorthand for fixedToFloat(floatToFixed(float(s))).
Args:
string (str): A string representing a decimal float.
precisionBits (int): Number of precision bits.
Returns:
float: The transformed and rounded value.
Examples::
>>> import math
>>> s = '-0.61884'
>>> bits = 14
>>> f = strToFixedToFloat(s, precisionBits=bits)
>>> math.isclose(f, -0.61883544921875)
True
>>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits)
True
"""
value = float(string)
scale = 1 << precisionBits
return otRound(value * scale) / scale | Convert a string to a decimal float with fixed-point rounding. This first converts string to a float, then turns it into a fixed-point number with ``precisionBits`` fractional binary digits, then back to a float again. This is simply a shorthand for fixedToFloat(floatToFixed(float(s))). Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits. Returns: float: The transformed and rounded value. Examples:: >>> import math >>> s = '-0.61884' >>> bits = 14 >>> f = strToFixedToFloat(s, precisionBits=bits) >>> math.isclose(f, -0.61883544921875) True >>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits) True |
175,475 | from .roundTools import otRound, nearestMultipleShortestRepr
import logging
def nearestMultipleShortestRepr(value: float, factor: float) -> str:
"""Round to nearest multiple of factor and return shortest decimal representation.
This chooses the float that is closer to a multiple of the given factor while
having the shortest decimal representation (the least number of fractional decimal
digits).
For example, given the following:
>>> nearestMultipleShortestRepr(-0.61883544921875, 1.0/(1<<14))
'-0.61884'
Useful when you need to serialize or print a fixed-point number (or multiples
thereof, such as F2Dot14 fractions of 180 degrees in COLRv1 PaintRotate) in
a human-readable form.
Args:
value (value): The value to be rounded and serialized.
factor (float): The value which the result is a close multiple of.
Returns:
str: A compact string representation of the value.
"""
if not value:
return "0.0"
value = otRound(value / factor) * factor
eps = 0.5 * factor
lo = value - eps
hi = value + eps
# If the range of valid choices spans an integer, return the integer.
if int(lo) != int(hi):
return str(float(round(value)))
fmt = "%.8f"
lo = fmt % lo
hi = fmt % hi
assert len(lo) == len(hi) and lo != hi
for i in range(len(lo)):
if lo[i] != hi[i]:
break
period = lo.find(".")
assert period < i
fmt = "%%.%df" % (i - period)
return fmt % value
The provided code snippet includes necessary dependencies for implementing the `floatToFixedToStr` function. Write a Python function `def floatToFixedToStr(value, precisionBits)` to solve the following problem:
Convert float to string with fixed-point rounding. This uses the shortest decimal representation (ie. the least number of fractional decimal digits) to represent the equivalent fixed-point number with ``precisionBits`` fractional binary digits. It uses nearestMultipleShortestRepr under the hood. >>> floatToFixedToStr(-0.61883544921875, precisionBits=14) '-0.61884' Args: value (float): The float value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value.
Here is the function:
def floatToFixedToStr(value, precisionBits):
"""Convert float to string with fixed-point rounding.
This uses the shortest decimal representation (ie. the least
number of fractional decimal digits) to represent the equivalent
fixed-point number with ``precisionBits`` fractional binary digits.
It uses nearestMultipleShortestRepr under the hood.
>>> floatToFixedToStr(-0.61883544921875, precisionBits=14)
'-0.61884'
Args:
value (float): The float value to convert.
precisionBits (int): Number of precision bits, *up to a maximum of 16*.
Returns:
str: A string representation of the value.
"""
scale = 1 << precisionBits
return nearestMultipleShortestRepr(value, factor=1.0 / scale) | Convert float to string with fixed-point rounding. This uses the shortest decimal representation (ie. the least number of fractional decimal digits) to represent the equivalent fixed-point number with ``precisionBits`` fractional binary digits. It uses nearestMultipleShortestRepr under the hood. >>> floatToFixedToStr(-0.61883544921875, precisionBits=14) '-0.61884' Args: value (float): The float value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value. |
175,476 | from .roundTools import otRound, nearestMultipleShortestRepr
import logging
def ensureVersionIsLong(value):
"""Ensure a table version is an unsigned long.
OpenType table version numbers are expressed as a single unsigned long
comprising of an unsigned short major version and unsigned short minor
version. This function detects if the value to be used as a version number
looks too small (i.e. is less than ``0x10000``), and converts it to
fixed-point using :func:`floatToFixed` if so.
Args:
value (Number): a candidate table version number.
Returns:
int: A table version number, possibly corrected to fixed-point.
"""
if value < 0x10000:
newValue = floatToFixed(value, 16)
log.warning(
"Table version value is a float: %.4f; " "fix to use hex instead: 0x%08x",
value,
newValue,
)
value = newValue
return value
The provided code snippet includes necessary dependencies for implementing the `versionToFixed` function. Write a Python function `def versionToFixed(value)` to solve the following problem:
Ensure a table version number is fixed-point. Args: value (str): a candidate table version number. Returns: int: A table version number, possibly corrected to fixed-point.
Here is the function:
def versionToFixed(value):
"""Ensure a table version number is fixed-point.
Args:
value (str): a candidate table version number.
Returns:
int: A table version number, possibly corrected to fixed-point.
"""
value = int(value, 0) if value.startswith("0") else float(value)
value = ensureVersionIsLong(value)
return value | Ensure a table version number is fixed-point. Args: value (str): a candidate table version number. Returns: int: A table version number, possibly corrected to fixed-point. |
175,477 |
The provided code snippet includes necessary dependencies for implementing the `bit_indices` function. Write a Python function `def bit_indices(v)` to solve the following problem:
Return list of indices where bits are set, 0 being the index of the least significant bit. >>> bit_indices(0b101) [0, 2]
Here is the function:
def bit_indices(v):
"""Return list of indices where bits are set, 0 being the index of the least significant bit.
>>> bit_indices(0b101)
[0, 2]
"""
return [i for i, b in enumerate(bin(v)[::-1]) if b == "1"] | Return list of indices where bits are set, 0 being the index of the least significant bit. >>> bit_indices(0b101) [0, 2] |
175,478 | from fontTools.misc.textTools import bytechr, bytesjoin, byteord
def _decryptChar(cipher, R):
cipher = byteord(cipher)
plain = ((cipher ^ (R >> 8))) & 0xFF
R = ((cipher + R) * 52845 + 22719) & 0xFFFF
return bytechr(plain), R
def bytesjoin(iterable, joiner=b""):
return tobytes(joiner).join(tobytes(item) for item in iterable)
The provided code snippet includes necessary dependencies for implementing the `decrypt` function. Write a Python function `def decrypt(cipherstring, R)` to solve the following problem:
r""" Decrypts a string using the Type 1 encryption algorithm. Args: cipherstring: String of ciphertext. R: Initial key. Returns: decryptedStr: Plaintext string. R: Output key for subsequent decryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True
Here is the function:
def decrypt(cipherstring, R):
r"""
Decrypts a string using the Type 1 encryption algorithm.
Args:
cipherstring: String of ciphertext.
R: Initial key.
Returns:
decryptedStr: Plaintext string.
R: Output key for subsequent decryptions.
Examples::
>>> testStr = b"\0\0asdadads asds\265"
>>> decryptedStr, R = decrypt(testStr, 12321)
>>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
True
>>> R == 36142
True
"""
plainList = []
for cipher in cipherstring:
plain, R = _decryptChar(cipher, R)
plainList.append(plain)
plainstring = bytesjoin(plainList)
return plainstring, int(R) | r""" Decrypts a string using the Type 1 encryption algorithm. Args: cipherstring: String of ciphertext. R: Initial key. Returns: decryptedStr: Plaintext string. R: Output key for subsequent decryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True |
175,479 | from fontTools.misc.textTools import bytechr, bytesjoin, byteord
def _encryptChar(plain, R):
plain = byteord(plain)
cipher = ((plain ^ (R >> 8))) & 0xFF
R = ((cipher + R) * 52845 + 22719) & 0xFFFF
return bytechr(cipher), R
def bytesjoin(iterable, joiner=b""):
return tobytes(joiner).join(tobytes(item) for item in iterable)
The provided code snippet includes necessary dependencies for implementing the `encrypt` function. Write a Python function `def encrypt(plainstring, R)` to solve the following problem:
r""" Encrypts a string using the Type 1 encryption algorithm. Note that the algorithm as described in the Type 1 specification requires the plaintext to be prefixed with a number of random bytes. (For ``eexec`` the number of random bytes is set to 4.) This routine does *not* add the random prefix to its input. Args: plainstring: String of plaintext. R: Initial key. Returns: cipherstring: Ciphertext string. R: Output key for subsequent encryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True >>> testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' >>> encryptedStr, R = encrypt(testStr, 12321) >>> encryptedStr == b"\0\0asdadads asds\265" True >>> R == 36142 True
Here is the function:
def encrypt(plainstring, R):
r"""
Encrypts a string using the Type 1 encryption algorithm.
Note that the algorithm as described in the Type 1 specification requires the
plaintext to be prefixed with a number of random bytes. (For ``eexec`` the
number of random bytes is set to 4.) This routine does *not* add the random
prefix to its input.
Args:
plainstring: String of plaintext.
R: Initial key.
Returns:
cipherstring: Ciphertext string.
R: Output key for subsequent encryptions.
Examples::
>>> testStr = b"\0\0asdadads asds\265"
>>> decryptedStr, R = decrypt(testStr, 12321)
>>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
True
>>> R == 36142
True
>>> testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
>>> encryptedStr, R = encrypt(testStr, 12321)
>>> encryptedStr == b"\0\0asdadads asds\265"
True
>>> R == 36142
True
"""
cipherList = []
for plain in plainstring:
cipher, R = _encryptChar(plain, R)
cipherList.append(cipher)
cipherstring = bytesjoin(cipherList)
return cipherstring, int(R) | r""" Encrypts a string using the Type 1 encryption algorithm. Note that the algorithm as described in the Type 1 specification requires the plaintext to be prefixed with a number of random bytes. (For ``eexec`` the number of random bytes is set to 4.) This routine does *not* add the random prefix to its input. Args: plainstring: String of plaintext. R: Initial key. Returns: cipherstring: Ciphertext string. R: Output key for subsequent encryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True >>> testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' >>> encryptedStr, R = encrypt(testStr, 12321) >>> encryptedStr == b"\0\0asdadads asds\265" True >>> R == 36142 True |
175,480 | from fontTools.misc.textTools import bytechr, bytesjoin, byteord
def hexString(s):
import binascii
return binascii.hexlify(s) | null |
175,481 | from fontTools.misc.textTools import bytechr, bytesjoin, byteord
def bytesjoin(iterable, joiner=b""):
return tobytes(joiner).join(tobytes(item) for item in iterable)
def deHexString(h):
import binascii
h = bytesjoin(h.split())
return binascii.unhexlify(h) | null |
175,482 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def byteord(c):
return c if isinstance(c, int) else ord(c)
def read_operator(self, b0, data, index):
if b0 == 12:
op = (b0, byteord(data[index]))
index = index + 1
else:
op = b0
try:
operator = self.operators[op]
except KeyError:
return None, index
value = self.handle_operator(operator)
return value, index | null |
175,483 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def read_byte(self, b0, data, index):
return b0 - 139, index | null |
175,484 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def byteord(c):
return c if isinstance(c, int) else ord(c)
def read_smallInt1(self, b0, data, index):
b1 = byteord(data[index])
return (b0 - 247) * 256 + b1 + 108, index + 1 | null |
175,485 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def byteord(c):
return c if isinstance(c, int) else ord(c)
def read_smallInt2(self, b0, data, index):
b1 = byteord(data[index])
return -(b0 - 251) * 256 - b1 - 108, index + 1 | null |
175,486 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def read_shortInt(self, b0, data, index):
(value,) = struct.unpack(">h", data[index : index + 2])
return value, index + 2 | null |
175,487 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def read_longInt(self, b0, data, index):
(value,) = struct.unpack(">l", data[index : index + 4])
return value, index + 4 | null |
175,488 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def fixedToFloat(value, precisionBits):
"""Converts a fixed-point number to a float given the number of
precision bits.
Args:
value (int): Number in fixed-point format.
precisionBits (int): Number of precision bits.
Returns:
Floating point value.
Examples::
>>> import math
>>> f = fixedToFloat(-10139, precisionBits=14)
>>> math.isclose(f, -0.61883544921875)
True
"""
return value / (1 << precisionBits)
def read_fixed1616(self, b0, data, index):
(value,) = struct.unpack(">l", data[index : index + 4])
return fixedToFloat(value, precisionBits=16), index + 4 | null |
175,489 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
def read_reserved(self, b0, data, index):
assert NotImplementedError
return NotImplemented, index | null |
175,490 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
realNibbles = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
".",
"E",
"E-",
None,
"-",
]
def byteord(c):
return c if isinstance(c, int) else ord(c)
def read_realNumber(self, b0, data, index):
number = ""
while True:
b = byteord(data[index])
index = index + 1
nibble0 = (b & 0xF0) >> 4
nibble1 = b & 0x0F
if nibble0 == 0xF:
break
number = number + realNibbles[nibble0]
if nibble1 == 0xF:
break
number = number + realNibbles[nibble1]
return float(number), index | null |
175,491 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
assert len(t1OperandEncoding) == 256
def buildOperatorDict(operatorList):
oper = {}
opc = {}
for item in operatorList:
if len(item) == 2:
oper[item[0]] = item[1]
else:
oper[item[0]] = item[1:]
if isinstance(item[0], tuple):
opc[item[1]] = item[0]
else:
opc[item[1]] = (item[0],)
return oper, opc | null |
175,492 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
log = logging.getLogger(__name__)
def bytechr(n):
return bytes([n])
def getIntEncoder(format):
if format == "cff":
fourByteOp = bytechr(29)
elif format == "t1":
fourByteOp = bytechr(255)
else:
assert format == "t2"
fourByteOp = None
def encodeInt(
value,
fourByteOp=fourByteOp,
bytechr=bytechr,
pack=struct.pack,
unpack=struct.unpack,
):
if -107 <= value <= 107:
code = bytechr(value + 139)
elif 108 <= value <= 1131:
value = value - 108
code = bytechr((value >> 8) + 247) + bytechr(value & 0xFF)
elif -1131 <= value <= -108:
value = -value - 108
code = bytechr((value >> 8) + 251) + bytechr(value & 0xFF)
elif fourByteOp is None:
# T2 only supports 2 byte ints
if -32768 <= value <= 32767:
code = bytechr(28) + pack(">h", value)
else:
# Backwards compatible hack: due to a previous bug in FontTools,
# 16.16 fixed numbers were written out as 4-byte ints. When
# these numbers were small, they were wrongly written back as
# small ints instead of 4-byte ints, breaking round-tripping.
# This here workaround doesn't do it any better, since we can't
# distinguish anymore between small ints that were supposed to
# be small fixed numbers and small ints that were just small
# ints. Hence the warning.
log.warning(
"4-byte T2 number got passed to the "
"IntType handler. This should happen only when reading in "
"old XML files.\n"
)
code = bytechr(255) + pack(">l", value)
else:
code = fourByteOp + pack(">l", value)
return code
return encodeInt | null |
175,493 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
encodeIntT2 = getIntEncoder("t2")
def floatToFixed(value, precisionBits):
"""Converts a float to a fixed-point number given the number of
precision bits.
Args:
value (float): Floating point value.
precisionBits (int): Number of precision bits.
Returns:
int: Fixed-point representation.
Examples::
>>> floatToFixed(-0.61883544921875, precisionBits=14)
-10139
>>> floatToFixed(-0.61884, precisionBits=14)
-10139
"""
return otRound(value * (1 << precisionBits))
The provided code snippet includes necessary dependencies for implementing the `encodeFixed` function. Write a Python function `def encodeFixed(f, pack=struct.pack)` to solve the following problem:
For T2 only
Here is the function:
def encodeFixed(f, pack=struct.pack):
"""For T2 only"""
value = floatToFixed(f, precisionBits=16)
if value & 0xFFFF == 0: # check if the fractional part is zero
return encodeIntT2(value >> 16) # encode only the integer part
else:
return b"\xff" + pack(">l", value) # encode the entire fixed point value | For T2 only |
175,494 | from fontTools.misc.fixedTools import (
fixedToFloat,
floatToFixed,
floatToFixedToStr,
strToFixedToFloat,
)
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
from fontTools.pens.boundsPen import BoundsPen
import struct
import logging
assert len(t1OperandEncoding) == 256
realNibblesDict = {v: i for i, v in enumerate(realNibbles)}
realZeroBytes = bytechr(30) + bytechr(0xF)
def bytechr(n):
return bytes([n])
def encodeFloat(f):
# For CFF only, used in cffLib
if f == 0.0: # 0.0 == +0.0 == -0.0
return realZeroBytes
# Note: 14 decimal digits seems to be the limitation for CFF real numbers
# in macOS. However, we use 8 here to match the implementation of AFDKO.
s = "%.8G" % f
if s[:2] == "0.":
s = s[1:]
elif s[:3] == "-0.":
s = "-" + s[2:]
nibbles = []
while s:
c = s[0]
s = s[1:]
if c == "E":
c2 = s[:1]
if c2 == "-":
s = s[1:]
c = "E-"
elif c2 == "+":
s = s[1:]
nibbles.append(realNibblesDict[c])
nibbles.append(0xF)
if len(nibbles) % 2:
nibbles.append(0xF)
d = bytechr(30)
for i in range(0, len(nibbles), 2):
d = d + bytechr(nibbles[i] << 4 | nibbles[i + 1])
return d | null |
175,495 | from fontTools.misc.textTools import byteord, strjoin, tobytes, tostr
import sys
import os
import string
def escape(data):
data = tostr(data, "utf_8")
data = data.replace("&", "&")
data = data.replace("<", "<")
data = data.replace(">", ">")
data = data.replace("\r", " ")
return data
def escapeattr(data):
data = escape(data)
data = data.replace('"', """)
return data | null |
175,496 | from fontTools.misc.textTools import byteord, strjoin, tobytes, tostr
import sys
import os
import string
def strjoin(iterable, joiner=""):
return tostr(joiner).join(iterable)
The provided code snippet includes necessary dependencies for implementing the `escape8bit` function. Write a Python function `def escape8bit(data)` to solve the following problem:
Input is Unicode string.
Here is the function:
def escape8bit(data):
"""Input is Unicode string."""
def escapechar(c):
n = ord(c)
if 32 <= n <= 127 and c not in "<&>":
return c
else:
return "&#" + repr(n) + ";"
return strjoin(map(escapechar, data.decode("latin-1"))) | Input is Unicode string. |
175,497 | from fontTools.misc.textTools import byteord, strjoin, tobytes, tostr
import sys
import os
import string
def byteord(c):
return c if isinstance(c, int) else ord(c)
def hexStr(s):
h = string.hexdigits
r = ""
for c in s:
i = byteord(c)
r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
return r | null |
175,498 | from fontTools.misc.textTools import Tag, bytesjoin, strjoin
def strjoin(iterable, joiner=""):
def _reverseString(s):
s = list(s)
s.reverse()
return strjoin(s) | null |
175,499 | from fontTools.misc.textTools import Tag, bytesjoin, strjoin
try:
import xattr
except ImportError:
xattr = None
def pad(data, size):
r"""Pad byte string 'data' with null bytes until its length is a
multiple of 'size'.
>>> len(pad(b'abcd', 4))
4
>>> len(pad(b'abcde', 2))
6
>>> len(pad(b'abcde', 4))
8
>>> pad(b'abcdef', 4) == b'abcdef\x00\x00'
True
"""
data = tobytes(data)
if size > 1:
remainder = len(data) % size
if remainder:
data += b"\0" * (size - remainder)
return data
def bytesjoin(iterable, joiner=b""):
return tobytes(joiner).join(tobytes(item) for item in iterable)
The provided code snippet includes necessary dependencies for implementing the `setMacCreatorAndType` function. Write a Python function `def setMacCreatorAndType(path, fileCreator, fileType)` to solve the following problem:
Set file creator and file type codes for a path. Note that if the ``xattr`` module is not installed, no action is taken but no error is raised. Args: path (str): A file path. fileCreator: A four-character file creator tag. fileType: A four-character file type tag.
Here is the function:
def setMacCreatorAndType(path, fileCreator, fileType):
"""Set file creator and file type codes for a path.
Note that if the ``xattr`` module is not installed, no action is
taken but no error is raised.
Args:
path (str): A file path.
fileCreator: A four-character file creator tag.
fileType: A four-character file type tag.
"""
if xattr is not None:
from fontTools.misc.textTools import pad
if not all(len(s) == 4 for s in (fileCreator, fileType)):
raise TypeError("arg must be string of 4 chars")
finderInfo = pad(bytesjoin([fileType, fileCreator]), 32)
xattr.setxattr(path, "com.apple.FinderInfo", finderInfo) | Set file creator and file type codes for a path. Note that if the ``xattr`` module is not installed, no action is taken but no error is raised. Args: path (str): A file path. fileCreator: A four-character file creator tag. fileType: A four-character file type tag. |
175,500 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
def calcBounds(array):
"""Calculate the bounding rectangle of a 2D points array.
Args:
array: A sequence of 2D tuples.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
"""
if not array:
return 0, 0, 0, 0
xs = [x for x, y in array]
ys = [y for x, y in array]
return min(xs), min(ys), max(xs), max(ys)
def otRound(value):
"""Round float value to nearest integer towards ``+Infinity``.
The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_)
defines the required method for converting floating point values to
fixed-point. In particular it specifies the following rounding strategy:
for fractional values of 0.5 and higher, take the next higher integer;
for other fractional values, truncate.
This function rounds the floating-point value according to this strategy
in preparation for conversion to fixed-point.
Args:
value (float): The input floating-point value.
Returns
float: The rounded value.
"""
# See this thread for how we ended up with this implementation:
# https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166
return int(math.floor(value + 0.5))
The provided code snippet includes necessary dependencies for implementing the `calcIntBounds` function. Write a Python function `def calcIntBounds(array, round=otRound)` to solve the following problem:
Calculate the integer bounding rectangle of a 2D points array. Values are rounded to closest integer towards ``+Infinity`` using the :func:`fontTools.misc.fixedTools.otRound` function by default, unless an optional ``round`` function is passed. Args: array: A sequence of 2D tuples. round: A rounding function of type ``f(x: float) -> int``. Returns: A four-item tuple of integers representing the bounding rectangle: ``(xMin, yMin, xMax, yMax)``.
Here is the function:
def calcIntBounds(array, round=otRound):
"""Calculate the integer bounding rectangle of a 2D points array.
Values are rounded to closest integer towards ``+Infinity`` using the
:func:`fontTools.misc.fixedTools.otRound` function by default, unless
an optional ``round`` function is passed.
Args:
array: A sequence of 2D tuples.
round: A rounding function of type ``f(x: float) -> int``.
Returns:
A four-item tuple of integers representing the bounding rectangle:
``(xMin, yMin, xMax, yMax)``.
"""
return tuple(round(v) for v in calcBounds(array)) | Calculate the integer bounding rectangle of a 2D points array. Values are rounded to closest integer towards ``+Infinity`` using the :func:`fontTools.misc.fixedTools.otRound` function by default, unless an optional ``round`` function is passed. Args: array: A sequence of 2D tuples. round: A rounding function of type ``f(x: float) -> int``. Returns: A four-item tuple of integers representing the bounding rectangle: ``(xMin, yMin, xMax, yMax)``. |
175,501 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `updateBounds` function. Write a Python function `def updateBounds(bounds, p, min=min, max=max)` to solve the following problem:
Add a point to a bounding rectangle. Args: bounds: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. p: A 2D tuple representing a point. min,max: functions to compute the minimum and maximum. Returns: The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``.
Here is the function:
def updateBounds(bounds, p, min=min, max=max):
"""Add a point to a bounding rectangle.
Args:
bounds: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
p: A 2D tuple representing a point.
min,max: functions to compute the minimum and maximum.
Returns:
The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``.
"""
(x, y) = p
xMin, yMin, xMax, yMax = bounds
return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y) | Add a point to a bounding rectangle. Args: bounds: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. p: A 2D tuple representing a point. min,max: functions to compute the minimum and maximum. Returns: The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``. |
175,502 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `pointInRect` function. Write a Python function `def pointInRect(p, rect)` to solve the following problem:
Test if a point is inside a bounding rectangle. Args: p: A 2D tuple representing a point. rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. Returns: ``True`` if the point is inside the rectangle, ``False`` otherwise.
Here is the function:
def pointInRect(p, rect):
"""Test if a point is inside a bounding rectangle.
Args:
p: A 2D tuple representing a point.
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
``True`` if the point is inside the rectangle, ``False`` otherwise.
"""
(x, y) = p
xMin, yMin, xMax, yMax = rect
return (xMin <= x <= xMax) and (yMin <= y <= yMax) | Test if a point is inside a bounding rectangle. Args: p: A 2D tuple representing a point. rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. Returns: ``True`` if the point is inside the rectangle, ``False`` otherwise. |
175,503 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `pointsInRect` function. Write a Python function `def pointsInRect(array, rect)` to solve the following problem:
Determine which points are inside a bounding rectangle. Args: array: A sequence of 2D tuples. rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. Returns: A list containing the points inside the rectangle.
Here is the function:
def pointsInRect(array, rect):
"""Determine which points are inside a bounding rectangle.
Args:
array: A sequence of 2D tuples.
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
A list containing the points inside the rectangle.
"""
if len(array) < 1:
return []
xMin, yMin, xMax, yMax = rect
return [(xMin <= x <= xMax) and (yMin <= y <= yMax) for x, y in array] | Determine which points are inside a bounding rectangle. Args: array: A sequence of 2D tuples. rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. Returns: A list containing the points inside the rectangle. |
175,504 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `vectorLength` function. Write a Python function `def vectorLength(vector)` to solve the following problem:
Calculate the length of the given vector. Args: vector: A 2D tuple. Returns: The Euclidean length of the vector.
Here is the function:
def vectorLength(vector):
"""Calculate the length of the given vector.
Args:
vector: A 2D tuple.
Returns:
The Euclidean length of the vector.
"""
x, y = vector
return math.sqrt(x**2 + y**2) | Calculate the length of the given vector. Args: vector: A 2D tuple. Returns: The Euclidean length of the vector. |
175,505 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `asInt16` function. Write a Python function `def asInt16(array)` to solve the following problem:
Round a list of floats to 16-bit signed integers. Args: array: List of float values. Returns: A list of rounded integers.
Here is the function:
def asInt16(array):
"""Round a list of floats to 16-bit signed integers.
Args:
array: List of float values.
Returns:
A list of rounded integers.
"""
return [int(math.floor(i + 0.5)) for i in array] | Round a list of floats to 16-bit signed integers. Args: array: List of float values. Returns: A list of rounded integers. |
175,506 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `scaleRect` function. Write a Python function `def scaleRect(rect, x, y)` to solve the following problem:
Scale a bounding box rectangle. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. x: Factor to scale the rectangle along the X axis. Y: Factor to scale the rectangle along the Y axis. Returns: A scaled bounding rectangle.
Here is the function:
def scaleRect(rect, x, y):
"""Scale a bounding box rectangle.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
x: Factor to scale the rectangle along the X axis.
Y: Factor to scale the rectangle along the Y axis.
Returns:
A scaled bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return xMin * x, yMin * y, xMax * x, yMax * y | Scale a bounding box rectangle. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. x: Factor to scale the rectangle along the X axis. Y: Factor to scale the rectangle along the Y axis. Returns: A scaled bounding rectangle. |
175,507 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `offsetRect` function. Write a Python function `def offsetRect(rect, dx, dy)` to solve the following problem:
Offset a bounding box rectangle. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. dx: Amount to offset the rectangle along the X axis. dY: Amount to offset the rectangle along the Y axis. Returns: An offset bounding rectangle.
Here is the function:
def offsetRect(rect, dx, dy):
"""Offset a bounding box rectangle.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
dx: Amount to offset the rectangle along the X axis.
dY: Amount to offset the rectangle along the Y axis.
Returns:
An offset bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return xMin + dx, yMin + dy, xMax + dx, yMax + dy | Offset a bounding box rectangle. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. dx: Amount to offset the rectangle along the X axis. dY: Amount to offset the rectangle along the Y axis. Returns: An offset bounding rectangle. |
175,508 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `insetRect` function. Write a Python function `def insetRect(rect, dx, dy)` to solve the following problem:
Inset a bounding box rectangle on all sides. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. dx: Amount to inset the rectangle along the X axis. dY: Amount to inset the rectangle along the Y axis. Returns: An inset bounding rectangle.
Here is the function:
def insetRect(rect, dx, dy):
"""Inset a bounding box rectangle on all sides.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
dx: Amount to inset the rectangle along the X axis.
dY: Amount to inset the rectangle along the Y axis.
Returns:
An inset bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return xMin + dx, yMin + dy, xMax - dx, yMax - dy | Inset a bounding box rectangle on all sides. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. dx: Amount to inset the rectangle along the X axis. dY: Amount to inset the rectangle along the Y axis. Returns: An inset bounding rectangle. |
175,509 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `unionRect` function. Write a Python function `def unionRect(rect1, rect2)` to solve the following problem:
Determine union of bounding rectangles. Args: rect1: First bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. rect2: Second bounding rectangle. Returns: The smallest rectangle in which both input rectangles are fully enclosed.
Here is the function:
def unionRect(rect1, rect2):
"""Determine union of bounding rectangles.
Args:
rect1: First bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
rect2: Second bounding rectangle.
Returns:
The smallest rectangle in which both input rectangles are fully
enclosed.
"""
(xMin1, yMin1, xMax1, yMax1) = rect1
(xMin2, yMin2, xMax2, yMax2) = rect2
xMin, yMin, xMax, yMax = (
min(xMin1, xMin2),
min(yMin1, yMin2),
max(xMax1, xMax2),
max(yMax1, yMax2),
)
return (xMin, yMin, xMax, yMax) | Determine union of bounding rectangles. Args: rect1: First bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. rect2: Second bounding rectangle. Returns: The smallest rectangle in which both input rectangles are fully enclosed. |
175,510 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `rectCenter` function. Write a Python function `def rectCenter(rect)` to solve the following problem:
Determine rectangle center. Args: rect: Bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. Returns: A 2D tuple representing the point at the center of the rectangle.
Here is the function:
def rectCenter(rect):
"""Determine rectangle center.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
A 2D tuple representing the point at the center of the rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return (xMin + xMax) / 2, (yMin + yMax) / 2 | Determine rectangle center. Args: rect: Bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. Returns: A 2D tuple representing the point at the center of the rectangle. |
175,511 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
def normRect(rect):
"""Normalize a bounding box rectangle.
This function "turns the rectangle the right way up", so that the following
holds::
xMin <= xMax and yMin <= yMax
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
A normalized bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return min(xMin, xMax), min(yMin, yMax), max(xMin, xMax), max(yMin, yMax)
The provided code snippet includes necessary dependencies for implementing the `quantizeRect` function. Write a Python function `def quantizeRect(rect, factor=1)` to solve the following problem:
>>> bounds = (72.3, -218.4, 1201.3, 919.1) >>> quantizeRect(bounds) (72, -219, 1202, 920) >>> quantizeRect(bounds, factor=10) (70, -220, 1210, 920) >>> quantizeRect(bounds, factor=100) (0, -300, 1300, 1000)
Here is the function:
def quantizeRect(rect, factor=1):
"""
>>> bounds = (72.3, -218.4, 1201.3, 919.1)
>>> quantizeRect(bounds)
(72, -219, 1202, 920)
>>> quantizeRect(bounds, factor=10)
(70, -220, 1210, 920)
>>> quantizeRect(bounds, factor=100)
(0, -300, 1300, 1000)
"""
if factor < 1:
raise ValueError(f"Expected quantization factor >= 1, found: {factor!r}")
xMin, yMin, xMax, yMax = normRect(rect)
return (
int(math.floor(xMin / factor) * factor),
int(math.floor(yMin / factor) * factor),
int(math.ceil(xMax / factor) * factor),
int(math.ceil(yMax / factor) * factor),
) | >>> bounds = (72.3, -218.4, 1201.3, 919.1) >>> quantizeRect(bounds) (72, -219, 1202, 920) >>> quantizeRect(bounds, factor=10) (70, -220, 1210, 920) >>> quantizeRect(bounds, factor=100) (0, -300, 1300, 1000) |
175,512 | from fontTools.misc.roundTools import otRound
from fontTools.misc.vector import Vector as _Vector
import math
import warnings
The provided code snippet includes necessary dependencies for implementing the `_test` function. Write a Python function `def _test()` to solve the following problem:
>>> import math >>> calcBounds([]) (0, 0, 0, 0) >>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)]) (0, 10, 80, 100) >>> updateBounds((0, 0, 0, 0), (100, 100)) (0, 0, 100, 100) >>> pointInRect((50, 50), (0, 0, 100, 100)) True >>> pointInRect((0, 0), (0, 0, 100, 100)) True >>> pointInRect((100, 100), (0, 0, 100, 100)) True >>> not pointInRect((101, 100), (0, 0, 100, 100)) True >>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100))) [True, True, True, False] >>> vectorLength((3, 4)) 5.0 >>> vectorLength((1, 1)) == math.sqrt(2) True >>> list(asInt16([0, 0.1, 0.5, 0.9])) [0, 0, 1, 1] >>> normRect((0, 10, 100, 200)) (0, 10, 100, 200) >>> normRect((100, 200, 0, 10)) (0, 10, 100, 200) >>> scaleRect((10, 20, 50, 150), 1.5, 2) (15.0, 40, 75.0, 300) >>> offsetRect((10, 20, 30, 40), 5, 6) (15, 26, 35, 46) >>> insetRect((10, 20, 50, 60), 5, 10) (15, 30, 45, 50) >>> insetRect((10, 20, 50, 60), -5, -10) (5, 10, 55, 70) >>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50)) >>> not intersects True >>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50)) >>> intersects 1 >>> rect (5, 20, 20, 30) >>> unionRect((0, 10, 20, 30), (0, 40, 20, 50)) (0, 10, 20, 50) >>> rectCenter((0, 0, 100, 200)) (50.0, 100.0) >>> rectCenter((0, 0, 100, 199.0)) (50.0, 99.5) >>> intRect((0.9, 2.9, 3.1, 4.1)) (0, 2, 4, 5)
Here is the function:
def _test():
"""
>>> import math
>>> calcBounds([])
(0, 0, 0, 0)
>>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)])
(0, 10, 80, 100)
>>> updateBounds((0, 0, 0, 0), (100, 100))
(0, 0, 100, 100)
>>> pointInRect((50, 50), (0, 0, 100, 100))
True
>>> pointInRect((0, 0), (0, 0, 100, 100))
True
>>> pointInRect((100, 100), (0, 0, 100, 100))
True
>>> not pointInRect((101, 100), (0, 0, 100, 100))
True
>>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100)))
[True, True, True, False]
>>> vectorLength((3, 4))
5.0
>>> vectorLength((1, 1)) == math.sqrt(2)
True
>>> list(asInt16([0, 0.1, 0.5, 0.9]))
[0, 0, 1, 1]
>>> normRect((0, 10, 100, 200))
(0, 10, 100, 200)
>>> normRect((100, 200, 0, 10))
(0, 10, 100, 200)
>>> scaleRect((10, 20, 50, 150), 1.5, 2)
(15.0, 40, 75.0, 300)
>>> offsetRect((10, 20, 30, 40), 5, 6)
(15, 26, 35, 46)
>>> insetRect((10, 20, 50, 60), 5, 10)
(15, 30, 45, 50)
>>> insetRect((10, 20, 50, 60), -5, -10)
(5, 10, 55, 70)
>>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50))
>>> not intersects
True
>>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50))
>>> intersects
1
>>> rect
(5, 20, 20, 30)
>>> unionRect((0, 10, 20, 30), (0, 40, 20, 50))
(0, 10, 20, 50)
>>> rectCenter((0, 0, 100, 200))
(50.0, 100.0)
>>> rectCenter((0, 0, 100, 199.0))
(50.0, 99.5)
>>> intRect((0.9, 2.9, 3.1, 4.1))
(0, 2, 4, 5)
""" | >>> import math >>> calcBounds([]) (0, 0, 0, 0) >>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)]) (0, 10, 80, 100) >>> updateBounds((0, 0, 0, 0), (100, 100)) (0, 0, 100, 100) >>> pointInRect((50, 50), (0, 0, 100, 100)) True >>> pointInRect((0, 0), (0, 0, 100, 100)) True >>> pointInRect((100, 100), (0, 0, 100, 100)) True >>> not pointInRect((101, 100), (0, 0, 100, 100)) True >>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100))) [True, True, True, False] >>> vectorLength((3, 4)) 5.0 >>> vectorLength((1, 1)) == math.sqrt(2) True >>> list(asInt16([0, 0.1, 0.5, 0.9])) [0, 0, 1, 1] >>> normRect((0, 10, 100, 200)) (0, 10, 100, 200) >>> normRect((100, 200, 0, 10)) (0, 10, 100, 200) >>> scaleRect((10, 20, 50, 150), 1.5, 2) (15.0, 40, 75.0, 300) >>> offsetRect((10, 20, 30, 40), 5, 6) (15, 26, 35, 46) >>> insetRect((10, 20, 50, 60), 5, 10) (15, 30, 45, 50) >>> insetRect((10, 20, 50, 60), -5, -10) (5, 10, 55, 70) >>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50)) >>> not intersects True >>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50)) >>> intersects 1 >>> rect (5, 20, 20, 30) >>> unionRect((0, 10, 20, 30), (0, 40, 20, 50)) (0, 10, 20, 50) >>> rectCenter((0, 0, 100, 200)) (50.0, 100.0) >>> rectCenter((0, 0, 100, 199.0)) (50.0, 99.5) >>> intRect((0.9, 2.9, 3.1, 4.1)) (0, 2, 4, 5) |
175,513 | from fontTools.pens.basePen import BasePen
from functools import partial
from itertools import count
import sympy as sp
import sys
n = 3
X = tuple(sp.symbols("x:%d" % (n + 1), real=True))
Y = tuple(sp.symbols("y:%d" % (n + 1), real=True))
P = tuple(zip(*(sp.symbols("p:%d[%s]" % (n + 1, w), real=True) for w in "01")))
for i in range(1, n + 1):
last = BinomialCoefficient[-1]
this = tuple(last[j - 1] + last[j] for j in range(len(last))) + (0,)
BinomialCoefficient.append(this)
BezierCurve = tuple(
tuple(
sum(P[i][j] * bernstein for i, bernstein in enumerate(bernsteins))
for j in range(2)
)
for n, bernsteins in enumerate(BernsteinPolynomial)
)
def green(f, curveXY):
f = -sp.integrate(sp.sympify(f), y)
f = f.subs({x: curveXY[0], y: curveXY[1]})
f = sp.integrate(f * sp.diff(curveXY[0], t), (t, 0, 1))
return f
def count(start: _N = ..., step: _N = ...) -> Iterator[_N]: ... # more general types?
def printGreenPen(penName, funcs, file=sys.stdout, docstring=None):
if docstring is not None:
print('"""%s"""' % docstring)
print(
"""from fontTools.pens.basePen import BasePen, OpenContourError
try:
import cython
COMPILED = cython.compiled
except (AttributeError, ImportError):
# if cython not installed, use mock module with no-op decorators and types
from fontTools.misc import cython
COMPILED = False
__all__ = ["%s"]
class %s(BasePen):
def __init__(self, glyphset=None):
BasePen.__init__(self, glyphset)
"""
% (penName, penName),
file=file,
)
for name, f in funcs:
print(" self.%s = 0" % name, file=file)
print(
"""
def _moveTo(self, p0):
self.__startPoint = p0
def _closePath(self):
p0 = self._getCurrentPoint()
if p0 != self.__startPoint:
self._lineTo(self.__startPoint)
def _endPath(self):
p0 = self._getCurrentPoint()
if p0 != self.__startPoint:
# Green theorem is not defined on open contours.
raise OpenContourError(
"Green theorem is not defined on open contours."
)
""",
end="",
file=file,
)
for n in (1, 2, 3):
subs = {P[i][j]: [X, Y][j][i] for i in range(n + 1) for j in range(2)}
greens = [green(f, BezierCurve[n]) for name, f in funcs]
greens = [sp.gcd_terms(f.collect(sum(P, ()))) for f in greens] # Optimize
greens = [f.subs(subs) for f in greens] # Convert to p to x/y
defs, exprs = sp.cse(
greens,
optimizations="basic",
symbols=(sp.Symbol("r%d" % i) for i in count()),
)
print()
for name, value in defs:
print(" @cython.locals(%s=cython.double)" % name, file=file)
if n == 1:
print(
"""\
@cython.locals(x0=cython.double, y0=cython.double)
@cython.locals(x1=cython.double, y1=cython.double)
def _lineTo(self, p1):
x0,y0 = self._getCurrentPoint()
x1,y1 = p1
""",
file=file,
)
elif n == 2:
print(
"""\
@cython.locals(x0=cython.double, y0=cython.double)
@cython.locals(x1=cython.double, y1=cython.double)
@cython.locals(x2=cython.double, y2=cython.double)
def _qCurveToOne(self, p1, p2):
x0,y0 = self._getCurrentPoint()
x1,y1 = p1
x2,y2 = p2
""",
file=file,
)
elif n == 3:
print(
"""\
@cython.locals(x0=cython.double, y0=cython.double)
@cython.locals(x1=cython.double, y1=cython.double)
@cython.locals(x2=cython.double, y2=cython.double)
@cython.locals(x3=cython.double, y3=cython.double)
def _curveToOne(self, p1, p2, p3):
x0,y0 = self._getCurrentPoint()
x1,y1 = p1
x2,y2 = p2
x3,y3 = p3
""",
file=file,
)
for name, value in defs:
print(" %s = %s" % (name, value), file=file)
print(file=file)
for name, value in zip([f[0] for f in funcs], exprs):
print(" self.%s += %s" % (name, value), file=file)
print(
"""
if __name__ == '__main__':
from fontTools.misc.symfont import x, y, printGreenPen
printGreenPen('%s', ["""
% penName,
file=file,
)
for name, f in funcs:
print(" ('%s', %s)," % (name, str(f)), file=file)
print(" ])", file=file) | null |
175,514 | from numbers import Number
import math
import operator
import warnings
def _operator_rsub(a, b):
return operator.sub(b, a) | null |
175,515 | from numbers import Number
import math
import operator
import warnings
def _operator_rtruediv(a, b):
return operator.truediv(b, a) | null |
175,516 | from fontTools.misc.fixedTools import fixedToFloat as fi2fl, floatToFixed as fl2fi
from fontTools.misc.textTools import tobytes, tostr
import struct
import re
def unpack(fmt, data, obj=None):
if obj is None:
obj = {}
data = tobytes(data)
formatstring, names, fixes = getformat(fmt)
if isinstance(obj, dict):
d = obj
else:
d = obj.__dict__
elements = struct.unpack(formatstring, data)
for i in range(len(names)):
name = names[i]
value = elements[i]
if name in fixes:
# fixed point conversion
value = fi2fl(value, fixes[name])
elif isinstance(value, bytes):
try:
value = tostr(value)
except UnicodeDecodeError:
pass
d[name] = value
return obj
def calcsize(fmt):
formatstring, names, fixes = getformat(fmt)
return struct.calcsize(formatstring)
def unpack2(fmt, data, obj=None):
length = calcsize(fmt)
return unpack(fmt, data[:length], obj), data[length:] | null |
175,517 | from fontTools.misc.fixedTools import fixedToFloat as fi2fl, floatToFixed as fl2fi
from fontTools.misc.textTools import tobytes, tostr
import struct
import re
def pack(fmt, obj):
formatstring, names, fixes = getformat(fmt, keep_pad_byte=True)
elements = []
if not isinstance(obj, dict):
obj = obj.__dict__
for name in names:
value = obj[name]
if name in fixes:
# fixed point conversion
value = fl2fi(value, fixes[name])
elif isinstance(value, str):
value = tobytes(value)
elements.append(value)
data = struct.pack(*(formatstring,) + tuple(elements))
return data
def unpack(fmt, data, obj=None):
if obj is None:
obj = {}
data = tobytes(data)
formatstring, names, fixes = getformat(fmt)
if isinstance(obj, dict):
d = obj
else:
d = obj.__dict__
elements = struct.unpack(formatstring, data)
for i in range(len(names)):
name = names[i]
value = elements[i]
if name in fixes:
# fixed point conversion
value = fi2fl(value, fixes[name])
elif isinstance(value, bytes):
try:
value = tostr(value)
except UnicodeDecodeError:
pass
d[name] = value
return obj
def calcsize(fmt):
formatstring, names, fixes = getformat(fmt)
return struct.calcsize(formatstring)
def _test():
fmt = """
# comments are allowed
> # big endian (see documentation for struct)
# empty lines are allowed:
ashort: h
along: l
abyte: b # a byte
achar: c
astr: 5s
afloat: f; adouble: d # multiple "statements" are allowed
afixed: 16.16F
abool: ?
apad: x
"""
print("size:", calcsize(fmt))
class foo(object):
pass
i = foo()
i.ashort = 0x7FFF
i.along = 0x7FFFFFFF
i.abyte = 0x7F
i.achar = "a"
i.astr = "12345"
i.afloat = 0.5
i.adouble = 0.5
i.afixed = 1.5
i.abool = True
data = pack(fmt, i)
print("data:", repr(data))
print(unpack(fmt, data))
i2 = foo()
unpack(fmt, data, i2)
print(vars(i2)) | null |
175,518 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005):
"""Calculates the arc length for a cubic Bezier segment.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
tolerance: Controls the precision of the calcuation.
Returns:
Arc length value.
"""
mult = 1.0 + 1.5 * tolerance # The 1.5 is a empirical hack; no math
return _calcCubicArcLengthCRecurse(mult, pt1, pt2, pt3, pt4)
from math import sqrt, acos, cos, pi
The provided code snippet includes necessary dependencies for implementing the `calcCubicArcLength` function. Write a Python function `def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005)` to solve the following problem:
Calculates the arc length for a cubic Bezier segment. Whereas :func:`approximateCubicArcLength` approximates the length, this function calculates it by "measuring", recursively dividing the curve until the divided segments are shorter than ``tolerance``. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples. tolerance: Controls the precision of the calcuation. Returns: Arc length value.
Here is the function:
def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005):
"""Calculates the arc length for a cubic Bezier segment.
Whereas :func:`approximateCubicArcLength` approximates the length, this
function calculates it by "measuring", recursively dividing the curve
until the divided segments are shorter than ``tolerance``.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
tolerance: Controls the precision of the calcuation.
Returns:
Arc length value.
"""
return calcCubicArcLengthC(
complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4), tolerance
) | Calculates the arc length for a cubic Bezier segment. Whereas :func:`approximateCubicArcLength` approximates the length, this function calculates it by "measuring", recursively dividing the curve until the divided segments are shorter than ``tolerance``. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples. tolerance: Controls the precision of the calcuation. Returns: Arc length value. |
175,519 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
def calcQuadraticArcLengthC(pt1, pt2, pt3):
"""Calculates the arc length for a quadratic Bezier segment.
Args:
pt1: Start point of the Bezier as a complex number.
pt2: Handle point of the Bezier as a complex number.
pt3: End point of the Bezier as a complex number.
Returns:
Arc length value.
"""
# Analytical solution to the length of a quadratic bezier.
# Documentation: https://github.com/fonttools/fonttools/issues/3055
d0 = pt2 - pt1
d1 = pt3 - pt2
d = d1 - d0
n = d * 1j
scale = abs(n)
if scale == 0.0:
return abs(pt3 - pt1)
origDist = _dot(n, d0)
if abs(origDist) < epsilon:
if _dot(d0, d1) >= 0:
return abs(pt3 - pt1)
a, b = abs(d0), abs(d1)
return (a * a + b * b) / (a + b)
x0 = _dot(d, d0) / origDist
x1 = _dot(d, d1) / origDist
Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0)))
return Len
from math import sqrt, acos, cos, pi
The provided code snippet includes necessary dependencies for implementing the `calcQuadraticArcLength` function. Write a Python function `def calcQuadraticArcLength(pt1, pt2, pt3)` to solve the following problem:
Calculates the arc length for a quadratic Bezier segment. Args: pt1: Start point of the Bezier as 2D tuple. pt2: Handle point of the Bezier as 2D tuple. pt3: End point of the Bezier as 2D tuple. Returns: Arc length value. Example:: >>> calcQuadraticArcLength((0, 0), (0, 0), (0, 0)) # empty segment 0.0 >>> calcQuadraticArcLength((0, 0), (50, 0), (80, 0)) # collinear points 80.0 >>> calcQuadraticArcLength((0, 0), (0, 50), (0, 80)) # collinear points vertical 80.0 >>> calcQuadraticArcLength((0, 0), (50, 20), (100, 40)) # collinear points 107.70329614269008 >>> calcQuadraticArcLength((0, 0), (0, 100), (100, 0)) 154.02976155645263 >>> calcQuadraticArcLength((0, 0), (0, 50), (100, 0)) 120.21581243984076 >>> calcQuadraticArcLength((0, 0), (50, -10), (80, 50)) 102.53273816445825 >>> calcQuadraticArcLength((0, 0), (40, 0), (-40, 0)) # collinear points, control point outside 66.66666666666667 >>> calcQuadraticArcLength((0, 0), (40, 0), (0, 0)) # collinear points, looping back 40.0
Here is the function:
def calcQuadraticArcLength(pt1, pt2, pt3):
"""Calculates the arc length for a quadratic Bezier segment.
Args:
pt1: Start point of the Bezier as 2D tuple.
pt2: Handle point of the Bezier as 2D tuple.
pt3: End point of the Bezier as 2D tuple.
Returns:
Arc length value.
Example::
>>> calcQuadraticArcLength((0, 0), (0, 0), (0, 0)) # empty segment
0.0
>>> calcQuadraticArcLength((0, 0), (50, 0), (80, 0)) # collinear points
80.0
>>> calcQuadraticArcLength((0, 0), (0, 50), (0, 80)) # collinear points vertical
80.0
>>> calcQuadraticArcLength((0, 0), (50, 20), (100, 40)) # collinear points
107.70329614269008
>>> calcQuadraticArcLength((0, 0), (0, 100), (100, 0))
154.02976155645263
>>> calcQuadraticArcLength((0, 0), (0, 50), (100, 0))
120.21581243984076
>>> calcQuadraticArcLength((0, 0), (50, -10), (80, 50))
102.53273816445825
>>> calcQuadraticArcLength((0, 0), (40, 0), (-40, 0)) # collinear points, control point outside
66.66666666666667
>>> calcQuadraticArcLength((0, 0), (40, 0), (0, 0)) # collinear points, looping back
40.0
"""
return calcQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3)) | Calculates the arc length for a quadratic Bezier segment. Args: pt1: Start point of the Bezier as 2D tuple. pt2: Handle point of the Bezier as 2D tuple. pt3: End point of the Bezier as 2D tuple. Returns: Arc length value. Example:: >>> calcQuadraticArcLength((0, 0), (0, 0), (0, 0)) # empty segment 0.0 >>> calcQuadraticArcLength((0, 0), (50, 0), (80, 0)) # collinear points 80.0 >>> calcQuadraticArcLength((0, 0), (0, 50), (0, 80)) # collinear points vertical 80.0 >>> calcQuadraticArcLength((0, 0), (50, 20), (100, 40)) # collinear points 107.70329614269008 >>> calcQuadraticArcLength((0, 0), (0, 100), (100, 0)) 154.02976155645263 >>> calcQuadraticArcLength((0, 0), (0, 50), (100, 0)) 120.21581243984076 >>> calcQuadraticArcLength((0, 0), (50, -10), (80, 50)) 102.53273816445825 >>> calcQuadraticArcLength((0, 0), (40, 0), (-40, 0)) # collinear points, control point outside 66.66666666666667 >>> calcQuadraticArcLength((0, 0), (40, 0), (0, 0)) # collinear points, looping back 40.0 |
175,520 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
def approximateQuadraticArcLengthC(pt1, pt2, pt3):
"""Calculates the arc length for a quadratic Bezier segment.
Uses Gauss-Legendre quadrature for a branch-free approximation.
See :func:`calcQuadraticArcLength` for a slower but more accurate result.
Args:
pt1: Start point of the Bezier as a complex number.
pt2: Handle point of the Bezier as a complex number.
pt3: End point of the Bezier as a complex number.
Returns:
Approximate arc length value.
"""
# This, essentially, approximates the length-of-derivative function
# to be integrated with the best-matching fifth-degree polynomial
# approximation of it.
#
# https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Legendre_quadrature
# abs(BezierCurveC[2].diff(t).subs({t:T})) for T in sorted(.5, .5±sqrt(3/5)/2),
# weighted 5/18, 8/18, 5/18 respectively.
v0 = abs(
-0.492943519233745 * pt1 + 0.430331482911935 * pt2 + 0.0626120363218102 * pt3
)
v1 = abs(pt3 - pt1) * 0.4444444444444444
v2 = abs(
-0.0626120363218102 * pt1 - 0.430331482911935 * pt2 + 0.492943519233745 * pt3
)
return v0 + v1 + v2
from math import sqrt, acos, cos, pi
The provided code snippet includes necessary dependencies for implementing the `approximateQuadraticArcLength` function. Write a Python function `def approximateQuadraticArcLength(pt1, pt2, pt3)` to solve the following problem:
Calculates the arc length for a quadratic Bezier segment. Uses Gauss-Legendre quadrature for a branch-free approximation. See :func:`calcQuadraticArcLength` for a slower but more accurate result. Args: pt1: Start point of the Bezier as 2D tuple. pt2: Handle point of the Bezier as 2D tuple. pt3: End point of the Bezier as 2D tuple. Returns: Approximate arc length value.
Here is the function:
def approximateQuadraticArcLength(pt1, pt2, pt3):
"""Calculates the arc length for a quadratic Bezier segment.
Uses Gauss-Legendre quadrature for a branch-free approximation.
See :func:`calcQuadraticArcLength` for a slower but more accurate result.
Args:
pt1: Start point of the Bezier as 2D tuple.
pt2: Handle point of the Bezier as 2D tuple.
pt3: End point of the Bezier as 2D tuple.
Returns:
Approximate arc length value.
"""
return approximateQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3)) | Calculates the arc length for a quadratic Bezier segment. Uses Gauss-Legendre quadrature for a branch-free approximation. See :func:`calcQuadraticArcLength` for a slower but more accurate result. Args: pt1: Start point of the Bezier as 2D tuple. pt2: Handle point of the Bezier as 2D tuple. pt3: End point of the Bezier as 2D tuple. Returns: Approximate arc length value. |
175,521 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
def approximateCubicArcLengthC(pt1, pt2, pt3, pt4):
"""Approximates the arc length for a cubic Bezier segment.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
Returns:
Arc length value.
"""
# This, essentially, approximates the length-of-derivative function
# to be integrated with the best-matching seventh-degree polynomial
# approximation of it.
#
# https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Lobatto_rules
# abs(BezierCurveC[3].diff(t).subs({t:T})) for T in sorted(0, .5±(3/7)**.5/2, .5, 1),
# weighted 1/20, 49/180, 32/90, 49/180, 1/20 respectively.
v0 = abs(pt2 - pt1) * 0.15
v1 = abs(
-0.558983582205757 * pt1
+ 0.325650248872424 * pt2
+ 0.208983582205757 * pt3
+ 0.024349751127576 * pt4
)
v2 = abs(pt4 - pt1 + pt3 - pt2) * 0.26666666666666666
v3 = abs(
-0.024349751127576 * pt1
- 0.208983582205757 * pt2
- 0.325650248872424 * pt3
+ 0.558983582205757 * pt4
)
v4 = abs(pt4 - pt3) * 0.15
return v0 + v1 + v2 + v3 + v4
from math import sqrt, acos, cos, pi
The provided code snippet includes necessary dependencies for implementing the `approximateCubicArcLength` function. Write a Python function `def approximateCubicArcLength(pt1, pt2, pt3, pt4)` to solve the following problem:
Approximates the arc length for a cubic Bezier segment. Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length. See :func:`calcCubicArcLength` for a slower but more accurate result. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples. Returns: Arc length value. Example:: >>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0)) 190.04332968932817 >>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100)) 154.8852074945903 >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150. 149.99999999999991 >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150. 136.9267662156362 >>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp 154.80848416537057
Here is the function:
def approximateCubicArcLength(pt1, pt2, pt3, pt4):
"""Approximates the arc length for a cubic Bezier segment.
Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length.
See :func:`calcCubicArcLength` for a slower but more accurate result.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
Returns:
Arc length value.
Example::
>>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0))
190.04332968932817
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100))
154.8852074945903
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150.
149.99999999999991
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150.
136.9267662156362
>>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp
154.80848416537057
"""
return approximateCubicArcLengthC(
complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4)
) | Approximates the arc length for a cubic Bezier segment. Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length. See :func:`calcCubicArcLength` for a slower but more accurate result. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples. Returns: Arc length value. Example:: >>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0)) 190.04332968932817 >>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100)) 154.8852074945903 >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150. 149.99999999999991 >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150. 136.9267662156362 >>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp 154.80848416537057 |
175,522 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
a=cython.double,
from math import sqrt, acos, cos, pi
The provided code snippet includes necessary dependencies for implementing the `splitLine` function. Write a Python function `def splitLine(pt1, pt2, where, isHorizontal)` to solve the following problem:
Split a line at a given coordinate. Args: pt1: Start point of line as 2D tuple. pt2: End point of line as 2D tuple. where: Position at which to split the line. isHorizontal: Direction of the ray splitting the line. If true, ``where`` is interpreted as a Y coordinate; if false, then ``where`` is interpreted as an X coordinate. Returns: A list of two line segments (each line segment being two 2D tuples) if the line was successfully split, or a list containing the original line. Example:: >>> printSegments(splitLine((0, 0), (100, 100), 50, True)) ((0, 0), (50, 50)) ((50, 50), (100, 100)) >>> printSegments(splitLine((0, 0), (100, 100), 100, True)) ((0, 0), (100, 100)) >>> printSegments(splitLine((0, 0), (100, 100), 0, True)) ((0, 0), (0, 0)) ((0, 0), (100, 100)) >>> printSegments(splitLine((0, 0), (100, 100), 0, False)) ((0, 0), (0, 0)) ((0, 0), (100, 100)) >>> printSegments(splitLine((100, 0), (0, 0), 50, False)) ((100, 0), (50, 0)) ((50, 0), (0, 0)) >>> printSegments(splitLine((0, 100), (0, 0), 50, True)) ((0, 100), (0, 50)) ((0, 50), (0, 0))
Here is the function:
def splitLine(pt1, pt2, where, isHorizontal):
"""Split a line at a given coordinate.
Args:
pt1: Start point of line as 2D tuple.
pt2: End point of line as 2D tuple.
where: Position at which to split the line.
isHorizontal: Direction of the ray splitting the line. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two line segments (each line segment being two 2D tuples)
if the line was successfully split, or a list containing the original
line.
Example::
>>> printSegments(splitLine((0, 0), (100, 100), 50, True))
((0, 0), (50, 50))
((50, 50), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 100, True))
((0, 0), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 0, True))
((0, 0), (0, 0))
((0, 0), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 0, False))
((0, 0), (0, 0))
((0, 0), (100, 100))
>>> printSegments(splitLine((100, 0), (0, 0), 50, False))
((100, 0), (50, 0))
((50, 0), (0, 0))
>>> printSegments(splitLine((0, 100), (0, 0), 50, True))
((0, 100), (0, 50))
((0, 50), (0, 0))
"""
pt1x, pt1y = pt1
pt2x, pt2y = pt2
ax = pt2x - pt1x
ay = pt2y - pt1y
bx = pt1x
by = pt1y
a = (ax, ay)[isHorizontal]
if a == 0:
return [(pt1, pt2)]
t = (where - (bx, by)[isHorizontal]) / a
if 0 <= t < 1:
midPt = ax * t + bx, ay * t + by
return [(pt1, midPt), (midPt, pt2)]
else:
return [(pt1, pt2)] | Split a line at a given coordinate. Args: pt1: Start point of line as 2D tuple. pt2: End point of line as 2D tuple. where: Position at which to split the line. isHorizontal: Direction of the ray splitting the line. If true, ``where`` is interpreted as a Y coordinate; if false, then ``where`` is interpreted as an X coordinate. Returns: A list of two line segments (each line segment being two 2D tuples) if the line was successfully split, or a list containing the original line. Example:: >>> printSegments(splitLine((0, 0), (100, 100), 50, True)) ((0, 0), (50, 50)) ((50, 50), (100, 100)) >>> printSegments(splitLine((0, 0), (100, 100), 100, True)) ((0, 0), (100, 100)) >>> printSegments(splitLine((0, 0), (100, 100), 0, True)) ((0, 0), (0, 0)) ((0, 0), (100, 100)) >>> printSegments(splitLine((0, 0), (100, 100), 0, False)) ((0, 0), (0, 0)) ((0, 0), (100, 100)) >>> printSegments(splitLine((100, 0), (0, 0), 50, False)) ((100, 0), (50, 0)) ((50, 0), (0, 0)) >>> printSegments(splitLine((0, 100), (0, 0), 50, True)) ((0, 100), (0, 50)) ((0, 50), (0, 0)) |
175,523 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
a=cython.double,
b=cython.double,
def _splitQuadraticAtT(a, b, c, *ts):
ts = list(ts)
segments = []
ts.insert(0, 0.0)
ts.append(1.0)
ax, ay = a
bx, by = b
cx, cy = c
for i in range(len(ts) - 1):
t1 = ts[i]
t2 = ts[i + 1]
delta = t2 - t1
# calc new a, b and c
delta_2 = delta * delta
a1x = ax * delta_2
a1y = ay * delta_2
b1x = (2 * ax * t1 + bx) * delta
b1y = (2 * ay * t1 + by) * delta
t1_2 = t1 * t1
c1x = ax * t1_2 + bx * t1 + cx
c1y = ay * t1_2 + by * t1 + cy
pt1, pt2, pt3 = calcQuadraticPoints((a1x, a1y), (b1x, b1y), (c1x, c1y))
segments.append((pt1, pt2, pt3))
return segments
from math import sqrt, acos, cos, pi
def solveQuadratic(a, b, c, sqrt=sqrt):
"""Solve a quadratic equation.
Solves *a*x*x + b*x + c = 0* where a, b and c are real.
Args:
a: coefficient of *x²*
b: coefficient of *x*
c: constant term
Returns:
A list of roots. Note that the returned list is neither guaranteed to
be sorted nor to contain unique values!
"""
if abs(a) < epsilon:
if abs(b) < epsilon:
# We have a non-equation; therefore, we have no valid solution
roots = []
else:
# We have a linear equation with 1 root.
roots = [-c / b]
else:
# We have a true quadratic equation. Apply the quadratic formula to find two roots.
DD = b * b - 4.0 * a * c
if DD >= 0.0:
rDD = sqrt(DD)
roots = [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a]
else:
# complex roots, ignore
roots = []
return roots
def calcQuadraticParameters(pt1, pt2, pt3):
x2, y2 = pt2
x3, y3 = pt3
cx, cy = pt1
bx = (x2 - cx) * 2.0
by = (y2 - cy) * 2.0
ax = x3 - cx - bx
ay = y3 - cy - by
return (ax, ay), (bx, by), (cx, cy)
The provided code snippet includes necessary dependencies for implementing the `splitQuadratic` function. Write a Python function `def splitQuadratic(pt1, pt2, pt3, where, isHorizontal)` to solve the following problem:
Split a quadratic Bezier curve at a given coordinate. Args: pt1,pt2,pt3: Control points of the Bezier as 2D tuples. where: Position at which to split the curve. isHorizontal: Direction of the ray splitting the curve. If true, ``where`` is interpreted as a Y coordinate; if false, then ``where`` is interpreted as an X coordinate. Returns: A list of two curve segments (each curve segment being three 2D tuples) if the curve was successfully split, or a list containing the original curve. Example:: >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False)) ((0, 0), (50, 100), (100, 0)) >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False)) ((0, 0), (25, 50), (50, 50)) ((50, 50), (75, 50), (100, 0)) >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False)) ((0, 0), (12.5, 25), (25, 37.5)) ((25, 37.5), (62.5, 75), (100, 0)) >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True)) ((0, 0), (7.32233, 14.6447), (14.6447, 25)) ((14.6447, 25), (50, 75), (85.3553, 25)) ((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15)) >>> # XXX I'm not at all sure if the following behavior is desirable: >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True)) ((0, 0), (25, 50), (50, 50)) ((50, 50), (50, 50), (50, 50)) ((50, 50), (75, 50), (100, 0))
Here is the function:
def splitQuadratic(pt1, pt2, pt3, where, isHorizontal):
"""Split a quadratic Bezier curve at a given coordinate.
Args:
pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
where: Position at which to split the curve.
isHorizontal: Direction of the ray splitting the curve. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two curve segments (each curve segment being three 2D tuples)
if the curve was successfully split, or a list containing the original
curve.
Example::
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False))
((0, 0), (50, 100), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False))
((0, 0), (25, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False))
((0, 0), (12.5, 25), (25, 37.5))
((25, 37.5), (62.5, 75), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True))
((0, 0), (7.32233, 14.6447), (14.6447, 25))
((14.6447, 25), (50, 75), (85.3553, 25))
((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15))
>>> # XXX I'm not at all sure if the following behavior is desirable:
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True))
((0, 0), (25, 50), (50, 50))
((50, 50), (50, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
"""
a, b, c = calcQuadraticParameters(pt1, pt2, pt3)
solutions = solveQuadratic(
a[isHorizontal], b[isHorizontal], c[isHorizontal] - where
)
solutions = sorted(t for t in solutions if 0 <= t < 1)
if not solutions:
return [(pt1, pt2, pt3)]
return _splitQuadraticAtT(a, b, c, *solutions) | Split a quadratic Bezier curve at a given coordinate. Args: pt1,pt2,pt3: Control points of the Bezier as 2D tuples. where: Position at which to split the curve. isHorizontal: Direction of the ray splitting the curve. If true, ``where`` is interpreted as a Y coordinate; if false, then ``where`` is interpreted as an X coordinate. Returns: A list of two curve segments (each curve segment being three 2D tuples) if the curve was successfully split, or a list containing the original curve. Example:: >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False)) ((0, 0), (50, 100), (100, 0)) >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False)) ((0, 0), (25, 50), (50, 50)) ((50, 50), (75, 50), (100, 0)) >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False)) ((0, 0), (12.5, 25), (25, 37.5)) ((25, 37.5), (62.5, 75), (100, 0)) >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True)) ((0, 0), (7.32233, 14.6447), (14.6447, 25)) ((14.6447, 25), (50, 75), (85.3553, 25)) ((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15)) >>> # XXX I'm not at all sure if the following behavior is desirable: >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True)) ((0, 0), (25, 50), (50, 50)) ((50, 50), (50, 50), (50, 50)) ((50, 50), (75, 50), (100, 0)) |
175,524 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
a=cython.double,
b=cython.double,
def _splitCubicAtT(a, b, c, d, *ts):
ts = list(ts)
ts.insert(0, 0.0)
ts.append(1.0)
segments = []
ax, ay = a
bx, by = b
cx, cy = c
dx, dy = d
for i in range(len(ts) - 1):
t1 = ts[i]
t2 = ts[i + 1]
delta = t2 - t1
delta_2 = delta * delta
delta_3 = delta * delta_2
t1_2 = t1 * t1
t1_3 = t1 * t1_2
# calc new a, b, c and d
a1x = ax * delta_3
a1y = ay * delta_3
b1x = (3 * ax * t1 + bx) * delta_2
b1y = (3 * ay * t1 + by) * delta_2
c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta
c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta
d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx
d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy
pt1, pt2, pt3, pt4 = calcCubicPoints(
(a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y)
)
segments.append((pt1, pt2, pt3, pt4))
return segments
a=cython.complex,
b=cython.complex,
c=cython.complex,
d=cython.complex,
t1=cython.double,
t2=cython.double,
delta=cython.double,
delta_2=cython.double,
delta_3=cython.double,
a1=cython.complex,
b1=cython.complex,
c1=cython.complex,
d1=cython.complex,
from math import sqrt, acos, cos, pi
def solveCubic(a, b, c, d):
"""Solve a cubic equation.
Solves *a*x*x*x + b*x*x + c*x + d = 0* where a, b, c and d are real.
Args:
a: coefficient of *x³*
b: coefficient of *x²*
c: coefficient of *x*
d: constant term
Returns:
A list of roots. Note that the returned list is neither guaranteed to
be sorted nor to contain unique values!
Examples::
>>> solveCubic(1, 1, -6, 0)
[-3.0, -0.0, 2.0]
>>> solveCubic(-10.0, -9.0, 48.0, -29.0)
[-2.9, 1.0, 1.0]
>>> solveCubic(-9.875, -9.0, 47.625, -28.75)
[-2.911392, 1.0, 1.0]
>>> solveCubic(1.0, -4.5, 6.75, -3.375)
[1.5, 1.5, 1.5]
>>> solveCubic(-12.0, 18.0, -9.0, 1.50023651123)
[0.5, 0.5, 0.5]
>>> solveCubic(
... 9.0, 0.0, 0.0, -7.62939453125e-05
... ) == [-0.0, -0.0, -0.0]
True
"""
#
# adapted from:
# CUBIC.C - Solve a cubic polynomial
# public domain by Ross Cottrell
# found at: http://www.strangecreations.com/library/snippets/Cubic.C
#
if abs(a) < epsilon:
# don't just test for zero; for very small values of 'a' solveCubic()
# returns unreliable results, so we fall back to quad.
return solveQuadratic(b, c, d)
a = float(a)
a1 = b / a
a2 = c / a
a3 = d / a
Q = (a1 * a1 - 3.0 * a2) / 9.0
R = (2.0 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0
R2 = R * R
Q3 = Q * Q * Q
R2 = 0 if R2 < epsilon else R2
Q3 = 0 if abs(Q3) < epsilon else Q3
R2_Q3 = R2 - Q3
if R2 == 0.0 and Q3 == 0.0:
x = round(-a1 / 3.0, epsilonDigits)
return [x, x, x]
elif R2_Q3 <= epsilon * 0.5:
# The epsilon * .5 above ensures that Q3 is not zero.
theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0))
rQ2 = -2.0 * sqrt(Q)
a1_3 = a1 / 3.0
x0 = rQ2 * cos(theta / 3.0) - a1_3
x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3
x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3
x0, x1, x2 = sorted([x0, x1, x2])
# Merge roots that are close-enough
if x1 - x0 < epsilon and x2 - x1 < epsilon:
x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits)
elif x1 - x0 < epsilon:
x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits)
x2 = round(x2, epsilonDigits)
elif x2 - x1 < epsilon:
x0 = round(x0, epsilonDigits)
x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits)
else:
x0 = round(x0, epsilonDigits)
x1 = round(x1, epsilonDigits)
x2 = round(x2, epsilonDigits)
return [x0, x1, x2]
else:
x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0)
x = x + Q / x
if R >= 0.0:
x = -x
x = round(x - a1 / 3.0, epsilonDigits)
return [x]
def calcCubicParameters(pt1, pt2, pt3, pt4):
x2, y2 = pt2
x3, y3 = pt3
x4, y4 = pt4
dx, dy = pt1
cx = (x2 - dx) * 3.0
cy = (y2 - dy) * 3.0
bx = (x3 - x2) * 3.0 - cx
by = (y3 - y2) * 3.0 - cy
ax = x4 - dx - cx - bx
ay = y4 - dy - cy - by
return (ax, ay), (bx, by), (cx, cy), (dx, dy)
pt1=cython.complex,
pt2=cython.complex,
pt3=cython.complex,
pt4=cython.complex,
a=cython.complex,
b=cython.complex,
c=cython.complex,
The provided code snippet includes necessary dependencies for implementing the `splitCubic` function. Write a Python function `def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal)` to solve the following problem:
Split a cubic Bezier curve at a given coordinate. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples. where: Position at which to split the curve. isHorizontal: Direction of the ray splitting the curve. If true, ``where`` is interpreted as a Y coordinate; if false, then ``where`` is interpreted as an X coordinate. Returns: A list of two curve segments (each curve segment being four 2D tuples) if the curve was successfully split, or a list containing the original curve. Example:: >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False)) ((0, 0), (25, 100), (75, 100), (100, 0)) >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False)) ((0, 0), (12.5, 50), (31.25, 75), (50, 75)) ((50, 75), (68.75, 75), (87.5, 50), (100, 0)) >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True)) ((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25)) ((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25)) ((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))
Here is the function:
def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal):
"""Split a cubic Bezier curve at a given coordinate.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
where: Position at which to split the curve.
isHorizontal: Direction of the ray splitting the curve. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two curve segments (each curve segment being four 2D tuples)
if the curve was successfully split, or a list containing the original
curve.
Example::
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False))
((0, 0), (25, 100), (75, 100), (100, 0))
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False))
((0, 0), (12.5, 50), (31.25, 75), (50, 75))
((50, 75), (68.75, 75), (87.5, 50), (100, 0))
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True))
((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25))
((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25))
((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))
"""
a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
solutions = solveCubic(
a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where
)
solutions = sorted(t for t in solutions if 0 <= t < 1)
if not solutions:
return [(pt1, pt2, pt3, pt4)]
return _splitCubicAtT(a, b, c, d, *solutions) | Split a cubic Bezier curve at a given coordinate. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples. where: Position at which to split the curve. isHorizontal: Direction of the ray splitting the curve. If true, ``where`` is interpreted as a Y coordinate; if false, then ``where`` is interpreted as an X coordinate. Returns: A list of two curve segments (each curve segment being four 2D tuples) if the curve was successfully split, or a list containing the original curve. Example:: >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False)) ((0, 0), (25, 100), (75, 100), (100, 0)) >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False)) ((0, 0), (12.5, 50), (31.25, 75), (50, 75)) ((50, 75), (68.75, 75), (87.5, 50), (100, 0)) >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True)) ((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25)) ((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25)) ((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15)) |
175,525 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.doubl
from math import sqrt, acos, cos, pi
The provided code snippet includes necessary dependencies for implementing the `splitCubicIntoTwoAtTC` function. Write a Python function `def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t)` to solve the following problem:
Split a cubic Bezier curve at t. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers. t: Position at which to split the curve. Returns: A tuple of two curve segments (each curve segment being four complex numbers).
Here is the function:
def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t):
"""Split a cubic Bezier curve at t.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
t: Position at which to split the curve.
Returns:
A tuple of two curve segments (each curve segment being four complex numbers).
"""
t2 = t * t
_1_t = 1 - t
_1_t_2 = _1_t * _1_t
_2_t_1_t = 2 * t * _1_t
pointAtT = (
_1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4
)
off1 = _1_t_2 * pt1 + _2_t_1_t * pt2 + t2 * pt3
off2 = _1_t_2 * pt2 + _2_t_1_t * pt3 + t2 * pt4
pt2 = pt1 + (pt2 - pt1) * t
pt3 = pt4 + (pt3 - pt4) * _1_t
return ((pt1, pt2, off1, pointAtT), (pointAtT, off2, pt3, pt4)) | Split a cubic Bezier curve at t. Args: pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers. t: Position at which to split the curve. Returns: A tuple of two curve segments (each curve segment being four complex numbers). |
175,526 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.doubl
from math import sqrt, acos, cos, pi
The provided code snippet includes necessary dependencies for implementing the `cubicPointAtTC` function. Write a Python function `def cubicPointAtTC(pt1, pt2, pt3, pt4, t)` to solve the following problem:
Finds the point at time `t` on a cubic curve. Args: pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers. t: The time along the curve. Returns: A complex number with the coordinates of the point.
Here is the function:
def cubicPointAtTC(pt1, pt2, pt3, pt4, t):
"""Finds the point at time `t` on a cubic curve.
Args:
pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers.
t: The time along the curve.
Returns:
A complex number with the coordinates of the point.
"""
t2 = t * t
_1_t = 1 - t
_1_t_2 = _1_t * _1_t
return _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4 | Finds the point at time `t` on a cubic curve. Args: pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers. t: The time along the curve. Returns: A complex number with the coordinates of the point. |
175,527 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
Intersection = namedtuple("Intersection", ["pt", "t1", "t2"])
t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.doubl
from math import sqrt, acos, cos, pi
def lineLineIntersections(s1, e1, s2, e2):
"""Finds intersections between two line segments.
Args:
s1, e1: Coordinates of the first line as 2D tuples.
s2, e2: Coordinates of the second line as 2D tuples.
Returns:
A list of ``Intersection`` objects, each object having ``pt``, ``t1``
and ``t2`` attributes containing the intersection point, time on first
segment and time on second segment respectively.
Examples::
>>> a = lineLineIntersections( (310,389), (453, 222), (289, 251), (447, 367))
>>> len(a)
1
>>> intersection = a[0]
>>> intersection.pt
(374.44882952482897, 313.73458370177315)
>>> (intersection.t1, intersection.t2)
(0.45069111555824465, 0.5408153767394238)
"""
s1x, s1y = s1
e1x, e1y = e1
s2x, s2y = s2
e2x, e2y = e2
if (
math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x)
): # Parallel vertical
return []
if (
math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y)
): # Parallel horizontal
return []
if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny
return []
if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny
return []
if math.isclose(e1x, s1x):
x = s1x
slope34 = (e2y - s2y) / (e2x - s2x)
y = slope34 * (x - s2x) + s2y
pt = (x, y)
return [
Intersection(
pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
)
]
if math.isclose(s2x, e2x):
x = s2x
slope12 = (e1y - s1y) / (e1x - s1x)
y = slope12 * (x - s1x) + s1y
pt = (x, y)
return [
Intersection(
pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
)
]
slope12 = (e1y - s1y) / (e1x - s1x)
slope34 = (e2y - s2y) / (e2x - s2x)
if math.isclose(slope12, slope34):
return []
x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34)
y = slope12 * (x - s1x) + s1y
pt = (x, y)
if _both_points_are_on_same_side_of_origin(
pt, e1, s1
) and _both_points_are_on_same_side_of_origin(pt, s2, e2):
return [
Intersection(
pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
)
]
return []
def curveLineIntersections(curve, line):
"""Finds intersections between a curve and a line.
Args:
curve: List of coordinates of the curve segment as 2D tuples.
line: List of coordinates of the line segment as 2D tuples.
Returns:
A list of ``Intersection`` objects, each object having ``pt``, ``t1``
and ``t2`` attributes containing the intersection point, time on first
segment and time on second segment respectively.
Examples::
>>> curve = [ (100, 240), (30, 60), (210, 230), (160, 30) ]
>>> line = [ (25, 260), (230, 20) ]
>>> intersections = curveLineIntersections(curve, line)
>>> len(intersections)
3
>>> intersections[0].pt
(84.9000930760723, 189.87306176459828)
"""
if len(curve) == 3:
pointFinder = quadraticPointAtT
elif len(curve) == 4:
pointFinder = cubicPointAtT
else:
raise ValueError("Unknown curve degree")
intersections = []
for t in _curve_line_intersections_t(curve, line):
pt = pointFinder(*curve, t)
# Back-project the point onto the line, to avoid problems with
# numerical accuracy in the case of vertical and horizontal lines
line_t = _line_t_of_pt(*line, pt)
pt = linePointAtT(*line, line_t)
intersections.append(Intersection(pt=pt, t1=t, t2=line_t))
return intersections
def curveCurveIntersections(curve1, curve2):
"""Finds intersections between a curve and a curve.
Args:
curve1: List of coordinates of the first curve segment as 2D tuples.
curve2: List of coordinates of the second curve segment as 2D tuples.
Returns:
A list of ``Intersection`` objects, each object having ``pt``, ``t1``
and ``t2`` attributes containing the intersection point, time on first
segment and time on second segment respectively.
Examples::
>>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]
>>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]
>>> intersections = curveCurveIntersections(curve1, curve2)
>>> len(intersections)
3
>>> intersections[0].pt
(81.7831487395506, 109.88904552375288)
"""
intersection_ts = _curve_curve_intersections_t(curve1, curve2)
return [
Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1])
for ts in intersection_ts
]
The provided code snippet includes necessary dependencies for implementing the `segmentSegmentIntersections` function. Write a Python function `def segmentSegmentIntersections(seg1, seg2)` to solve the following problem:
Finds intersections between two segments. Args: seg1: List of coordinates of the first segment as 2D tuples. seg2: List of coordinates of the second segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ] >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ] >>> intersections = segmentSegmentIntersections(curve1, curve2) >>> len(intersections) 3 >>> intersections[0].pt (81.7831487395506, 109.88904552375288) >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ] >>> line = [ (25, 260), (230, 20) ] >>> intersections = segmentSegmentIntersections(curve3, line) >>> len(intersections) 3 >>> intersections[0].pt (84.9000930760723, 189.87306176459828)
Here is the function:
def segmentSegmentIntersections(seg1, seg2):
"""Finds intersections between two segments.
Args:
seg1: List of coordinates of the first segment as 2D tuples.
seg2: List of coordinates of the second segment as 2D tuples.
Returns:
A list of ``Intersection`` objects, each object having ``pt``, ``t1``
and ``t2`` attributes containing the intersection point, time on first
segment and time on second segment respectively.
Examples::
>>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]
>>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]
>>> intersections = segmentSegmentIntersections(curve1, curve2)
>>> len(intersections)
3
>>> intersections[0].pt
(81.7831487395506, 109.88904552375288)
>>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ]
>>> line = [ (25, 260), (230, 20) ]
>>> intersections = segmentSegmentIntersections(curve3, line)
>>> len(intersections)
3
>>> intersections[0].pt
(84.9000930760723, 189.87306176459828)
"""
# Arrange by degree
swapped = False
if len(seg2) > len(seg1):
seg2, seg1 = seg1, seg2
swapped = True
if len(seg1) > 2:
if len(seg2) > 2:
intersections = curveCurveIntersections(seg1, seg2)
else:
intersections = curveLineIntersections(seg1, seg2)
elif len(seg1) == 2 and len(seg2) == 2:
intersections = lineLineIntersections(*seg1, *seg2)
else:
raise ValueError("Couldn't work out which intersection function to use")
if not swapped:
return intersections
return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections] | Finds intersections between two segments. Args: seg1: List of coordinates of the first segment as 2D tuples. seg2: List of coordinates of the second segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ] >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ] >>> intersections = segmentSegmentIntersections(curve1, curve2) >>> len(intersections) 3 >>> intersections[0].pt (81.7831487395506, 109.88904552375288) >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ] >>> line = [ (25, 260), (230, 20) ] >>> intersections = segmentSegmentIntersections(curve3, line) >>> len(intersections) 3 >>> intersections[0].pt (84.9000930760723, 189.87306176459828) |
175,528 | from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
from fontTools.misc.transform import Identity
import math
from collections import namedtuple
from math import sqrt, acos, cos, pi
def _segmentrepr(obj):
"""
>>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]])
'(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))'
"""
try:
it = iter(obj)
except TypeError:
return "%g" % obj
else:
return "(%s)" % ", ".join(_segmentrepr(x) for x in it)
The provided code snippet includes necessary dependencies for implementing the `printSegments` function. Write a Python function `def printSegments(segments)` to solve the following problem:
Helper for the doctests, displaying each segment in a list of segments on a single line as a tuple.
Here is the function:
def printSegments(segments):
"""Helper for the doctests, displaying each segment in a list of
segments on a single line as a tuple.
"""
for segment in segments:
print(_segmentrepr(segment)) | Helper for the doctests, displaying each segment in a list of segments on a single line as a tuple. |
175,529 | import os
import time
from datetime import datetime, timezone
import calendar
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
def asctime(t=None):
def timestampToString(value):
return asctime(time.gmtime(max(0, value + epoch_diff))) | null |
175,530 | import os
import time
from datetime import datetime, timezone
import calendar
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
DAYNAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
MONTHNAMES = [
None,
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
class datetime(date):
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> _S:
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> _S:
def year(self) -> int:
def month(self) -> int:
def day(self) -> int:
def hour(self) -> int:
def minute(self) -> int:
def second(self) -> int:
def microsecond(self) -> int:
def tzinfo(self) -> Optional[_tzinfo]:
def fold(self) -> int:
def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S:
def utcfromtimestamp(cls: Type[_S], t: float) -> _S:
def today(cls: Type[_S]) -> _S:
def fromordinal(cls: Type[_S], n: int) -> _S:
def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S:
def now(cls: Type[_S], tz: None = ...) -> _S:
def now(cls, tz: _tzinfo) -> datetime:
def utcnow(cls: Type[_S]) -> _S:
def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime:
def combine(cls, date: _date, time: _time) -> datetime:
def fromisoformat(cls: Type[_S], date_string: str) -> _S:
def strftime(self, fmt: _Text) -> str:
def __format__(self, fmt: str) -> str:
def __format__(self, fmt: AnyStr) -> AnyStr:
def toordinal(self) -> int:
def timetuple(self) -> struct_time:
def timestamp(self) -> float:
def utctimetuple(self) -> struct_time:
def date(self) -> _date:
def time(self) -> _time:
def timetz(self) -> _time:
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> datetime:
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> datetime:
def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S:
def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime:
def astimezone(self, tz: _tzinfo) -> datetime:
def ctime(self) -> str:
def isoformat(self, sep: str = ..., timespec: str = ...) -> str:
def isoformat(self, sep: str = ...) -> str:
def strptime(cls, date_string: _Text, format: _Text) -> datetime:
def utcoffset(self) -> Optional[timedelta]:
def tzname(self) -> Optional[str]:
def dst(self) -> Optional[timedelta]:
def __le__(self, other: datetime) -> bool:
def __lt__(self, other: datetime) -> bool:
def __ge__(self, other: datetime) -> bool:
def __gt__(self, other: datetime) -> bool:
def __add__(self: _S, other: timedelta) -> _S:
def __radd__(self: _S, other: timedelta) -> _S:
def __add__(self, other: timedelta) -> datetime:
def __radd__(self, other: timedelta) -> datetime:
def __sub__(self, other: datetime) -> timedelta:
def __sub__(self, other: timedelta) -> datetime:
def __hash__(self) -> int:
def weekday(self) -> int:
def isoweekday(self) -> int:
def isocalendar(self) -> Tuple[int, int, int]:
def timestampFromString(value):
wkday, mnth = value[:7].split()
t = datetime.strptime(value[7:], " %d %H:%M:%S %Y")
t = t.replace(month=MONTHNAMES.index(mnth), tzinfo=timezone.utc)
wkday_idx = DAYNAMES.index(wkday)
assert t.weekday() == wkday_idx, '"' + value + '" has inconsistent weekday'
return int(t.timestamp()) - epoch_diff | null |
175,531 | import sys
import logging
import timeit
from functools import wraps
from collections.abc import Mapping, Callable
import warnings
from logging import PercentStyle
class LevelFormatter(logging.Formatter):
"""Log formatter with level-specific formatting.
Formatter class which optionally takes a dict of logging levels to
format strings, allowing to customise the log records appearance for
specific levels.
Attributes:
fmt: A dictionary mapping logging levels to format strings.
The ``*`` key identifies the default format string.
datefmt: As per py:class:`logging.Formatter`
style: As per py:class:`logging.Formatter`
>>> import sys
>>> handler = logging.StreamHandler(sys.stdout)
>>> formatter = LevelFormatter(
... fmt={
... '*': '[%(levelname)s] %(message)s',
... 'DEBUG': '%(name)s [%(levelname)s] %(message)s',
... 'INFO': '%(message)s',
... })
>>> handler.setFormatter(formatter)
>>> log = logging.getLogger('test')
>>> log.setLevel(logging.DEBUG)
>>> log.addHandler(handler)
>>> log.debug('this uses a custom format string')
test [DEBUG] this uses a custom format string
>>> log.info('this also uses a custom format string')
this also uses a custom format string
>>> log.warning("this one uses the default format string")
[WARNING] this one uses the default format string
"""
def __init__(self, fmt=None, datefmt=None, style="%"):
if style != "%":
raise ValueError(
"only '%' percent style is supported in both python 2 and 3"
)
if fmt is None:
fmt = DEFAULT_FORMATS
if isinstance(fmt, str):
default_format = fmt
custom_formats = {}
elif isinstance(fmt, Mapping):
custom_formats = dict(fmt)
default_format = custom_formats.pop("*", None)
else:
raise TypeError("fmt must be a str or a dict of str: %r" % fmt)
super(LevelFormatter, self).__init__(default_format, datefmt)
self.default_format = self._fmt
self.custom_formats = {}
for level, fmt in custom_formats.items():
level = logging._checkLevel(level)
self.custom_formats[level] = fmt
def format(self, record):
if self.custom_formats:
fmt = self.custom_formats.get(record.levelno, self.default_format)
if self._fmt != fmt:
self._fmt = fmt
# for python >= 3.2, _style needs to be set if _fmt changes
if PercentStyle:
self._style = PercentStyle(fmt)
return super(LevelFormatter, self).format(record)
def _resetExistingLoggers(parent="root"):
"""Reset the logger named 'parent' and all its children to their initial
state, if they already exist in the current configuration.
"""
root = logging.root
# get sorted list of all existing loggers
existing = sorted(root.manager.loggerDict.keys())
if parent == "root":
# all the existing loggers are children of 'root'
loggers_to_reset = [parent] + existing
elif parent not in existing:
# nothing to do
return
elif parent in existing:
loggers_to_reset = [parent]
# collect children, starting with the entry after parent name
i = existing.index(parent) + 1
prefixed = parent + "."
pflen = len(prefixed)
num_existing = len(existing)
while i < num_existing:
if existing[i][:pflen] == prefixed:
loggers_to_reset.append(existing[i])
i += 1
for name in loggers_to_reset:
if name == "root":
root.setLevel(logging.WARNING)
for h in root.handlers[:]:
root.removeHandler(h)
for f in root.filters[:]:
root.removeFilters(f)
root.disabled = False
else:
logger = root.manager.loggerDict[name]
logger.level = logging.NOTSET
logger.handlers = []
logger.filters = []
logger.propagate = True
logger.disabled = False
The provided code snippet includes necessary dependencies for implementing the `configLogger` function. Write a Python function `def configLogger(**kwargs)` to solve the following problem:
A more sophisticated logging system configuation manager. This is more or less the same as :py:func:`logging.basicConfig`, with some additional options and defaults. The default behaviour is to create a ``StreamHandler`` which writes to sys.stderr, set a formatter using the ``DEFAULT_FORMATS`` strings, and add the handler to the top-level library logger ("fontTools"). A number of optional keyword arguments may be specified, which can alter the default behaviour. Args: logger: Specifies the logger name or a Logger instance to be configured. (Defaults to "fontTools" logger). Unlike ``basicConfig``, this function can be called multiple times to reconfigure a logger. If the logger or any of its children already exists before the call is made, they will be reset before the new configuration is applied. filename: Specifies that a ``FileHandler`` be created, using the specified filename, rather than a ``StreamHandler``. filemode: Specifies the mode to open the file, if filename is specified. (If filemode is unspecified, it defaults to ``a``). format: Use the specified format string for the handler. This argument also accepts a dictionary of format strings keyed by level name, to allow customising the records appearance for specific levels. The special ``'*'`` key is for 'any other' level. datefmt: Use the specified date/time format. level: Set the logger level to the specified level. stream: Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with ``filename`` - if both are present, ``stream`` is ignored. handlers: If specified, this should be an iterable of already created handlers, which will be added to the logger. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. filters: If specified, this should be an iterable of already created filters. If the ``handlers`` do not already have filters assigned, these filters will be added to them. propagate: All loggers have a ``propagate`` attribute which determines whether to continue searching for handlers up the logging hierarchy. If not provided, the "propagate" attribute will be set to ``False``.
Here is the function:
def configLogger(**kwargs):
"""A more sophisticated logging system configuation manager.
This is more or less the same as :py:func:`logging.basicConfig`,
with some additional options and defaults.
The default behaviour is to create a ``StreamHandler`` which writes to
sys.stderr, set a formatter using the ``DEFAULT_FORMATS`` strings, and add
the handler to the top-level library logger ("fontTools").
A number of optional keyword arguments may be specified, which can alter
the default behaviour.
Args:
logger: Specifies the logger name or a Logger instance to be
configured. (Defaults to "fontTools" logger). Unlike ``basicConfig``,
this function can be called multiple times to reconfigure a logger.
If the logger or any of its children already exists before the call is
made, they will be reset before the new configuration is applied.
filename: Specifies that a ``FileHandler`` be created, using the
specified filename, rather than a ``StreamHandler``.
filemode: Specifies the mode to open the file, if filename is
specified. (If filemode is unspecified, it defaults to ``a``).
format: Use the specified format string for the handler. This
argument also accepts a dictionary of format strings keyed by
level name, to allow customising the records appearance for
specific levels. The special ``'*'`` key is for 'any other' level.
datefmt: Use the specified date/time format.
level: Set the logger level to the specified level.
stream: Use the specified stream to initialize the StreamHandler. Note
that this argument is incompatible with ``filename`` - if both
are present, ``stream`` is ignored.
handlers: If specified, this should be an iterable of already created
handlers, which will be added to the logger. Any handler in the
list which does not have a formatter assigned will be assigned the
formatter created in this function.
filters: If specified, this should be an iterable of already created
filters. If the ``handlers`` do not already have filters assigned,
these filters will be added to them.
propagate: All loggers have a ``propagate`` attribute which determines
whether to continue searching for handlers up the logging hierarchy.
If not provided, the "propagate" attribute will be set to ``False``.
"""
# using kwargs to enforce keyword-only arguments in py2.
handlers = kwargs.pop("handlers", None)
if handlers is None:
if "stream" in kwargs and "filename" in kwargs:
raise ValueError(
"'stream' and 'filename' should not be " "specified together"
)
else:
if "stream" in kwargs or "filename" in kwargs:
raise ValueError(
"'stream' or 'filename' should not be "
"specified together with 'handlers'"
)
if handlers is None:
filename = kwargs.pop("filename", None)
mode = kwargs.pop("filemode", "a")
if filename:
h = logging.FileHandler(filename, mode)
else:
stream = kwargs.pop("stream", None)
h = logging.StreamHandler(stream)
handlers = [h]
# By default, the top-level library logger is configured.
logger = kwargs.pop("logger", "fontTools")
if not logger or isinstance(logger, str):
# empty "" or None means the 'root' logger
logger = logging.getLogger(logger)
# before (re)configuring, reset named logger and its children (if exist)
_resetExistingLoggers(parent=logger.name)
# use DEFAULT_FORMATS if 'format' is None
fs = kwargs.pop("format", None)
dfs = kwargs.pop("datefmt", None)
# XXX: '%' is the only format style supported on both py2 and 3
style = kwargs.pop("style", "%")
fmt = LevelFormatter(fs, dfs, style)
filters = kwargs.pop("filters", [])
for h in handlers:
if h.formatter is None:
h.setFormatter(fmt)
if not h.filters:
for f in filters:
h.addFilter(f)
logger.addHandler(h)
if logger.name != "root":
# stop searching up the hierarchy for handlers
logger.propagate = kwargs.pop("propagate", False)
# set a custom severity level
level = kwargs.pop("level", None)
if level is not None:
logger.setLevel(level)
if kwargs:
keys = ", ".join(kwargs.keys())
raise ValueError("Unrecognised argument(s): %s" % keys) | A more sophisticated logging system configuation manager. This is more or less the same as :py:func:`logging.basicConfig`, with some additional options and defaults. The default behaviour is to create a ``StreamHandler`` which writes to sys.stderr, set a formatter using the ``DEFAULT_FORMATS`` strings, and add the handler to the top-level library logger ("fontTools"). A number of optional keyword arguments may be specified, which can alter the default behaviour. Args: logger: Specifies the logger name or a Logger instance to be configured. (Defaults to "fontTools" logger). Unlike ``basicConfig``, this function can be called multiple times to reconfigure a logger. If the logger or any of its children already exists before the call is made, they will be reset before the new configuration is applied. filename: Specifies that a ``FileHandler`` be created, using the specified filename, rather than a ``StreamHandler``. filemode: Specifies the mode to open the file, if filename is specified. (If filemode is unspecified, it defaults to ``a``). format: Use the specified format string for the handler. This argument also accepts a dictionary of format strings keyed by level name, to allow customising the records appearance for specific levels. The special ``'*'`` key is for 'any other' level. datefmt: Use the specified date/time format. level: Set the logger level to the specified level. stream: Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with ``filename`` - if both are present, ``stream`` is ignored. handlers: If specified, this should be an iterable of already created handlers, which will be added to the logger. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. filters: If specified, this should be an iterable of already created filters. If the ``handlers`` do not already have filters assigned, these filters will be added to them. propagate: All loggers have a ``propagate`` attribute which determines whether to continue searching for handlers up the logging hierarchy. If not provided, the "propagate" attribute will be set to ``False``. |
175,532 | import sys
import logging
import timeit
from functools import wraps
from collections.abc import Mapping, Callable
import warnings
from logging import PercentStyle
The provided code snippet includes necessary dependencies for implementing the `deprecateArgument` function. Write a Python function `def deprecateArgument(name, msg, category=UserWarning)` to solve the following problem:
Raise a warning about deprecated function argument 'name'.
Here is the function:
def deprecateArgument(name, msg, category=UserWarning):
"""Raise a warning about deprecated function argument 'name'."""
warnings.warn("%r is deprecated; %s" % (name, msg), category=category, stacklevel=3) | Raise a warning about deprecated function argument 'name'. |
175,533 | import sys
import logging
import timeit
from functools import wraps
from collections.abc import Mapping, Callable
import warnings
from logging import PercentStyle
def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ...
The provided code snippet includes necessary dependencies for implementing the `deprecateFunction` function. Write a Python function `def deprecateFunction(msg, category=UserWarning)` to solve the following problem:
Decorator to raise a warning when a deprecated function is called.
Here is the function:
def deprecateFunction(msg, category=UserWarning):
"""Decorator to raise a warning when a deprecated function is called."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
warnings.warn(
"%r is deprecated; %s" % (func.__name__, msg),
category=category,
stacklevel=2,
)
return func(*args, **kwargs)
return wrapper
return decorator | Decorator to raise a warning when a deprecated function is called. |
175,534 | from fontTools.misc.textTools import bytechr, byteord, bytesjoin, tobytes, tostr
from fontTools.misc import eexec
from .psOperators import (
PSOperators,
ps_StandardEncoding,
ps_array,
ps_boolean,
ps_dict,
ps_integer,
ps_literal,
ps_mark,
ps_name,
ps_operator,
ps_procedure,
ps_procmark,
ps_real,
ps_string,
)
import re
from collections.abc import Callable
from string import whitespace
import logging
class PSInterpreter(PSOperators):
def __init__(self, encoding="ascii"):
systemdict = {}
userdict = {}
self.encoding = encoding
self.dictstack = [systemdict, userdict]
self.stack = []
self.proclevel = 0
self.procmark = ps_procmark()
self.fillsystemdict()
def fillsystemdict(self):
systemdict = self.dictstack[0]
systemdict["["] = systemdict["mark"] = self.mark = ps_mark()
systemdict["]"] = ps_operator("]", self.do_makearray)
systemdict["true"] = ps_boolean(1)
systemdict["false"] = ps_boolean(0)
systemdict["StandardEncoding"] = ps_array(ps_StandardEncoding)
systemdict["FontDirectory"] = ps_dict({})
self.suckoperators(systemdict, self.__class__)
def suckoperators(self, systemdict, klass):
for name in dir(klass):
attr = getattr(self, name)
if isinstance(attr, Callable) and name[:3] == "ps_":
name = name[3:]
systemdict[name] = ps_operator(name, attr)
for baseclass in klass.__bases__:
self.suckoperators(systemdict, baseclass)
def interpret(self, data, getattr=getattr):
tokenizer = self.tokenizer = PSTokenizer(data, self.encoding)
getnexttoken = tokenizer.getnexttoken
do_token = self.do_token
handle_object = self.handle_object
try:
while 1:
tokentype, token = getnexttoken()
if not token:
break
if tokentype:
handler = getattr(self, tokentype)
object = handler(token)
else:
object = do_token(token)
if object is not None:
handle_object(object)
tokenizer.close()
self.tokenizer = None
except:
if self.tokenizer is not None:
log.debug(
"ps error:\n"
"- - - - - - -\n"
"%s\n"
">>>\n"
"%s\n"
"- - - - - - -",
self.tokenizer.buf[self.tokenizer.pos - 50 : self.tokenizer.pos],
self.tokenizer.buf[self.tokenizer.pos : self.tokenizer.pos + 50],
)
raise
def handle_object(self, object):
if not (self.proclevel or object.literal or object.type == "proceduretype"):
if object.type != "operatortype":
object = self.resolve_name(object.value)
if object.literal:
self.push(object)
else:
if object.type == "proceduretype":
self.call_procedure(object)
else:
object.function()
else:
self.push(object)
def call_procedure(self, proc):
handle_object = self.handle_object
for item in proc.value:
handle_object(item)
def resolve_name(self, name):
dictstack = self.dictstack
for i in range(len(dictstack) - 1, -1, -1):
if name in dictstack[i]:
return dictstack[i][name]
raise PSError("name error: " + str(name))
def do_token(
self,
token,
int=int,
float=float,
ps_name=ps_name,
ps_integer=ps_integer,
ps_real=ps_real,
):
try:
num = int(token)
except (ValueError, OverflowError):
try:
num = float(token)
except (ValueError, OverflowError):
if "#" in token:
hashpos = token.find("#")
try:
base = int(token[:hashpos])
num = int(token[hashpos + 1 :], base)
except (ValueError, OverflowError):
return ps_name(token)
else:
return ps_integer(num)
else:
return ps_name(token)
else:
return ps_real(num)
else:
return ps_integer(num)
def do_comment(self, token):
pass
def do_literal(self, token):
return ps_literal(token[1:])
def do_string(self, token):
return ps_string(token[1:-1])
def do_hexstring(self, token):
hexStr = "".join(token[1:-1].split())
if len(hexStr) % 2:
hexStr = hexStr + "0"
cleanstr = []
for i in range(0, len(hexStr), 2):
cleanstr.append(chr(int(hexStr[i : i + 2], 16)))
cleanstr = "".join(cleanstr)
return ps_string(cleanstr)
def do_special(self, token):
if token == "{":
self.proclevel = self.proclevel + 1
return self.procmark
elif token == "}":
proc = []
while 1:
topobject = self.pop()
if topobject == self.procmark:
break
proc.append(topobject)
self.proclevel = self.proclevel - 1
proc.reverse()
return ps_procedure(proc)
elif token == "[":
return self.mark
elif token == "]":
return ps_name("]")
else:
raise PSTokenError("huh?")
def push(self, object):
self.stack.append(object)
def pop(self, *types):
stack = self.stack
if not stack:
raise PSError("stack underflow")
object = stack[-1]
if types:
if object.type not in types:
raise PSError(
"typecheck, expected %s, found %s" % (repr(types), object.type)
)
del stack[-1]
return object
def do_makearray(self):
array = []
while 1:
topobject = self.pop()
if topobject == self.mark:
break
array.append(topobject)
array.reverse()
self.push(ps_array(array))
def close(self):
"""Remove circular references."""
del self.stack
del self.dictstack
def unpack_item(item):
tp = type(item.value)
if tp == dict:
newitem = {}
for key, value in item.value.items():
newitem[key] = unpack_item(value)
elif tp == list:
newitem = [None] * len(item.value)
for i in range(len(item.value)):
newitem[i] = unpack_item(item.value[i])
if item.type == "proceduretype":
newitem = tuple(newitem)
else:
newitem = item.value
return newitem
def suckfont(data, encoding="ascii"):
m = re.search(rb"/FontName\s+/([^ \t\n\r]+)\s+def", data)
if m:
fontName = m.group(1)
fontName = fontName.decode()
else:
fontName = None
interpreter = PSInterpreter(encoding=encoding)
interpreter.interpret(
b"/Helvetica 4 dict dup /Encoding StandardEncoding put definefont pop"
)
interpreter.interpret(data)
fontdir = interpreter.dictstack[0]["FontDirectory"].value
if fontName in fontdir:
rawfont = fontdir[fontName]
else:
# fall back, in case fontName wasn't found
fontNames = list(fontdir.keys())
if len(fontNames) > 1:
fontNames.remove("Helvetica")
fontNames.sort()
rawfont = fontdir[fontNames[0]]
interpreter.close()
return unpack_item(rawfont) | null |
175,535 | import math
import functools
import logging
def noRound(value):
return value
def otRound(value):
"""Round float value to nearest integer towards ``+Infinity``.
The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_)
defines the required method for converting floating point values to
fixed-point. In particular it specifies the following rounding strategy:
for fractional values of 0.5 and higher, take the next higher integer;
for other fractional values, truncate.
This function rounds the floating-point value according to this strategy
in preparation for conversion to fixed-point.
Args:
value (float): The input floating-point value.
Returns
float: The rounded value.
"""
# See this thread for how we ended up with this implementation:
# https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166
return int(math.floor(value + 0.5))
def maybeRound(v, tolerance, round=otRound):
rounded = round(v)
return rounded if abs(rounded - v) <= tolerance else v
def roundFunc(tolerance, round=otRound):
if tolerance < 0:
raise ValueError("Rounding tolerance must be positive")
if tolerance == 0:
return noRound
if tolerance >= 0.5:
return round
return functools.partial(maybeRound, tolerance=tolerance, round=round) | null |
175,536 | from fontTools.misc.textTools import tostr
try:
from lxml.etree import *
_have_lxml = True
except ImportError:
try:
from xml.etree.cElementTree import *
# the cElementTree version of XML function doesn't support
# the optional 'parser' keyword argument
from xml.etree.ElementTree import XML
except ImportError: # pragma: no cover
from xml.etree.ElementTree import *
_have_lxml = False
import sys
# dict is always ordered in python >= 3.6 and on pypy
PY36 = sys.version_info >= (3, 6)
try:
import __pypy__
except ImportError:
__pypy__ = None
_dict_is_ordered = bool(PY36 or __pypy__)
del PY36, __pypy__
if _dict_is_ordered:
_Attrib = dict
else:
from collections import OrderedDict as _Attrib
if isinstance(Element, type):
_Element = Element
else:
# in py27, cElementTree.Element cannot be subclassed, so
# we need to import the pure-python class
from xml.etree.ElementTree import Element as _Element
def _iterwalk(element, events, tag):
include = tag is None or element.tag == tag
if include and "start" in events:
yield ("start", element)
for e in element:
for item in _iterwalk(e, events, tag):
yield item
if include:
yield ("end", element)
_ElementTree = ElementTree
import io
# serialization support
import re
# Valid XML strings can include any Unicode character, excluding control
# characters, the surrogate blocks, FFFE, and FFFF:
# Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
# Here we reversed the pattern to match only the invalid characters.
# For the 'narrow' python builds supporting only UCS-2, which represent
# characters beyond BMP as UTF-16 surrogate pairs, we need to pass through
# the surrogate block. I haven't found a more elegant solution...
UCS2 = sys.maxunicode < 0x10FFFF
if UCS2:
_invalid_xml_string = re.compile(
"[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]"
)
else:
_invalid_xml_string = re.compile(
"[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"
)
import contextlib
from xml.etree.ElementTree import _namespace_map
The provided code snippet includes necessary dependencies for implementing the `iterwalk` function. Write a Python function `def iterwalk(element_or_tree, events=("end",), tag=None)` to solve the following problem:
A tree walker that generates events from an existing tree as if it was parsing XML data with iterparse(). Drop-in replacement for lxml.etree.iterwalk.
Here is the function:
def iterwalk(element_or_tree, events=("end",), tag=None):
"""A tree walker that generates events from an existing tree as
if it was parsing XML data with iterparse().
Drop-in replacement for lxml.etree.iterwalk.
"""
if iselement(element_or_tree):
element = element_or_tree
else:
element = element_or_tree.getroot()
if tag == "*":
tag = None
for item in _iterwalk(element, events, tag):
yield item | A tree walker that generates events from an existing tree as if it was parsing XML data with iterparse(). Drop-in replacement for lxml.etree.iterwalk. |
175,537 | from fontTools.misc.textTools import tostr
def _get_writer(file_or_filename, encoding):
# returns text write method and release all resources after using
try:
write = file_or_filename.write
except AttributeError:
# file_or_filename is a file name
f = open(
file_or_filename,
"w",
encoding="utf-8" if encoding == "unicode" else encoding,
errors="xmlcharrefreplace",
)
with f:
yield f.write
else:
# file_or_filename is a file-like object
# encoding determines if it is a text or binary writer
if encoding == "unicode":
# use a text writer as is
yield write
else:
# wrap a binary writer with TextIOWrapper
detach_buffer = False
if isinstance(file_or_filename, io.BufferedIOBase):
buf = file_or_filename
elif isinstance(file_or_filename, io.RawIOBase):
buf = io.BufferedWriter(file_or_filename)
detach_buffer = True
else:
# This is to handle passed objects that aren't in the
# IOBase hierarchy, but just have a write method
buf = io.BufferedIOBase()
buf.writable = lambda: True
buf.write = write
try:
# TextIOWrapper uses this methods to determine
# if BOM (for UTF-16, etc) should be added
buf.seekable = file_or_filename.seekable
buf.tell = file_or_filename.tell
except AttributeError:
pass
wrapper = io.TextIOWrapper(
buf,
encoding=encoding,
errors="xmlcharrefreplace",
newline="\n",
)
try:
yield wrapper.write
finally:
# Keep the original file open when the TextIOWrapper and
# the BufferedWriter are destroyed
wrapper.detach()
if detach_buffer:
buf.detach() | null |
175,538 | from fontTools.misc.textTools import tostr
try:
from lxml.etree import *
_have_lxml = True
except ImportError:
try:
from xml.etree.cElementTree import *
# the cElementTree version of XML function doesn't support
# the optional 'parser' keyword argument
from xml.etree.ElementTree import XML
except ImportError: # pragma: no cover
from xml.etree.ElementTree import *
_have_lxml = False
import sys
# dict is always ordered in python >= 3.6 and on pypy
PY36 = sys.version_info >= (3, 6)
try:
import __pypy__
except ImportError:
__pypy__ = None
_dict_is_ordered = bool(PY36 or __pypy__)
del PY36, __pypy__
if _dict_is_ordered:
_Attrib = dict
else:
from collections import OrderedDict as _Attrib
if isinstance(Element, type):
_Element = Element
else:
# in py27, cElementTree.Element cannot be subclassed, so
# we need to import the pure-python class
from xml.etree.ElementTree import Element as _Element
_ElementTree = ElementTree
import io
# serialization support
import re
# Valid XML strings can include any Unicode character, excluding control
# characters, the surrogate blocks, FFFE, and FFFF:
# Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
# Here we reversed the pattern to match only the invalid characters.
# For the 'narrow' python builds supporting only UCS-2, which represent
# characters beyond BMP as UTF-16 surrogate pairs, we need to pass through
# the surrogate block. I haven't found a more elegant solution...
UCS2 = sys.maxunicode < 0x10FFFF
if UCS2:
_invalid_xml_string = re.compile(
"[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]"
)
else:
_invalid_xml_string = re.compile(
"[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"
)
def _tounicode(s):
"""Test if a string is valid user input and decode it to unicode string
using ASCII encoding if it's a bytes string.
Reject all bytes/unicode input that contains non-XML characters.
Reject all bytes input that contains non-ASCII characters.
"""
try:
s = tostr(s, encoding="ascii", errors="strict")
except UnicodeDecodeError:
raise ValueError(
"Bytes strings can only contain ASCII characters. "
"Use unicode strings for non-ASCII characters."
)
except AttributeError:
_raise_serialization_error(s)
if s and _invalid_xml_string.search(s):
raise ValueError(
"All strings must be XML compatible: Unicode or ASCII, "
"no NULL bytes or control characters"
)
return s
import contextlib
from xml.etree.ElementTree import _namespace_map
def _raise_serialization_error(text):
raise TypeError("cannot serialize %r (type %s)" % (text, type(text).__name__))
def _namespaces(elem):
# identify namespaces used in this tree
# maps qnames to *encoded* prefix:local names
qnames = {None: None}
# maps uri:s to prefixes
namespaces = {}
def add_qname(qname):
# calculate serialized qname representation
try:
qname = _tounicode(qname)
if qname[:1] == "{":
uri, tag = qname[1:].rsplit("}", 1)
prefix = namespaces.get(uri)
if prefix is None:
prefix = _namespace_map.get(uri)
if prefix is None:
prefix = "ns%d" % len(namespaces)
else:
prefix = _tounicode(prefix)
if prefix != "xml":
namespaces[uri] = prefix
if prefix:
qnames[qname] = "%s:%s" % (prefix, tag)
else:
qnames[qname] = tag # default element
else:
qnames[qname] = qname
except TypeError:
_raise_serialization_error(qname)
# populate qname and namespaces table
for elem in elem.iter():
tag = elem.tag
if isinstance(tag, QName):
if tag.text not in qnames:
add_qname(tag.text)
elif isinstance(tag, str):
if tag not in qnames:
add_qname(tag)
elif tag is not None and tag is not Comment and tag is not PI:
_raise_serialization_error(tag)
for key, value in elem.items():
if isinstance(key, QName):
key = key.text
if key not in qnames:
add_qname(key)
if isinstance(value, QName) and value.text not in qnames:
add_qname(value.text)
text = elem.text
if isinstance(text, QName) and text.text not in qnames:
add_qname(text.text)
return qnames, namespaces | null |
175,539 | from fontTools.misc.textTools import tostr
try:
from lxml.etree import *
_have_lxml = True
except ImportError:
try:
from xml.etree.cElementTree import *
# the cElementTree version of XML function doesn't support
# the optional 'parser' keyword argument
from xml.etree.ElementTree import XML
except ImportError: # pragma: no cover
from xml.etree.ElementTree import *
_have_lxml = False
import sys
# dict is always ordered in python >= 3.6 and on pypy
PY36 = sys.version_info >= (3, 6)
try:
import __pypy__
except ImportError:
__pypy__ = None
_dict_is_ordered = bool(PY36 or __pypy__)
del PY36, __pypy__
if _dict_is_ordered:
_Attrib = dict
else:
from collections import OrderedDict as _Attrib
if isinstance(Element, type):
_Element = Element
else:
# in py27, cElementTree.Element cannot be subclassed, so
# we need to import the pure-python class
from xml.etree.ElementTree import Element as _Element
_ElementTree = ElementTree
import io
# serialization support
import re
# Valid XML strings can include any Unicode character, excluding control
# characters, the surrogate blocks, FFFE, and FFFF:
# Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
# Here we reversed the pattern to match only the invalid characters.
# For the 'narrow' python builds supporting only UCS-2, which represent
# characters beyond BMP as UTF-16 surrogate pairs, we need to pass through
# the surrogate block. I haven't found a more elegant solution...
UCS2 = sys.maxunicode < 0x10FFFF
if UCS2:
_invalid_xml_string = re.compile(
"[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]"
)
else:
_invalid_xml_string = re.compile(
"[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"
)
def _tounicode(s):
import contextlib
from xml.etree.ElementTree import _namespace_map
def _escape_cdata(text):
def _escape_attrib(text):
def _serialize_xml(write, elem, qnames, namespaces, **kwargs):
tag = elem.tag
text = elem.text
if tag is Comment:
write("<!--%s-->" % _tounicode(text))
elif tag is ProcessingInstruction:
write("<?%s?>" % _tounicode(text))
else:
tag = qnames[_tounicode(tag) if tag is not None else None]
if tag is None:
if text:
write(_escape_cdata(text))
for e in elem:
_serialize_xml(write, e, qnames, None)
else:
write("<" + tag)
if namespaces:
for uri, prefix in sorted(
namespaces.items(), key=lambda x: x[1]
): # sort on prefix
if prefix:
prefix = ":" + prefix
write(' xmlns%s="%s"' % (prefix, _escape_attrib(uri)))
attrs = elem.attrib
if attrs:
# try to keep existing attrib order
if len(attrs) <= 1 or type(attrs) is _Attrib:
items = attrs.items()
else:
# if plain dict, use lexical order
items = sorted(attrs.items())
for k, v in items:
if isinstance(k, QName):
k = _tounicode(k.text)
else:
k = _tounicode(k)
if isinstance(v, QName):
v = qnames[_tounicode(v.text)]
else:
v = _escape_attrib(v)
write(' %s="%s"' % (qnames[k], v))
if text is not None or len(elem):
write(">")
if text:
write(_escape_cdata(text))
for e in elem:
_serialize_xml(write, e, qnames, None)
write("</" + tag + ">")
else:
write("/>")
if elem.tail:
write(_escape_cdata(elem.tail)) | null |
175,540 | from fontTools.misc.textTools import tostr
def _indent(elem, level=0):
# From http://effbot.org/zone/element-lib.htm#prettyprint
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
_indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i | null |
175,541 | import math
from typing import NamedTuple
from dataclasses import dataclass
_EPSILON = 1e-15
_ONE_EPSILON = 1 - _EPSILON
_MINUS_ONE_EPSILON = -1 + _EPSILON
def _normSinCos(v):
if abs(v) < _EPSILON:
v = 0
elif v > _ONE_EPSILON:
v = 1
elif v < _MINUS_ONE_EPSILON:
v = -1
return v | null |
175,542 | import math
from typing import NamedTuple
from dataclasses import dataclass
class Transform(NamedTuple):
"""2x2 transformation matrix plus offset, a.k.a. Affine transform.
Transform instances are immutable: all transforming methods, eg.
rotate(), return a new Transform instance.
:Example:
>>> t = Transform()
>>> t
<Transform [1 0 0 1 0 0]>
>>> t.scale(2)
<Transform [2 0 0 2 0 0]>
>>> t.scale(2.5, 5.5)
<Transform [2.5 0 0 5.5 0 0]>
>>>
>>> t.scale(2, 3).transformPoint((100, 100))
(200, 300)
Transform's constructor takes six arguments, all of which are
optional, and can be used as keyword arguments::
>>> Transform(12)
<Transform [12 0 0 1 0 0]>
>>> Transform(dx=12)
<Transform [1 0 0 1 12 0]>
>>> Transform(yx=12)
<Transform [1 0 12 1 0 0]>
Transform instances also behave like sequences of length 6::
>>> len(Identity)
6
>>> list(Identity)
[1, 0, 0, 1, 0, 0]
>>> tuple(Identity)
(1, 0, 0, 1, 0, 0)
Transform instances are comparable::
>>> t1 = Identity.scale(2, 3).translate(4, 6)
>>> t2 = Identity.translate(8, 18).scale(2, 3)
>>> t1 == t2
1
But beware of floating point rounding errors::
>>> t1 = Identity.scale(0.2, 0.3).translate(0.4, 0.6)
>>> t2 = Identity.translate(0.08, 0.18).scale(0.2, 0.3)
>>> t1
<Transform [0.2 0 0 0.3 0.08 0.18]>
>>> t2
<Transform [0.2 0 0 0.3 0.08 0.18]>
>>> t1 == t2
0
Transform instances are hashable, meaning you can use them as
keys in dictionaries::
>>> d = {Scale(12, 13): None}
>>> d
{<Transform [12 0 0 13 0 0]>: None}
But again, beware of floating point rounding errors::
>>> t1 = Identity.scale(0.2, 0.3).translate(0.4, 0.6)
>>> t2 = Identity.translate(0.08, 0.18).scale(0.2, 0.3)
>>> t1
<Transform [0.2 0 0 0.3 0.08 0.18]>
>>> t2
<Transform [0.2 0 0 0.3 0.08 0.18]>
>>> d = {t1: None}
>>> d
{<Transform [0.2 0 0 0.3 0.08 0.18]>: None}
>>> d[t2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: <Transform [0.2 0 0 0.3 0.08 0.18]>
"""
xx: float = 1
xy: float = 0
yx: float = 0
yy: float = 1
dx: float = 0
dy: float = 0
def transformPoint(self, p):
"""Transform a point.
:Example:
>>> t = Transform()
>>> t = t.scale(2.5, 5.5)
>>> t.transformPoint((100, 100))
(250.0, 550.0)
"""
(x, y) = p
xx, xy, yx, yy, dx, dy = self
return (xx * x + yx * y + dx, xy * x + yy * y + dy)
def transformPoints(self, points):
"""Transform a list of points.
:Example:
>>> t = Scale(2, 3)
>>> t.transformPoints([(0, 0), (0, 100), (100, 100), (100, 0)])
[(0, 0), (0, 300), (200, 300), (200, 0)]
>>>
"""
xx, xy, yx, yy, dx, dy = self
return [(xx * x + yx * y + dx, xy * x + yy * y + dy) for x, y in points]
def transformVector(self, v):
"""Transform an (dx, dy) vector, treating translation as zero.
:Example:
>>> t = Transform(2, 0, 0, 2, 10, 20)
>>> t.transformVector((3, -4))
(6, -8)
>>>
"""
(dx, dy) = v
xx, xy, yx, yy = self[:4]
return (xx * dx + yx * dy, xy * dx + yy * dy)
def transformVectors(self, vectors):
"""Transform a list of (dx, dy) vector, treating translation as zero.
:Example:
>>> t = Transform(2, 0, 0, 2, 10, 20)
>>> t.transformVectors([(3, -4), (5, -6)])
[(6, -8), (10, -12)]
>>>
"""
xx, xy, yx, yy = self[:4]
return [(xx * dx + yx * dy, xy * dx + yy * dy) for dx, dy in vectors]
def translate(self, x=0, y=0):
"""Return a new transformation, translated (offset) by x, y.
:Example:
>>> t = Transform()
>>> t.translate(20, 30)
<Transform [1 0 0 1 20 30]>
>>>
"""
return self.transform((1, 0, 0, 1, x, y))
def scale(self, x=1, y=None):
"""Return a new transformation, scaled by x, y. The 'y' argument
may be None, which implies to use the x value for y as well.
:Example:
>>> t = Transform()
>>> t.scale(5)
<Transform [5 0 0 5 0 0]>
>>> t.scale(5, 6)
<Transform [5 0 0 6 0 0]>
>>>
"""
if y is None:
y = x
return self.transform((x, 0, 0, y, 0, 0))
def rotate(self, angle):
"""Return a new transformation, rotated by 'angle' (radians).
:Example:
>>> import math
>>> t = Transform()
>>> t.rotate(math.pi / 2)
<Transform [0 1 -1 0 0 0]>
>>>
"""
import math
c = _normSinCos(math.cos(angle))
s = _normSinCos(math.sin(angle))
return self.transform((c, s, -s, c, 0, 0))
def skew(self, x=0, y=0):
"""Return a new transformation, skewed by x and y.
:Example:
>>> import math
>>> t = Transform()
>>> t.skew(math.pi / 4)
<Transform [1 0 1 1 0 0]>
>>>
"""
import math
return self.transform((1, math.tan(y), math.tan(x), 1, 0, 0))
def transform(self, other):
"""Return a new transformation, transformed by another
transformation.
:Example:
>>> t = Transform(2, 0, 0, 3, 1, 6)
>>> t.transform((4, 3, 2, 1, 5, 6))
<Transform [8 9 4 3 11 24]>
>>>
"""
xx1, xy1, yx1, yy1, dx1, dy1 = other
xx2, xy2, yx2, yy2, dx2, dy2 = self
return self.__class__(
xx1 * xx2 + xy1 * yx2,
xx1 * xy2 + xy1 * yy2,
yx1 * xx2 + yy1 * yx2,
yx1 * xy2 + yy1 * yy2,
xx2 * dx1 + yx2 * dy1 + dx2,
xy2 * dx1 + yy2 * dy1 + dy2,
)
def reverseTransform(self, other):
"""Return a new transformation, which is the other transformation
transformed by self. self.reverseTransform(other) is equivalent to
other.transform(self).
:Example:
>>> t = Transform(2, 0, 0, 3, 1, 6)
>>> t.reverseTransform((4, 3, 2, 1, 5, 6))
<Transform [8 6 6 3 21 15]>
>>> Transform(4, 3, 2, 1, 5, 6).transform((2, 0, 0, 3, 1, 6))
<Transform [8 6 6 3 21 15]>
>>>
"""
xx1, xy1, yx1, yy1, dx1, dy1 = self
xx2, xy2, yx2, yy2, dx2, dy2 = other
return self.__class__(
xx1 * xx2 + xy1 * yx2,
xx1 * xy2 + xy1 * yy2,
yx1 * xx2 + yy1 * yx2,
yx1 * xy2 + yy1 * yy2,
xx2 * dx1 + yx2 * dy1 + dx2,
xy2 * dx1 + yy2 * dy1 + dy2,
)
def inverse(self):
"""Return the inverse transformation.
:Example:
>>> t = Identity.translate(2, 3).scale(4, 5)
>>> t.transformPoint((10, 20))
(42, 103)
>>> it = t.inverse()
>>> it.transformPoint((42, 103))
(10.0, 20.0)
>>>
"""
if self == Identity:
return self
xx, xy, yx, yy, dx, dy = self
det = xx * yy - yx * xy
xx, xy, yx, yy = yy / det, -xy / det, -yx / det, xx / det
dx, dy = -xx * dx - yx * dy, -xy * dx - yy * dy
return self.__class__(xx, xy, yx, yy, dx, dy)
def toPS(self):
"""Return a PostScript representation
:Example:
>>> t = Identity.scale(2, 3).translate(4, 5)
>>> t.toPS()
'[2 0 0 3 8 15]'
>>>
"""
return "[%s %s %s %s %s %s]" % self
def toDecomposed(self) -> "DecomposedTransform":
"""Decompose into a DecomposedTransform."""
return DecomposedTransform.fromTransform(self)
def __bool__(self):
"""Returns True if transform is not identity, False otherwise.
:Example:
>>> bool(Identity)
False
>>> bool(Transform())
False
>>> bool(Scale(1.))
False
>>> bool(Scale(2))
True
>>> bool(Offset())
False
>>> bool(Offset(0))
False
>>> bool(Offset(2))
True
"""
return self != Identity
def __repr__(self):
return "<%s [%g %g %g %g %g %g]>" % ((self.__class__.__name__,) + self)
The provided code snippet includes necessary dependencies for implementing the `Offset` function. Write a Python function `def Offset(x=0, y=0)` to solve the following problem:
Return the identity transformation offset by x, y. :Example: >>> Offset(2, 3) <Transform [1 0 0 1 2 3]> >>>
Here is the function:
def Offset(x=0, y=0):
"""Return the identity transformation offset by x, y.
:Example:
>>> Offset(2, 3)
<Transform [1 0 0 1 2 3]>
>>>
"""
return Transform(1, 0, 0, 1, x, y) | Return the identity transformation offset by x, y. :Example: >>> Offset(2, 3) <Transform [1 0 0 1 2 3]> >>> |
175,543 | import ast
import string
def num2binary(l, bits=32):
items = []
binary = ""
for i in range(bits):
if l & 0x1:
binary = "1" + binary
else:
binary = "0" + binary
l = l >> 1
if not ((i + 1) % 8):
items.append(binary)
binary = ""
if binary:
items.append(binary)
items.reverse()
assert l in (0, -1), "number doesn't fit in number of bits"
return " ".join(items) | null |
175,544 | import ast
import string
def strjoin(iterable, joiner=""):
def binary2num(bin):
bin = strjoin(bin.split())
l = 0
for digit in bin:
l = l << 1
if digit != "0":
l = l | 0x1
return l | null |
175,545 | import ast
import string
The provided code snippet includes necessary dependencies for implementing the `caselessSort` function. Write a Python function `def caselessSort(alist)` to solve the following problem:
Return a sorted copy of a list. If there are only strings in the list, it will not consider case.
Here is the function:
def caselessSort(alist):
"""Return a sorted copy of a list. If there are only strings
in the list, it will not consider case.
"""
try:
return sorted(alist, key=lambda a: (a.lower(), a))
except TypeError:
return sorted(alist) | Return a sorted copy of a list. If there are only strings in the list, it will not consider case. |
175,546 | from types import SimpleNamespace
def _empty_decorator(x):
return x | null |
175,547 | class Classifier(object):
"""
Main Classifier object, used to classify things into similar sets.
"""
def __init__(self, sort=True):
self._things = set() # set of all things known so far
self._sets = [] # list of class sets produced so far
self._mapping = {} # map from things to their class set
self._dirty = False
self._sort = sort
def add(self, set_of_things):
"""
Add a set to the classifier. Any iterable is accepted.
"""
if not set_of_things:
return
self._dirty = True
things, sets, mapping = self._things, self._sets, self._mapping
s = set(set_of_things)
intersection = s.intersection(things) # existing things
s.difference_update(intersection) # new things
difference = s
del s
# Add new class for new things
if difference:
things.update(difference)
sets.append(difference)
for thing in difference:
mapping[thing] = difference
del difference
while intersection:
# Take one item and process the old class it belongs to
old_class = mapping[next(iter(intersection))]
old_class_intersection = old_class.intersection(intersection)
# Update old class to remove items from new set
old_class.difference_update(old_class_intersection)
# Remove processed items from todo list
intersection.difference_update(old_class_intersection)
# Add new class for the intersection with old class
sets.append(old_class_intersection)
for thing in old_class_intersection:
mapping[thing] = old_class_intersection
del old_class_intersection
def update(self, list_of_sets):
"""
Add a a list of sets to the classifier. Any iterable of iterables is accepted.
"""
for s in list_of_sets:
self.add(s)
def _process(self):
if not self._dirty:
return
# Do any deferred processing
sets = self._sets
self._sets = [s for s in sets if s]
if self._sort:
self._sets = sorted(self._sets, key=lambda s: (-len(s), sorted(s)))
self._dirty = False
# Output methods
def getThings(self):
"""Returns the set of all things known so far.
The return value belongs to the Classifier object and should NOT
be modified while the classifier is still in use.
"""
self._process()
return self._things
def getMapping(self):
"""Returns the mapping from things to their class set.
The return value belongs to the Classifier object and should NOT
be modified while the classifier is still in use.
"""
self._process()
return self._mapping
def getClasses(self):
"""Returns the list of class sets.
The return value belongs to the Classifier object and should NOT
be modified while the classifier is still in use.
"""
self._process()
return self._sets
The provided code snippet includes necessary dependencies for implementing the `classify` function. Write a Python function `def classify(list_of_sets, sort=True)` to solve the following problem:
Takes a iterable of iterables (list of sets from here on; but any iterable works.), and returns the smallest list of sets such that each set, is either a subset, or is disjoint from, each of the input sets. In other words, this function classifies all the things present in any of the input sets, into similar classes, based on which sets things are a member of. If sort=True, return class sets are sorted by decreasing size and their natural sort order within each class size. Otherwise, class sets are returned in the order that they were identified, which is generally not significant. >>> classify([]) == ([], {}) True >>> classify([[]]) == ([], {}) True >>> classify([[], []]) == ([], {}) True >>> classify([[1]]) == ([{1}], {1: {1}}) True >>> classify([[1,2]]) == ([{1, 2}], {1: {1, 2}, 2: {1, 2}}) True >>> classify([[1],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2,4]]) == ([{1}, {2}, {4}], {1: {1}, 2: {2}, 4: {4}}) True >>> classify([[1,2],[2,4,5]]) == ( ... [{4, 5}, {1}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2],[2,4,5]], sort=False) == ( ... [{1}, {4, 5}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2,9],[2,4,5]], sort=False) == ( ... [{1, 9}, {4, 5}, {2}], {1: {1, 9}, 2: {2}, 4: {4, 5}, 5: {4, 5}, ... 9: {1, 9}}) True >>> classify([[1,2,9,15],[2,4,5]], sort=False) == ( ... [{1, 9, 15}, {4, 5}, {2}], {1: {1, 9, 15}, 2: {2}, 4: {4, 5}, ... 5: {4, 5}, 9: {1, 9, 15}, 15: {1, 9, 15}}) True >>> classes, mapping = classify([[1,2,9,15],[2,4,5],[15,5]], sort=False) >>> set([frozenset(c) for c in classes]) == set( ... [frozenset(s) for s in ({1, 9}, {4}, {2}, {5}, {15})]) True >>> mapping == {1: {1, 9}, 2: {2}, 4: {4}, 5: {5}, 9: {1, 9}, 15: {15}} True
Here is the function:
def classify(list_of_sets, sort=True):
"""
Takes a iterable of iterables (list of sets from here on; but any
iterable works.), and returns the smallest list of sets such that
each set, is either a subset, or is disjoint from, each of the input
sets.
In other words, this function classifies all the things present in
any of the input sets, into similar classes, based on which sets
things are a member of.
If sort=True, return class sets are sorted by decreasing size and
their natural sort order within each class size. Otherwise, class
sets are returned in the order that they were identified, which is
generally not significant.
>>> classify([]) == ([], {})
True
>>> classify([[]]) == ([], {})
True
>>> classify([[], []]) == ([], {})
True
>>> classify([[1]]) == ([{1}], {1: {1}})
True
>>> classify([[1,2]]) == ([{1, 2}], {1: {1, 2}, 2: {1, 2}})
True
>>> classify([[1],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}})
True
>>> classify([[1,2],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}})
True
>>> classify([[1,2],[2,4]]) == ([{1}, {2}, {4}], {1: {1}, 2: {2}, 4: {4}})
True
>>> classify([[1,2],[2,4,5]]) == (
... [{4, 5}, {1}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}})
True
>>> classify([[1,2],[2,4,5]], sort=False) == (
... [{1}, {4, 5}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}})
True
>>> classify([[1,2,9],[2,4,5]], sort=False) == (
... [{1, 9}, {4, 5}, {2}], {1: {1, 9}, 2: {2}, 4: {4, 5}, 5: {4, 5},
... 9: {1, 9}})
True
>>> classify([[1,2,9,15],[2,4,5]], sort=False) == (
... [{1, 9, 15}, {4, 5}, {2}], {1: {1, 9, 15}, 2: {2}, 4: {4, 5},
... 5: {4, 5}, 9: {1, 9, 15}, 15: {1, 9, 15}})
True
>>> classes, mapping = classify([[1,2,9,15],[2,4,5],[15,5]], sort=False)
>>> set([frozenset(c) for c in classes]) == set(
... [frozenset(s) for s in ({1, 9}, {4}, {2}, {5}, {15})])
True
>>> mapping == {1: {1, 9}, 2: {2}, 4: {4}, 5: {5}, 9: {1, 9}, 15: {15}}
True
"""
classifier = Classifier(sort=sort)
classifier.update(list_of_sets)
return classifier.getClasses(), classifier.getMapping() | Takes a iterable of iterables (list of sets from here on; but any iterable works.), and returns the smallest list of sets such that each set, is either a subset, or is disjoint from, each of the input sets. In other words, this function classifies all the things present in any of the input sets, into similar classes, based on which sets things are a member of. If sort=True, return class sets are sorted by decreasing size and their natural sort order within each class size. Otherwise, class sets are returned in the order that they were identified, which is generally not significant. >>> classify([]) == ([], {}) True >>> classify([[]]) == ([], {}) True >>> classify([[], []]) == ([], {}) True >>> classify([[1]]) == ([{1}], {1: {1}}) True >>> classify([[1,2]]) == ([{1, 2}], {1: {1, 2}, 2: {1, 2}}) True >>> classify([[1],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2,4]]) == ([{1}, {2}, {4}], {1: {1}, 2: {2}, 4: {4}}) True >>> classify([[1,2],[2,4,5]]) == ( ... [{4, 5}, {1}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2],[2,4,5]], sort=False) == ( ... [{1}, {4, 5}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2,9],[2,4,5]], sort=False) == ( ... [{1, 9}, {4, 5}, {2}], {1: {1, 9}, 2: {2}, 4: {4, 5}, 5: {4, 5}, ... 9: {1, 9}}) True >>> classify([[1,2,9,15],[2,4,5]], sort=False) == ( ... [{1, 9, 15}, {4, 5}, {2}], {1: {1, 9, 15}, 2: {2}, 4: {4, 5}, ... 5: {4, 5}, 9: {1, 9, 15}, 15: {1, 9, 15}}) True >>> classes, mapping = classify([[1,2,9,15],[2,4,5],[15,5]], sort=False) >>> set([frozenset(c) for c in classes]) == set( ... [frozenset(s) for s in ({1, 9}, {4}, {2}, {5}, {15})]) True >>> mapping == {1: {1, 9}, 2: {2}, 4: {4}, 5: {5}, 9: {1, 9}, 15: {15}} True |
175,548 | illegalCharacters = r"\" * + / : < > ? [ \ ] | \0".split(" ")
illegalCharacters += [chr(i) for i in range(1, 32)]
illegalCharacters += [chr(0x7F)]
reservedFileNames = "CON PRN AUX CLOCK$ NUL A:-Z: COM1".lower().split(" ")
reservedFileNames += "LPT1 LPT2 LPT3 COM2 COM3 COM4".lower().split(" ")
maxFileNameLength = 255
def handleClash1(userName, existing=[], prefix="", suffix=""):
"""
existing should be a case-insensitive list
of all existing file names.
>>> prefix = ("0" * 5) + "."
>>> suffix = "." + ("0" * 10)
>>> existing = ["a" * 5]
>>> e = list(existing)
>>> handleClash1(userName="A" * 5, existing=e,
... prefix=prefix, suffix=suffix) == (
... '00000.AAAAA000000000000001.0000000000')
True
>>> e = list(existing)
>>> e.append(prefix + "aaaaa" + "1".zfill(15) + suffix)
>>> handleClash1(userName="A" * 5, existing=e,
... prefix=prefix, suffix=suffix) == (
... '00000.AAAAA000000000000002.0000000000')
True
>>> e = list(existing)
>>> e.append(prefix + "AAAAA" + "2".zfill(15) + suffix)
>>> handleClash1(userName="A" * 5, existing=e,
... prefix=prefix, suffix=suffix) == (
... '00000.AAAAA000000000000001.0000000000')
True
"""
# if the prefix length + user name length + suffix length + 15 is at
# or past the maximum length, silce 15 characters off of the user name
prefixLength = len(prefix)
suffixLength = len(suffix)
if prefixLength + len(userName) + suffixLength + 15 > maxFileNameLength:
l = prefixLength + len(userName) + suffixLength + 15
sliceLength = maxFileNameLength - l
userName = userName[:sliceLength]
finalName = None
# try to add numbers to create a unique name
counter = 1
while finalName is None:
name = userName + str(counter).zfill(15)
fullName = prefix + name + suffix
if fullName.lower() not in existing:
finalName = fullName
break
else:
counter += 1
if counter >= 999999999999999:
break
# if there is a clash, go to the next fallback
if finalName is None:
finalName = handleClash2(existing, prefix, suffix)
# finished
return finalName
The provided code snippet includes necessary dependencies for implementing the `userNameToFileName` function. Write a Python function `def userNameToFileName(userName, existing=[], prefix="", suffix="")` to solve the following problem:
Converts from a user name to a file name. Takes care to avoid illegal characters, reserved file names, ambiguity between upper- and lower-case characters, and clashes with existing files. Args: userName (str): The input file name. existing: A case-insensitive list of all existing file names. prefix: Prefix to be prepended to the file name. suffix: Suffix to be appended to the file name. Returns: A suitable filename. Raises: NameTranslationError: If no suitable name could be generated. Examples:: >>> userNameToFileName("a") == "a" True >>> userNameToFileName("A") == "A_" True >>> userNameToFileName("AE") == "A_E_" True >>> userNameToFileName("Ae") == "A_e" True >>> userNameToFileName("ae") == "ae" True >>> userNameToFileName("aE") == "aE_" True >>> userNameToFileName("a.alt") == "a.alt" True >>> userNameToFileName("A.alt") == "A_.alt" True >>> userNameToFileName("A.Alt") == "A_.A_lt" True >>> userNameToFileName("A.aLt") == "A_.aL_t" True >>> userNameToFileName(u"A.alT") == "A_.alT_" True >>> userNameToFileName("T_H") == "T__H_" True >>> userNameToFileName("T_h") == "T__h" True >>> userNameToFileName("t_h") == "t_h" True >>> userNameToFileName("F_F_I") == "F__F__I_" True >>> userNameToFileName("f_f_i") == "f_f_i" True >>> userNameToFileName("Aacute_V.swash") == "A_acute_V_.swash" True >>> userNameToFileName(".notdef") == "_notdef" True >>> userNameToFileName("con") == "_con" True >>> userNameToFileName("CON") == "C_O_N_" True >>> userNameToFileName("con.alt") == "_con.alt" True >>> userNameToFileName("alt.con") == "alt._con" True
Here is the function:
def userNameToFileName(userName, existing=[], prefix="", suffix=""):
"""Converts from a user name to a file name.
Takes care to avoid illegal characters, reserved file names, ambiguity between
upper- and lower-case characters, and clashes with existing files.
Args:
userName (str): The input file name.
existing: A case-insensitive list of all existing file names.
prefix: Prefix to be prepended to the file name.
suffix: Suffix to be appended to the file name.
Returns:
A suitable filename.
Raises:
NameTranslationError: If no suitable name could be generated.
Examples::
>>> userNameToFileName("a") == "a"
True
>>> userNameToFileName("A") == "A_"
True
>>> userNameToFileName("AE") == "A_E_"
True
>>> userNameToFileName("Ae") == "A_e"
True
>>> userNameToFileName("ae") == "ae"
True
>>> userNameToFileName("aE") == "aE_"
True
>>> userNameToFileName("a.alt") == "a.alt"
True
>>> userNameToFileName("A.alt") == "A_.alt"
True
>>> userNameToFileName("A.Alt") == "A_.A_lt"
True
>>> userNameToFileName("A.aLt") == "A_.aL_t"
True
>>> userNameToFileName(u"A.alT") == "A_.alT_"
True
>>> userNameToFileName("T_H") == "T__H_"
True
>>> userNameToFileName("T_h") == "T__h"
True
>>> userNameToFileName("t_h") == "t_h"
True
>>> userNameToFileName("F_F_I") == "F__F__I_"
True
>>> userNameToFileName("f_f_i") == "f_f_i"
True
>>> userNameToFileName("Aacute_V.swash") == "A_acute_V_.swash"
True
>>> userNameToFileName(".notdef") == "_notdef"
True
>>> userNameToFileName("con") == "_con"
True
>>> userNameToFileName("CON") == "C_O_N_"
True
>>> userNameToFileName("con.alt") == "_con.alt"
True
>>> userNameToFileName("alt.con") == "alt._con"
True
"""
# the incoming name must be a str
if not isinstance(userName, str):
raise ValueError("The value for userName must be a string.")
# establish the prefix and suffix lengths
prefixLength = len(prefix)
suffixLength = len(suffix)
# replace an initial period with an _
# if no prefix is to be added
if not prefix and userName[0] == ".":
userName = "_" + userName[1:]
# filter the user name
filteredUserName = []
for character in userName:
# replace illegal characters with _
if character in illegalCharacters:
character = "_"
# add _ to all non-lower characters
elif character != character.lower():
character += "_"
filteredUserName.append(character)
userName = "".join(filteredUserName)
# clip to 255
sliceLength = maxFileNameLength - prefixLength - suffixLength
userName = userName[:sliceLength]
# test for illegal files names
parts = []
for part in userName.split("."):
if part.lower() in reservedFileNames:
part = "_" + part
parts.append(part)
userName = ".".join(parts)
# test for clash
fullName = prefix + userName + suffix
if fullName.lower() in existing:
fullName = handleClash1(userName, existing, prefix, suffix)
# finished
return fullName | Converts from a user name to a file name. Takes care to avoid illegal characters, reserved file names, ambiguity between upper- and lower-case characters, and clashes with existing files. Args: userName (str): The input file name. existing: A case-insensitive list of all existing file names. prefix: Prefix to be prepended to the file name. suffix: Suffix to be appended to the file name. Returns: A suitable filename. Raises: NameTranslationError: If no suitable name could be generated. Examples:: >>> userNameToFileName("a") == "a" True >>> userNameToFileName("A") == "A_" True >>> userNameToFileName("AE") == "A_E_" True >>> userNameToFileName("Ae") == "A_e" True >>> userNameToFileName("ae") == "ae" True >>> userNameToFileName("aE") == "aE_" True >>> userNameToFileName("a.alt") == "a.alt" True >>> userNameToFileName("A.alt") == "A_.alt" True >>> userNameToFileName("A.Alt") == "A_.A_lt" True >>> userNameToFileName("A.aLt") == "A_.aL_t" True >>> userNameToFileName(u"A.alT") == "A_.alT_" True >>> userNameToFileName("T_H") == "T__H_" True >>> userNameToFileName("T_h") == "T__h" True >>> userNameToFileName("t_h") == "t_h" True >>> userNameToFileName("F_F_I") == "F__F__I_" True >>> userNameToFileName("f_f_i") == "f_f_i" True >>> userNameToFileName("Aacute_V.swash") == "A_acute_V_.swash" True >>> userNameToFileName(".notdef") == "_notdef" True >>> userNameToFileName("con") == "_con" True >>> userNameToFileName("CON") == "C_O_N_" True >>> userNameToFileName("con.alt") == "_con.alt" True >>> userNameToFileName("alt.con") == "alt._con" True |
175,549 | import decimal as _decimal
import math as _math
import warnings
from contextlib import redirect_stderr, redirect_stdout
from io import BytesIO
from io import StringIO as UnicodeIO
from types import SimpleNamespace
from .textTools import Tag, bytechr, byteord, bytesjoin, strjoin, tobytes, tostr
class Py23Error(NotImplementedError):
pass
def xrange(*args, **kwargs):
raise Py23Error("'xrange' is not defined. Use 'range' instead.") | null |
175,550 | import decimal as _decimal
import math as _math
import warnings
from contextlib import redirect_stderr, redirect_stdout
from io import BytesIO
from io import StringIO as UnicodeIO
from types import SimpleNamespace
from .textTools import Tag, bytechr, byteord, bytesjoin, strjoin, tobytes, tostr
The provided code snippet includes necessary dependencies for implementing the `round2` function. Write a Python function `def round2(number, ndigits=None)` to solve the following problem:
Implementation of Python 2 built-in round() function. Rounds a number to a given precision in decimal digits (default 0 digits). The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0. ndigits may be negative. See Python 2 documentation: https://docs.python.org/2/library/functions.html?highlight=round#round
Here is the function:
def round2(number, ndigits=None):
"""
Implementation of Python 2 built-in round() function.
Rounds a number to a given precision in decimal digits (default
0 digits). The result is a floating point number. Values are rounded
to the closest multiple of 10 to the power minus ndigits; if two
multiples are equally close, rounding is done away from 0.
ndigits may be negative.
See Python 2 documentation:
https://docs.python.org/2/library/functions.html?highlight=round#round
"""
if ndigits is None:
ndigits = 0
if ndigits < 0:
exponent = 10 ** (-ndigits)
quotient, remainder = divmod(number, exponent)
if remainder >= exponent // 2 and number >= 0:
quotient += 1
return float(quotient * exponent)
else:
exponent = _decimal.Decimal("10") ** (-ndigits)
d = _decimal.Decimal.from_float(number).quantize(
exponent, rounding=_decimal.ROUND_HALF_UP
)
return float(d) | Implementation of Python 2 built-in round() function. Rounds a number to a given precision in decimal digits (default 0 digits). The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0. ndigits may be negative. See Python 2 documentation: https://docs.python.org/2/library/functions.html?highlight=round#round |
175,551 |
def _makeunicodes(f):
lines = iter(f.readlines())
unicodes = {}
for line in lines:
if not line:
continue
num, name = line.split(";")[:2]
if name[0] == "<":
continue # "<control>", etc.
num = int(num, 16)
unicodes[num] = name
return unicodes | null |
175,552 | from .arc import EllipticalArc
import re
COMMANDS = set("MmZzLlHhVvCcSsQqTtAa")
UPPERCASE = set("MZLHVCSQTA")
def _tokenize_path(pathdef):
arc_cmd = None
for x in COMMAND_RE.split(pathdef):
if x in COMMANDS:
arc_cmd = x if x in ARC_COMMANDS else None
yield x
continue
if arc_cmd:
try:
yield from _tokenize_arc_arguments(x)
except ValueError as e:
raise ValueError(f"Invalid arc command: '{arc_cmd}{x}'") from e
else:
for token in FLOAT_RE.findall(x):
yield token
class EllipticalArc(object):
def __init__(self, current_point, rx, ry, rotation, large, sweep, target_point):
self.current_point = current_point
self.rx = rx
self.ry = ry
self.rotation = rotation
self.large = large
self.sweep = sweep
self.target_point = target_point
# SVG arc's rotation angle is expressed in degrees, whereas Transform.rotate
# uses radians
self.angle = radians(rotation)
# these derived attributes are computed by the _parametrize method
self.center_point = self.theta1 = self.theta2 = self.theta_arc = None
def _parametrize(self):
# convert from endopoint to center parametrization:
# https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
# If rx = 0 or ry = 0 then this arc is treated as a straight line segment (a
# "lineto") joining the endpoints.
# http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
rx = fabs(self.rx)
ry = fabs(self.ry)
if not (rx and ry):
return False
# If the current point and target point for the arc are identical, it should
# be treated as a zero length path. This ensures continuity in animations.
if self.target_point == self.current_point:
return False
mid_point_distance = (self.current_point - self.target_point) * 0.5
point_transform = Identity.rotate(-self.angle)
transformed_mid_point = _map_point(point_transform, mid_point_distance)
square_rx = rx * rx
square_ry = ry * ry
square_x = transformed_mid_point.real * transformed_mid_point.real
square_y = transformed_mid_point.imag * transformed_mid_point.imag
# Check if the radii are big enough to draw the arc, scale radii if not.
# http://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii
radii_scale = square_x / square_rx + square_y / square_ry
if radii_scale > 1:
rx *= sqrt(radii_scale)
ry *= sqrt(radii_scale)
self.rx, self.ry = rx, ry
point_transform = Scale(1 / rx, 1 / ry).rotate(-self.angle)
point1 = _map_point(point_transform, self.current_point)
point2 = _map_point(point_transform, self.target_point)
delta = point2 - point1
d = delta.real * delta.real + delta.imag * delta.imag
scale_factor_squared = max(1 / d - 0.25, 0.0)
scale_factor = sqrt(scale_factor_squared)
if self.sweep == self.large:
scale_factor = -scale_factor
delta *= scale_factor
center_point = (point1 + point2) * 0.5
center_point += complex(-delta.imag, delta.real)
point1 -= center_point
point2 -= center_point
theta1 = atan2(point1.imag, point1.real)
theta2 = atan2(point2.imag, point2.real)
theta_arc = theta2 - theta1
if theta_arc < 0 and self.sweep:
theta_arc += TWO_PI
elif theta_arc > 0 and not self.sweep:
theta_arc -= TWO_PI
self.theta1 = theta1
self.theta2 = theta1 + theta_arc
self.theta_arc = theta_arc
self.center_point = center_point
return True
def _decompose_to_cubic_curves(self):
if self.center_point is None and not self._parametrize():
return
point_transform = Identity.rotate(self.angle).scale(self.rx, self.ry)
# Some results of atan2 on some platform implementations are not exact
# enough. So that we get more cubic curves than expected here. Adding 0.001f
# reduces the count of sgements to the correct count.
num_segments = int(ceil(fabs(self.theta_arc / (PI_OVER_TWO + 0.001))))
for i in range(num_segments):
start_theta = self.theta1 + i * self.theta_arc / num_segments
end_theta = self.theta1 + (i + 1) * self.theta_arc / num_segments
t = (4 / 3) * tan(0.25 * (end_theta - start_theta))
if not isfinite(t):
return
sin_start_theta = sin(start_theta)
cos_start_theta = cos(start_theta)
sin_end_theta = sin(end_theta)
cos_end_theta = cos(end_theta)
point1 = complex(
cos_start_theta - t * sin_start_theta,
sin_start_theta + t * cos_start_theta,
)
point1 += self.center_point
target_point = complex(cos_end_theta, sin_end_theta)
target_point += self.center_point
point2 = target_point
point2 += complex(t * sin_end_theta, -t * cos_end_theta)
point1 = _map_point(point_transform, point1)
point2 = _map_point(point_transform, point2)
target_point = _map_point(point_transform, target_point)
yield point1, point2, target_point
def draw(self, pen):
for point1, point2, target_point in self._decompose_to_cubic_curves():
pen.curveTo(
(point1.real, point1.imag),
(point2.real, point2.imag),
(target_point.real, target_point.imag),
)
The provided code snippet includes necessary dependencies for implementing the `parse_path` function. Write a Python function `def parse_path(pathdef, pen, current_pos=(0, 0), arc_class=EllipticalArc)` to solve the following problem:
Parse SVG path definition (i.e. "d" attribute of <path> elements) and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath methods. If 'current_pos' (2-float tuple) is provided, the initial moveTo will be relative to that instead being absolute. If the pen has an "arcTo" method, it is called with the original values of the elliptical arc curve commands: pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y)) Otherwise, the arcs are approximated by series of cubic Bezier segments ("curveTo"), one every 90 degrees.
Here is the function:
def parse_path(pathdef, pen, current_pos=(0, 0), arc_class=EllipticalArc):
"""Parse SVG path definition (i.e. "d" attribute of <path> elements)
and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath
methods.
If 'current_pos' (2-float tuple) is provided, the initial moveTo will
be relative to that instead being absolute.
If the pen has an "arcTo" method, it is called with the original values
of the elliptical arc curve commands:
pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y))
Otherwise, the arcs are approximated by series of cubic Bezier segments
("curveTo"), one every 90 degrees.
"""
# In the SVG specs, initial movetos are absolute, even if
# specified as 'm'. This is the default behavior here as well.
# But if you pass in a current_pos variable, the initial moveto
# will be relative to that current_pos. This is useful.
current_pos = complex(*current_pos)
elements = list(_tokenize_path(pathdef))
# Reverse for easy use of .pop()
elements.reverse()
start_pos = None
command = None
last_control = None
have_arcTo = hasattr(pen, "arcTo")
while elements:
if elements[-1] in COMMANDS:
# New command.
last_command = command # Used by S and T
command = elements.pop()
absolute = command in UPPERCASE
command = command.upper()
else:
# If this element starts with numbers, it is an implicit command
# and we don't change the command. Check that it's allowed:
if command is None:
raise ValueError(
"Unallowed implicit command in %s, position %s"
% (pathdef, len(pathdef.split()) - len(elements))
)
last_command = command # Used by S and T
if command == "M":
# Moveto command.
x = elements.pop()
y = elements.pop()
pos = float(x) + float(y) * 1j
if absolute:
current_pos = pos
else:
current_pos += pos
# M is not preceded by Z; it's an open subpath
if start_pos is not None:
pen.endPath()
pen.moveTo((current_pos.real, current_pos.imag))
# when M is called, reset start_pos
# This behavior of Z is defined in svg spec:
# http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand
start_pos = current_pos
# Implicit moveto commands are treated as lineto commands.
# So we set command to lineto here, in case there are
# further implicit commands after this moveto.
command = "L"
elif command == "Z":
# Close path
if current_pos != start_pos:
pen.lineTo((start_pos.real, start_pos.imag))
pen.closePath()
current_pos = start_pos
start_pos = None
command = None # You can't have implicit commands after closing.
elif command == "L":
x = elements.pop()
y = elements.pop()
pos = float(x) + float(y) * 1j
if not absolute:
pos += current_pos
pen.lineTo((pos.real, pos.imag))
current_pos = pos
elif command == "H":
x = elements.pop()
pos = float(x) + current_pos.imag * 1j
if not absolute:
pos += current_pos.real
pen.lineTo((pos.real, pos.imag))
current_pos = pos
elif command == "V":
y = elements.pop()
pos = current_pos.real + float(y) * 1j
if not absolute:
pos += current_pos.imag * 1j
pen.lineTo((pos.real, pos.imag))
current_pos = pos
elif command == "C":
control1 = float(elements.pop()) + float(elements.pop()) * 1j
control2 = float(elements.pop()) + float(elements.pop()) * 1j
end = float(elements.pop()) + float(elements.pop()) * 1j
if not absolute:
control1 += current_pos
control2 += current_pos
end += current_pos
pen.curveTo(
(control1.real, control1.imag),
(control2.real, control2.imag),
(end.real, end.imag),
)
current_pos = end
last_control = control2
elif command == "S":
# Smooth curve. First control point is the "reflection" of
# the second control point in the previous path.
if last_command not in "CS":
# If there is no previous command or if the previous command
# was not an C, c, S or s, assume the first control point is
# coincident with the current point.
control1 = current_pos
else:
# The first control point is assumed to be the reflection of
# the second control point on the previous command relative
# to the current point.
control1 = current_pos + current_pos - last_control
control2 = float(elements.pop()) + float(elements.pop()) * 1j
end = float(elements.pop()) + float(elements.pop()) * 1j
if not absolute:
control2 += current_pos
end += current_pos
pen.curveTo(
(control1.real, control1.imag),
(control2.real, control2.imag),
(end.real, end.imag),
)
current_pos = end
last_control = control2
elif command == "Q":
control = float(elements.pop()) + float(elements.pop()) * 1j
end = float(elements.pop()) + float(elements.pop()) * 1j
if not absolute:
control += current_pos
end += current_pos
pen.qCurveTo((control.real, control.imag), (end.real, end.imag))
current_pos = end
last_control = control
elif command == "T":
# Smooth curve. Control point is the "reflection" of
# the second control point in the previous path.
if last_command not in "QT":
# If there is no previous command or if the previous command
# was not an Q, q, T or t, assume the first control point is
# coincident with the current point.
control = current_pos
else:
# The control point is assumed to be the reflection of
# the control point on the previous command relative
# to the current point.
control = current_pos + current_pos - last_control
end = float(elements.pop()) + float(elements.pop()) * 1j
if not absolute:
end += current_pos
pen.qCurveTo((control.real, control.imag), (end.real, end.imag))
current_pos = end
last_control = control
elif command == "A":
rx = abs(float(elements.pop()))
ry = abs(float(elements.pop()))
rotation = float(elements.pop())
arc_large = bool(int(elements.pop()))
arc_sweep = bool(int(elements.pop()))
end = float(elements.pop()) + float(elements.pop()) * 1j
if not absolute:
end += current_pos
# if the pen supports arcs, pass the values unchanged, otherwise
# approximate the arc with a series of cubic bezier curves
if have_arcTo:
pen.arcTo(
rx,
ry,
rotation,
arc_large,
arc_sweep,
(end.real, end.imag),
)
else:
arc = arc_class(
current_pos, rx, ry, rotation, arc_large, arc_sweep, end
)
arc.draw(pen)
current_pos = end
# no final Z command, it's an open path
if start_pos is not None:
pen.endPath() | Parse SVG path definition (i.e. "d" attribute of <path> elements) and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath methods. If 'current_pos' (2-float tuple) is provided, the initial moveTo will be relative to that instead being absolute. If the pen has an "arcTo" method, it is called with the original values of the elliptical arc curve commands: pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y)) Otherwise, the arcs are approximated by series of cubic Bezier segments ("curveTo"), one every 90 degrees. |
175,553 | from fontTools.misc.transform import Identity, Scale
from math import atan2, ceil, cos, fabs, isfinite, pi, radians, sin, sqrt, tan
def _map_point(matrix, pt):
# apply Transform matrix to a point represented as a complex number
r = matrix.transformPoint((pt.real, pt.imag))
return r[0] + r[1] * 1j | null |
175,554 | import re
def _prefer_non_zero(*args):
for arg in args:
if arg != 0:
return arg
return 0.0 | null |
175,555 | import re
def _ntos(n):
# %f likes to add unnecessary 0's, %g isn't consistent about # decimals
return ("%.3f" % n).rstrip("0").rstrip(".") | null |
175,556 | import re
def _strip_xml_ns(tag):
# ElementTree API doesn't provide a way to ignore XML namespaces in tags
# so we here strip them ourselves: cf. https://bugs.python.org/issue18304
return tag.split("}", 1)[1] if "}" in tag else tag | null |
175,557 | import re
def _transform(raw_value):
# TODO assumes a 'matrix' transform.
# No other transform functions are supported at the moment.
# https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
# start simple: if you aren't exactly matrix(...) then no love
match = re.match(r"matrix\((.*)\)", raw_value)
if not match:
raise NotImplementedError
matrix = tuple(float(p) for p in re.split(r"\s+|,", match.group(1)))
if len(matrix) != 6:
raise ValueError("wrong # of terms in %s" % raw_value)
return matrix | null |
175,558 | from __future__ import absolute_import
import logging
import os
from email.parser import FeedParser
from pip._vendor import pkg_resources
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.utils.misc import write_output
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
logger = logging.getLogger(__name__)
def canonicalize_name(name):
# type: (str) -> NormalizedName
# This is taken from PEP 503.
value = _canonicalize_regex.sub("-", name).lower()
return cast("NormalizedName", value)
The provided code snippet includes necessary dependencies for implementing the `search_packages_info` function. Write a Python function `def search_packages_info(query)` to solve the following problem:
Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory.
Here is the function:
def search_packages_info(query):
# type: (List[str]) -> Iterator[Dict[str, str]]
"""
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
"""
installed = {}
for p in pkg_resources.working_set:
installed[canonicalize_name(p.project_name)] = p
query_names = [canonicalize_name(name) for name in query]
missing = sorted(
[name for name, pkg in zip(query, query_names) if pkg not in installed]
)
if missing:
logger.warning('Package(s) not found: %s', ', '.join(missing))
def get_requiring_packages(package_name):
# type: (str) -> List[str]
canonical_name = canonicalize_name(package_name)
return [
pkg.project_name for pkg in pkg_resources.working_set
if canonical_name in
[canonicalize_name(required.name) for required in
pkg.requires()]
]
for dist in [installed[pkg] for pkg in query_names if pkg in installed]:
package = {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'requires': [dep.project_name for dep in dist.requires()],
'required_by': get_requiring_packages(dist.project_name)
}
file_list = None
metadata = ''
if isinstance(dist, pkg_resources.DistInfoDistribution):
# RECORDs should be part of .dist-info metadatas
if dist.has_metadata('RECORD'):
lines = dist.get_metadata_lines('RECORD')
paths = [line.split(',')[0] for line in lines]
paths = [os.path.join(dist.location, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('METADATA'):
metadata = dist.get_metadata('METADATA')
else:
# Otherwise use pip's log for .egg-info's
if dist.has_metadata('installed-files.txt'):
paths = dist.get_metadata_lines('installed-files.txt')
paths = [os.path.join(dist.egg_info, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('PKG-INFO'):
metadata = dist.get_metadata('PKG-INFO')
if dist.has_metadata('entry_points.txt'):
entry_points = dist.get_metadata_lines('entry_points.txt')
package['entry_points'] = entry_points
if dist.has_metadata('INSTALLER'):
for line in dist.get_metadata_lines('INSTALLER'):
if line.strip():
package['installer'] = line.strip()
break
# @todo: Should pkg_resources.Distribution have a
# `get_pkg_info` method?
feed_parser = FeedParser()
feed_parser.feed(metadata)
pkg_info_dict = feed_parser.close()
for key in ('metadata-version', 'summary',
'home-page', 'author', 'author-email', 'license'):
package[key] = pkg_info_dict.get(key)
# It looks like FeedParser cannot deal with repeated headers
classifiers = []
for line in metadata.splitlines():
if line.startswith('Classifier: '):
classifiers.append(line[len('Classifier: '):])
package['classifiers'] = classifiers
if file_list:
package['files'] = sorted(file_list)
yield package | Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. |
175,559 | from __future__ import absolute_import
import logging
import os
from email.parser import FeedParser
from pip._vendor import pkg_resources
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.utils.misc import write_output
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
def write_output(msg, *args):
# type: (Any, Any) -> None
logger.info(msg, *args)
The provided code snippet includes necessary dependencies for implementing the `print_results` function. Write a Python function `def print_results(distributions, list_files=False, verbose=False)` to solve the following problem:
Print the information from installed distributions found.
Here is the function:
def print_results(distributions, list_files=False, verbose=False):
# type: (Iterator[Dict[str, str]], bool, bool) -> bool
"""
Print the information from installed distributions found.
"""
results_printed = False
for i, dist in enumerate(distributions):
results_printed = True
if i > 0:
write_output("---")
write_output("Name: %s", dist.get('name', ''))
write_output("Version: %s", dist.get('version', ''))
write_output("Summary: %s", dist.get('summary', ''))
write_output("Home-page: %s", dist.get('home-page', ''))
write_output("Author: %s", dist.get('author', ''))
write_output("Author-email: %s", dist.get('author-email', ''))
write_output("License: %s", dist.get('license', ''))
write_output("Location: %s", dist.get('location', ''))
write_output("Requires: %s", ', '.join(dist.get('requires', [])))
write_output("Required-by: %s", ', '.join(dist.get('required_by', [])))
if verbose:
write_output("Metadata-Version: %s",
dist.get('metadata-version', ''))
write_output("Installer: %s", dist.get('installer', ''))
write_output("Classifiers:")
for classifier in dist.get('classifiers', []):
write_output(" %s", classifier)
write_output("Entry-points:")
for entry in dist.get('entry_points', []):
write_output(" %s", entry.strip())
if list_files:
write_output("Files:")
for line in dist.get('files', []):
write_output(" %s", line.strip())
if "files" not in dist:
write_output("Cannot locate installed-files.txt")
return results_printed | Print the information from installed distributions found. |
175,560 | from __future__ import absolute_import
import hashlib
import logging
import sys
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES
from pip._internal.utils.misc import read_chunks, write_output
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
"""Yield pieces of data from a file-like object until EOF."""
while True:
chunk = file.read(size)
if not chunk:
break
yield chunk
The provided code snippet includes necessary dependencies for implementing the `_hash_of_file` function. Write a Python function `def _hash_of_file(path, algorithm)` to solve the following problem:
Return the hash digest of a file.
Here is the function:
def _hash_of_file(path, algorithm):
# type: (str, str) -> str
"""Return the hash digest of a file."""
with open(path, 'rb') as archive:
hash = hashlib.new(algorithm)
for chunk in read_chunks(archive):
hash.update(chunk)
return hash.hexdigest() | Return the hash digest of a file. |
175,561 | from __future__ import absolute_import
import errno
import logging
import operator
import os
import shutil
import site
from optparse import SUPPRESS_HELP
from pip._vendor import pkg_resources
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cache import WheelCache
from pip._internal.cli import cmdoptions
from pip._internal.cli.cmdoptions import make_target_python
from pip._internal.cli.req_command import RequirementCommand, with_cleanup
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.exceptions import CommandError, InstallationError
from pip._internal.locations import distutils_scheme
from pip._internal.operations.check import check_install_conflicts
from pip._internal.req import install_given_reqs
from pip._internal.req.req_tracker import get_requirement_tracker
from pip._internal.utils.datetime import today_is_later_than
from pip._internal.utils.distutils_args import parse_distutils_args
from pip._internal.utils.filesystem import test_writable_dir
from pip._internal.utils.misc import (
ensure_dir,
get_installed_version,
get_pip_version,
protect_pip_from_modification_on_windows,
write_output,
)
from pip._internal.utils.temp_dir import TempDirectory
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
from pip._internal.utils.virtualenv import virtualenv_no_global
from pip._internal.wheel_builder import build, should_build_for_install_command
def canonicalize_name(name):
# type: (str) -> NormalizedName
# This is taken from PEP 503.
value = _canonicalize_regex.sub("-", name).lower()
return cast("NormalizedName", value)
def get_check_binary_allowed(format_control):
# type: (FormatControl) -> BinaryAllowedPredicate
def check_binary_allowed(req):
# type: (InstallRequirement) -> bool
if req.use_pep517:
return True
canonical_name = canonicalize_name(req.name)
allowed_formats = format_control.get_allowed_formats(canonical_name)
return "binary" in allowed_formats
return check_binary_allowed | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.