<commit_before># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Converts cubic bezier curves to quadratic splines.

Conversion is performed such that the quadratic splines keep the same end-curve
tangents as the original cubics. The approach is iterative, increasing the
number of segments for a spline until the error gets below a bound.

If necessary, respective curves from multiple fonts will be converted at once to
ensure that the resulting splines are interpolation-compatible.
"""


from math import hypot

from fontTools.misc import bezierTools
from robofab.objects.objectsRF import RSegment, RPoint


def replace_segments(contour, segments):
    try:
        contour.replace_segments(segments)
        return
    except AttributeError:
        pass

    while len(contour):
        contour.removeSegment(0)
    for s in segments:
        contour.appendSegment(s.type, [(p.x, p.y) for p in s.points], s.smooth)


def as_quadratic(segment, points):
    try:
        return segment.as_quadratic(points)
    except AttributeError:
        return RSegment(
            'qcurve', [[int(i) for i in p] for p in points], segment.smooth)


_zip = zip
def zip(*args):
    """Ensure each argument to zip has the same length."""
    if len(set(len(a) for a in args)) != 1:
        msg = 'Args to zip in convert_curves.py should have equal lengths: '
        raise ValueError(msg + ' '.join(str(a) for a in args))
    return _zip(*args)


class Point:
    """An arithmetic-compatible 2D vector.
    We use this because arithmetic with RoboFab's RPoint is prohibitively slow.
    """

    def __init__(self, p):
        self.p = map(float, p)

    def __getitem__(self, key):
        return self.p[key]

    def __add__(self, other):
        return Point([a + b for a, b in zip(self.p, other.p)])

    def __sub__(self, other):
        return Point([a - b for a, b in zip(self.p, other.p)])

    def __mul__(self, n):
        return Point([a * n for a in self.p])

    def dist(self, other):
        """Calculate the distance between two points."""
        return hypot(self[0] - other[0], self[1] - other[1])

    def dot(self, other):
        """Return the dot product of two points."""
        return self[0] * other[0] + self[1] * other[1]


def lerp(p1, p2, t):
    """Linearly interpolate between p1 and p2 at time t."""
    return p1 * (1 - t) + p2 * t


def quadratic_bezier_at(p, t):
    """Return the point on a quadratic bezier curve at time t."""

    return Point([
        lerp(lerp(p[0][0], p[1][0], t), lerp(p[1][0], p[2][0], t), t),
        lerp(lerp(p[0][1], p[1][1], t), lerp(p[1][1], p[2][1], t), t)])


def cubic_bezier_at(p, t):
    """Return the point on a cubic bezier curve at time t."""

    return Point([
        lerp(lerp(lerp(p[0][0], p[1][0], t), lerp(p[1][0], p[2][0], t), t),
             lerp(lerp(p[1][0], p[2][0], t), lerp(p[2][0], p[3][0], t), t), t),
        lerp(lerp(lerp(p[0][1], p[1][1], t), lerp(p[1][1], p[2][1], t), t),
             lerp(lerp(p[1][1], p[2][1], t), lerp(p[2][1], p[3][1], t), t), t)])


def cubic_approx(p, t):
    """Approximate a cubic bezier curve with a quadratic one."""

    p1 = lerp(p[0], p[1], 1.5)
    p2 = lerp(p[3], p[2], 1.5)
    return [p[0], lerp(p1, p2, t), p[3]]


def calc_intersect(p):
    """Calculate the intersection of ab and cd, given [a, b, c, d]."""

    a, b, c, d = p
    ab = b - a
    cd = d - c
    p = Point([-ab[1], ab[0]])
    try:
        h = p.dot(a - c) / p.dot(cd)
    except ZeroDivisionError:
        raise ValueError('Parallel vectors given to calc_intersect.')
    return c + cd * h


def cubic_approx_spline(p, n):
    """Approximate a cubic bezier curve with a spline of n quadratics.

    Returns None if n is 1 and the cubic's control vectors are parallel, since
    no quadratic exists with this cubic's tangents."""

    if n == 1:
        try:
            p1 = calc_intersect(p)
        except ValueError:
            return None
        return p[0], p1, p[3]
<commit_msg>Add comments, fix comment formatting.<commit_after># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Converts cubic bezier curves to quadratic splines.

Conversion is performed such that the quadratic splines keep the same end-curve
tangents as the original cubics. The approach is iterative, increasing the
number of segments for a spline until the error gets below a bound.

If necessary, respective curves from multiple fonts will be converted at once to
ensure that the resulting splines are interpolation-compatible.
"""


from math import hypot

from fontTools.misc import bezierTools
from robofab.objects.objectsRF import RSegment, RPoint


def replace_segments(contour, segments):
    """Replace the segments of a given contour."""

    try:
        contour.replace_segments(segments)
        return
    except AttributeError:
        pass

    while len(contour):
        contour.removeSegment(0)
    for s in segments:
        contour.appendSegment(s.type, [(p.x, p.y) for p in s.points], s.smooth)


def as_quadratic(segment, points):
    """Return a new segment with given points and type qcurve."""

    try:
        return segment.as_quadratic(points)
    except AttributeError:
        return RSegment(
            'qcurve', [[int(i) for i in p] for p in points], segment.smooth)


_zip = zip
def zip(*args):
    """Ensure each argument to zip has the same length."""

    if len(set(len(a) for a in args)) != 1:
        msg = 'Args to zip in convert_curves.py should have equal lengths: '
        raise ValueError(msg + ' '.join(str(a) for a in args))
    return _zip(*args)


class Point:
    """An arithmetic-compatible 2D vector.
    We use this because arithmetic with RoboFab's RPoint is prohibitively slow.
    """

    def __init__(self, p):
        self.p = map(float, p)

    def __getitem__(self, key):
        return self.p[key]

    def __add__(self, other):
        return Point([a + b for a, b in zip(self.p, other.p)])

    def __sub__(self, other):
        return Point([a - b for a, b in zip(self.p, other.p)])

    def __mul__(self, n):
        return Point([a * n for a in self.p])

    def dist(self, other):
        """Calculate the distance between two points."""
        return hypot(self[0] - other[0], self[1] - other[1])

    def dot(self, other):
        """Return the dot product of two points."""
        return self[0] * other[0] + self[1] * other[1]


def lerp(p1, p2, t):
    """Linearly interpolate between p1 and p2 at time t."""
    return p1 * (1 - t) + p2 * t


def quadratic_bezier_at(p, t):
    """Return the point on a quadratic bezier curve at time t."""

    return Point([
        lerp(lerp(p[0][0], p[1][0], t), lerp(p[1][0], p[2][0], t), t),
        lerp(lerp(p[0][1], p[1][1], t), lerp(p[1][1], p[2][1], t), t)])


def cubic_bezier_at(p, t):
    """Return the point on a cubic bezier curve at time t."""

    return Point([
        lerp(lerp(lerp(p[0][0], p[1][0], t), lerp(p[1][0], p[2][0], t), t),
             lerp(lerp(p[1][0], p[2][0], t), lerp(p[2][0], p[3][0], t), t), t),
        lerp(lerp(lerp(p[0][1], p[1][1], t), lerp(p[1][1], p[2][1], t), t),
             lerp(lerp(p[1][1], p[2][1], t), lerp(p[2][1], p[3][1], t), t), t)])


def cubic_approx(p, t):
    """Approximate a cubic bezier curve with a quadratic one."""

    p1 = lerp(p[0], p[1], 1.5)
    p2 = lerp(p[3], p[2], 1.5)
    return [p[0], lerp(p1, p2, t), p[3]]


def calc_intersect(p):
    """Calculate the intersection of ab and cd, given [a, b, c, d]."""

    a, b, c, d = p
    ab = b - a
    cd = d - c
    p = Point([-ab[1], ab[0]])
    try:
        h = p.dot(a - c) / p.dot(cd)
    except ZeroDivisionError:
        raise ValueError('Parallel vectors given to calc_intersect.')
    return c + cd * h


def cubic_approx_spline(p, n):
    """Approximate a cubic bezier curve with a spline of n quadratics.

    Returns None if n is 1 and the cubic's control vectors are parallel, since
    no quadratic exists with this cubic's tangents.
    """

    if n == 1:
        try:
            p1 = calc_intersect(p)
        except ValueError:
            return None
        return p[0], p1, p[3]

{'fraction_non_alphanumeric': 0.13551960039092192, 'fraction_numerical': 0.020849169290911067, 'mean_word_length': 2.914152146196345, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2931888', 'n_tokens_mistral': 3217, 'n_tokens_neox': 3036, 'n_words': 1125}