text:
""" $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University

This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the BSD-3 License for more details.

You should have received a copy of the Modified BSD-3 License along with this
program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
"""

from collections import OrderedDict, namedtuple
import math
import fastcache

from . import data_category_enum as de
from . import loop_blocking
from . import loop_enum as le
from . import mem_hier_enum as me
from . import partition
from .. import util
from .cost import Cost
from .data_layout import DataLayout
from .fmap_range import FmapPosition, FmapRange
from .layer import Layer
from .map_strategy import MapStrategy
from .resource import Resource
from .scheduling_constraint import SchedulingConstraint

class SchedulingCondition(namedtuple('SchedulingCondition',
                                     ['resource',
                                      'constraint',
                                      'ifmap_layout',
                                      'sched_seq',
                                     ])):
    '''
    Layer scheduling condition.
    '''

    def __new__(cls, *args, **kwargs):
        ntp = super(SchedulingCondition, cls).__new__(cls, *args, **kwargs)

        if not isinstance(ntp.resource, Resource):
            raise TypeError('SchedulingCondition: resource must be '
                            'a Resource instance.')
        if not isinstance(ntp.constraint, SchedulingConstraint):
            raise TypeError('SchedulingCondition: constraint must be '
                            'a SchedulingConstraint instance.')
        if not isinstance(ntp.ifmap_layout, DataLayout):
            raise TypeError('SchedulingCondition: ifmap_layout must be '
                            'a DataLayout instance.')
        if not isinstance(ntp.sched_seq, tuple):
            raise TypeError('SchedulingCondition: sched_seq must be a tuple.')
        if len(ntp.sched_seq) != 3:
            raise ValueError('SchedulingCondition: sched_seq must have '
                             '(segment, spatial, temporal) 3 indices.')

        return ntp

class SchedulingResult(namedtuple('SchedulingResult',
                                  ['scheme',
                                   'ofmap_layout',
                                   'sched_seq',
                                  ])):
    '''
    Layer scheduling result.
    '''

    def __new__(cls, *args, **kwargs):
        ntp = super(SchedulingResult, cls).__new__(cls, *args, **kwargs)

        if not isinstance(ntp.scheme, OrderedDict):
            raise TypeError('SchedulingResult: scheme must be an OrderedDict '
                            'instance.')
        if not isinstance(ntp.ofmap_layout, DataLayout):
            raise TypeError('SchedulingResult: ofmap_layout must be '
                            'a DataLayout instance.')
        if not isinstance(ntp.sched_seq, tuple):
            raise TypeError('SchedulingResult: sched_seq must be a tuple.')
        if len(ntp.sched_seq) != 3:
            raise ValueError('SchedulingResult: sched_seq must have '
                             '(segment, spatial, temporal) 3 indices.')

        return ntp

    @property
    def total_cost(self):
        ''' Get the total cost. '''
        return self.scheme['cost']

    @property
    def total_time(self):
        ''' Get the dataflow total time. '''
        return self.scheme['time']

    @property
    def total_node_time(self):
        ''' Get the total time on processing nodes. '''
        return max(self.scheme['proc_time'], self.scheme['bus_time'])

    @property
    def total_dram_time(self):
        ''' Get the total time on DRAM access. '''
        return self.scheme['dram_time']

    @property
    def total_proc_time(self):
        ''' Get the total active processing time. '''
        return self.scheme['proc_time']

    @property
    def total_ops(self):
        ''' Get the total ops. '''
        return self.scheme['ops']

    @property
    def total_accesses(self):
        ''' Get the total accesses at all memory hierarchies as a list. '''
        accesses = [sum(acc) for acc in self.scheme['access']]
        accesses[me.GBUF] += sum(self.scheme['remote_gbuf_access'])
        return accesses

    @property
    def total_noc_hops(self):
        ''' Get the total NoC hops. '''
        return sum(self.scheme['total_nhops'])

    @property
    def num_nodes(self):
        ''' Get the number of processing nodes. '''
        return self.scheme['num_nodes']

class Scheduling():
    '''
    Layer scheduling.
    '''

    def __init__(self, layer, batch_size, cost, map_strategy_class):

        if not isinstance(layer, Layer):
            raise TypeError('Scheduling: layer must be a Layer instance.')
        if not isinstance(cost, Cost):
            raise TypeError('Scheduling: cost must be a Cost instance.')

        if not issubclass(map_strategy_class, MapStrategy):
            raise TypeError('Scheduling: map_strategy_class must be '
                            'a subclass of MapStrategy.')

        self.layer = layer
        self.batch_size = batch_size
        self.cost = cost
        self.map_strategy_class = map_strategy_class

        # Default compare key function.
        self.cmp_key = lambda res: (res.total_cost, res.total_time)

    @fastcache.clru_cache(maxsize=1024)
    def schedule_search(self, condition, options):
        '''
        Search the best scheduling results.
        '''
        # Set key function.
        if options.opt_goal == 'ed':
            self.cmp_key = lambda res: res.total_cost * res.total_time
        elif options.opt_goal == 'd':
            self.cmp_key = lambda res: (res.total_time, res.total_cost)
        else:
            assert options.opt_goal == 'e'

        tops = []

        resource = condition.resource
        proc_region = resource.proc_region

        # Ifmap layout.
        ifmap_layout = condition.ifmap_layout
        # Ifmap should be from the source data region or local.
        if not ifmap_layout.is_in(resource.src_data_region, proc_region):
            raise ValueError('Scheduling: ifmap layout is not contained in '
                             'source data region.')
        ifrng = ifmap_layout.complete_fmap_range()
        if self.batch_size != ifrng.size('b') \
                or self.layer.nifm != ifrng.size('n') \
                or not self.layer.is_valid_padding_sifm([ifrng.size('h'),
                                                         ifrng.size('w')]):
            raise ValueError('Scheduling: ifmap layout does not match '
                             'input layer.')

        # Filter nodes. All memory nodes can store filters. Deduplicate.
        filter_nodes = frozenset(resource.dram_region.iter_node())

        # Explore parallel partitioning schemes.
        for part in partition.gen_partition(self.layer, self.batch_size,
                                            proc_region.dim, options,
                                            guaranteed=True):
            # Explore single-node schedules.
            lbs_tops = list(self.schedule_search_per_node(
                part, resource, condition.constraint, options))
            if not lbs_tops:
                continue

            # Ofmap layout.
            ofmap_range = FmapRange(
                FmapPosition(b=0, n=0, h=0, w=0),
                FmapPosition(b=self.batch_size, n=self.layer.nofm,
                             h=self.layer.hofm, w=self.layer.wofm))
            ofmap_data_region = resource.dst_data_region
            ofmap_layout = DataLayout(
                frngs=(ofmap_range,),
                regions=(ofmap_data_region,),
                parts=(part.projection(ofmap_data_region, appl2frng=True),))

            # Partition NoC hop cost.
            unit_nhops = partition.unit_nhops_to_proc_region(
                self.layer, self.batch_size, proc_region, part,
                filter_nodes, ifmap_layout, ofmap_layout, options)

            # Make scheduling result.
            tops += [self._get_result(lbs, part, ofmap_layout,
                                      condition.sched_seq, unit_nhops)
                     for lbs in lbs_tops]

        # Pick the top n.
        tops = sorted(tops, key=self.cmp_key)[:options.ntops]

        # Check total op count.
        total_layer_ops = self.layer.total_ops(self.batch_size)
        for t in tops:
            assert util.isclose(total_layer_ops, t.total_ops, rel_tol=1e-4)

        # Check ofmap layout matches the layer.
        for t in tops:
            ofrng = t.ofmap_layout.complete_fmap_range()
            assert ofrng.size('b') == self.batch_size \
                    and ofrng.size('n') == self.layer.nofm \
                    and ofrng.size('h') == self.layer.hofm \
                    and ofrng.size('w') == self.layer.wofm

        return list(tops)

    def cache_stats(self):
        '''
        Get the cache hits/misses stats. Return a tuple of (hits, misses).
        '''
        # pylint: disable=no-member
        info = self.schedule_search_per_node.cache_info()
        return (info.hits, info.misses)

    @fastcache.clru_cache(maxsize=1024)
    def schedule_search_per_node(self, part, resource, constraint, options):
        '''
        Search the best mapping strategies and loop blocking schemes for a
        single node after partitioning. Return the top LoopBlockingScheme
        instances.
        '''
        lbs_tops = []

        # Partitioned layer.
        p_layer, p_batch_size, p_occ = part.part_layer(self.layer,
                                                       self.batch_size)

        # Mapping strategy.
        map_strategy = self.map_strategy_class(p_layer, p_batch_size, p_occ,
                                               resource.dim_array)

        # Explore PE array mapping schemes for partitioned layer.
        for nested_loop_desc in map_strategy.gen_nested_loop_desc():

            # Explore loop blocking schemes.
            for lbs in loop_blocking.gen_loopblocking(
                    nested_loop_desc, resource, part, constraint, self.cost,
                    options):

                if lbs.is_valid():
                    lbs_tops.append(lbs)

        return lbs_tops

    def _get_result(self, lbs, part, ofmap_layout, sched_seq, unit_nhops):
        '''
        Make the schedule result from loop blocking and partitioning.
        '''
        scheme = OrderedDict()

        # Cost components.
        cost_access = lbs.get_access_cost(self.cost)

        # Inter-node data forwarding/rotation hops.
        node_nhops = lbs.get_noc_access()
        # Memory access hops.
        mem_nhops = [unh * f for unh, f
                     in zip(unit_nhops, lbs.get_top_level_fetch())]
        # Total hops = inter-node hops + memory hops.
        total_nhops = [nnh + mnh for nnh, mnh in zip(node_nhops, mem_nhops)]
        cost_noc = self.cost.noc_hop * sum(total_nhops)

        cost_op = self.cost.mac_op * lbs.ops

        cost_static = self.cost.idl_unit * lbs.time

        assert not math.isnan(cost_op + cost_access + cost_noc + cost_static)

        # Overall stats.
        scheme['cost'] = cost_op + cost_access + cost_noc + cost_static
        scheme['time'] = lbs.time
        scheme['ops'] = lbs.ops
        scheme['num_nodes'] = lbs.num_nodes
        scheme['is_dram'] = (lbs.src_is_dram, lbs.dst_is_dram)
        scheme['cost_op'] = cost_op
        scheme['cost_access'] = cost_access
        scheme['cost_noc'] = cost_noc
        scheme['cost_static'] = cost_static
        scheme['proc_time'] = lbs.proc_time
        scheme['bus_time'] = lbs.bus_time
        scheme['dram_time'] = lbs.dram_time
        scheme['access'] = lbs.get_access()
        scheme['remote_gbuf_access'] = lbs.remote_gbuf_access
        scheme['total_nhops'] = total_nhops
        scheme['fetch'] = lbs.fetch

        # Loop blocking.
        lp_ts = list(zip(*lbs.bl_ts))
        scheme['ti'] = tuple(lp_ts[le.IFM])
        scheme['to'] = tuple(lp_ts[le.OFM])
        scheme['tb'] = tuple(lp_ts[le.BAT])
        scheme['tvals'] = lbs.bl_ts
        scheme['orders'] = lbs.bl_ords
        scheme['size'] = [[lbs.data_size(bl, dce) for dce in range(de.NUM)]
                          for bl in range(lbs.BL.NUM)]
        scheme['unit_size'] = lbs.unit_size
        scheme['unit_cnt'] = lbs.unit_cnt
        scheme['accfwd_reduction'] = lbs.accfwd_reduction
        scheme['bufshr_grp_size'] = lbs.bufshr_grp_size
        scheme['bufshr_subgrp_size'] = lbs.bufshr_subgrp_size
        scheme['bufshr_bs_t'] = lbs.bufshr_bs_t
        scheme['bufshr_bs_ord'] = lbs.bufshr_bs_ord
        scheme['bufshr_rot_fetch'] = lbs.bufshr_rot_fetch
        scheme['bufshr_rot_round_cnt'] = lbs.bufshr_rot_round_cnt
        scheme['bufshr_rot_unit_cnt'] = lbs.bufshr_rot_unit_cnt
        scheme['bufshr_wide_fetch'] = lbs.bufshr_wide_fetch
        scheme['bufshr_wide_fetch_width'] = lbs.bufshr_wide_fetch_width

        # Partitioning.
        scheme['part'] = part
        scheme['mem_nhops'] = mem_nhops
        scheme['node_nhops'] = node_nhops
        scheme['unit_nhops'] = unit_nhops

        return SchedulingResult(scheme=scheme, ofmap_layout=ofmap_layout,
                                sched_seq=sched_seq)


text:
<?php

use MotaMonteiro\Helpers\Traits\StringHelper;
use PHPUnit\Framework\TestCase;

class FormatarIeCpfCnpjTest extends TestCase
{
    use StringHelper;

    public function testFormatarIe()
    {
        $this->assertEquals($this->formatarIeCpfCnpj('012345678'), '012.345.67-8');
    }

    public function testFormatarCpf()
    {
        $this->assertEquals($this->formatarIeCpfCnpj('01234567890'), '012.345.678-90');
    }

    public function testFormatarCnpj()
    {
        $this->assertEquals($this->formatarIeCpfCnpj('01234567890123'), '01.234.567/8901-23');
    }

    public function testFormatarValorVazio()
    {
        $this->assertEquals($this->formatarIeCpfCnpj(''), '##.###.###/####-##');
    }
}

redpajama_set_name: RedPajamaGithub


text: apache_module 'cache_socache'


text:
@implementation UIView (Chainable)

- (ChainableKit *)make {
    ChainableKit *chainable = [[ChainableKit alloc] init];
    chainable.view = self;
    return chainable;
}

+ (ChainableKit *)make {
    ChainableKit *chainable = [[ChainableKit alloc] init];
    UIView *view = [[self alloc] init];
    chainable.view = view;
    return chainable;
}

@end


text:
package com.javarush.task.task09.task0919;

/*
Деление на ноль
*/

public class Solution {

    public static void main(String[] args) {
        try {
            divisionByZero();
        }
        catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }

    public static void divisionByZero() {
        System.out.println(10 / 0);
    }
}


text:
'use strict';

var _                   = require('../../../i18n')
  , BusinessProcessDemo = require('../base');

module.exports = BusinessProcessDemo;

BusinessProcessDemo.prototype.costs.map.define('certificateOfIncentives', {
	nested: true
});

BusinessProcessDemo.prototype.costs.map.certificateOfIncentives.setProperties({
	label: _("Certificate of incentives"),
	amount: 100
});


text:
#include "config.h"

#include "core/svg/graphics/SVGImage.h"

#include "core/animation/AnimationTimeline.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/shadow/ComposedTreeTraversal.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/style/ComputedStyle.h"
#include "core/layout/svg/LayoutSVGRoot.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/paint/CompositingRecorder.h"
#include "core/paint/FloatClipRecorder.h"
#include "core/paint/TransformRecorder.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGFEImageElement.h"
#include "core/svg/SVGImageElement.h"
#include "core/svg/SVGSVGElement.h"
#include "core/svg/animation/SMILTimeContainer.h"
#include "core/svg/graphics/SVGImageChromeClient.h"
#include "platform/EventDispatchForbiddenScope.h"
#include "platform/LengthFunctions.h"
#include "platform/TraceEvent.h"
#include "platform/geometry/IntRect.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/ImageObserver.h"
#include "platform/graphics/paint/ClipRecorder.h"
#include "platform/graphics/paint/DrawingRecorder.h"
#include "platform/graphics/paint/SkPictureBuilder.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "wtf/PassRefPtr.h"

namespace blink {

SVGImage::SVGImage(ImageObserver* observer)
    : Image(observer)
{
}

SVGImage::~SVGImage()
{
    if (m_page) {
        // Store m_page in a local variable, clearing m_page, so that SVGImageChromeClient knows we're destructed.
        OwnPtrWillBeRawPtr<Page> currentPage = m_page.release();
        // Break both the loader and view references to the frame
        currentPage->willBeDestroyed();
    }

    // Verify that page teardown destroyed the Chrome
    ASSERT(!m_chromeClient || !m_chromeClient->image());
}

bool SVGImage::isInSVGImage(const Node* node)
{
    ASSERT(node);

    Page* page = node->document().page();
    if (!page)
        return false;

    return page->chromeClient().isSVGImageChromeClient();
}

bool SVGImage::currentFrameHasSingleSecurityOrigin() const
{
    if (!m_page)
        return true;

    LocalFrame* frame = toLocalFrame(m_page->mainFrame());

    RELEASE_ASSERT(frame->document()->loadEventFinished());

    SVGSVGElement* rootElement = frame->document()->accessSVGExtensions().rootElement();
    if (!rootElement)
        return true;

    // Don't allow foreignObject elements or images that are not known to be
    // single-origin since these can leak cross-origin information.
    for (Node* node = rootElement; node; node = ComposedTreeTraversal::next(*node)) {
        if (isSVGForeignObjectElement(*node))
            return false;
        if (isSVGImageElement(*node)) {
            if (!toSVGImageElement(*node).currentFrameHasSingleSecurityOrigin())
                return false;
        } else if (isSVGFEImageElement(*node)) {
            if (!toSVGFEImageElement(*node).currentFrameHasSingleSecurityOrigin())
                return false;
        }
    }

    // Because SVG image rendering disallows external resources and links, these
    // images effectively are restricted to a single security origin.
    return true;
}

static SVGSVGElement* svgRootElement(Page* page)
{
    if (!page)
        return nullptr;
    LocalFrame* frame = toLocalFrame(page->mainFrame());
    return frame->document()->accessSVGExtensions().rootElement();
}

void SVGImage::setContainerSize(const IntSize& size)
{
    if (!usesContainerSize())
        return;

    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement)
        return;

    FrameView* view = frameView();
    view->resize(this->containerSize());

    LayoutSVGRoot* layoutObject = toLayoutSVGRoot(rootElement->layoutObject());
    if (!layoutObject)
        return;
    layoutObject->setContainerSize(size);
}

IntSize SVGImage::containerSize() const
{
    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement)
        return IntSize();

    LayoutSVGRoot* layoutObject = toLayoutSVGRoot(rootElement->layoutObject());
    if (!layoutObject)
        return IntSize();

    // If a container size is available it has precedence.
    IntSize containerSize = layoutObject->containerSize();
    if (!containerSize.isEmpty())
        return containerSize;

    // Assure that a container size is always given for a non-identity zoom level.
    ASSERT(layoutObject->style()->effectiveZoom() == 1);

    FloatSize intrinsicSize;
    double intrinsicRatio = 0;
    layoutObject->computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);

    if (intrinsicSize.isEmpty() && intrinsicRatio) {
        if (!intrinsicSize.width() && intrinsicSize.height())
            intrinsicSize.setWidth(intrinsicSize.height() * intrinsicRatio);
        else if (intrinsicSize.width() && !intrinsicSize.height())
            intrinsicSize.setHeight(intrinsicSize.width() / intrinsicRatio);
    }

    // TODO(davve): In order to maintain aspect ratio the intrinsic
    // size is faked from the viewBox as a last resort. This may cause
    // unwanted side effects. Preferably we should be able to signal
    // the intrinsic ratio in another way.
    if (intrinsicSize.isEmpty())
        intrinsicSize = rootElement->currentViewBoxRect().size();

    if (!intrinsicSize.isEmpty())
        return expandedIntSize(intrinsicSize);

    // As last resort, use CSS replaced element fallback size.
    return IntSize(300, 150);
}

void SVGImage::drawForContainer(SkCanvas* canvas, const SkPaint& paint, const FloatSize containerSize, float zoom, const FloatRect& dstRect,
    const FloatRect& srcRect)
{
    if (!m_page)
        return;

    // Temporarily disable the image observer to prevent changeInRect() calls due re-laying out the image.
    ImageObserverDisabler imageObserverDisabler(this);

    IntSize roundedContainerSize = roundedIntSize(containerSize);
    setContainerSize(roundedContainerSize);

    FloatRect scaledSrc = srcRect;
    scaledSrc.scale(1 / zoom);

    // Compensate for the container size rounding by adjusting the source rect.
    FloatSize adjustedSrcSize = scaledSrc.size();
    adjustedSrcSize.scale(roundedContainerSize.width() / containerSize.width(), roundedContainerSize.height() / containerSize.height());
    scaledSrc.setSize(adjustedSrcSize);

    draw(canvas, paint, dstRect, scaledSrc, DoNotRespectImageOrientation, ClampImageToSourceRect);
}

PassRefPtr<SkImage> SVGImage::imageForCurrentFrame()
{
    // TODO(fmalita): instead of rasterizing, investigate returning a SkPicture-backed image.

    if (!m_page)
        return nullptr;

    IntSize size = this->size();
    SkImageInfo imageInfo = SkImageInfo::MakeN32(size.width(), size.height(), kPremul_SkAlphaType);
    SkSurfaceProps disableLCDProps(0, kUnknown_SkPixelGeometry);
    RefPtr<SkSurface> surface = adoptRef(SkSurface::NewRaster(imageInfo, &disableLCDProps));
    if (!surface)
        return nullptr;

    drawForContainer(surface->getCanvas(), SkPaint(), size, 1, rect(), rect());

    return adoptRef(surface->newImageSnapshot());
}

void SVGImage::drawPatternForContainer(GraphicsContext* context, const FloatSize containerSize,
    float zoom, const FloatRect& srcRect, const FloatSize& tileScale, const FloatPoint& phase,
    SkXfermode::Mode compositeOp, const FloatRect& dstRect,
    const IntSize& repeatSpacing)
{
    // Tile adjusted for scaling/stretch.
    FloatRect tile(srcRect);
    tile.scale(tileScale.width(), tileScale.height());

    // Expand the tile to account for repeat spacing.
    FloatRect spacedTile(tile);
    spacedTile.expand(repeatSpacing);

    SkPictureBuilder patternPicture(spacedTile, nullptr, context);
    if (!DrawingRecorder::useCachedDrawingIfPossible(patternPicture.context(), *this, DisplayItem::Type::SVGImage)) {
        DrawingRecorder patternPictureRecorder(patternPicture.context(), *this, DisplayItem::Type::SVGImage, spacedTile);
        // When generating an expanded tile, make sure we don't draw into the spacing area.
        if (tile != spacedTile)
            patternPicture.context().clip(tile);
        SkPaint paint;
        drawForContainer(patternPicture.context().canvas(), paint, containerSize, zoom, tile, srcRect);
    }
    RefPtr<const SkPicture> tilePicture = patternPicture.endRecording();

    SkMatrix patternTransform;
    patternTransform.setTranslate(phase.x() + spacedTile.x(), phase.y() + spacedTile.y());
    RefPtr<SkShader> patternShader = adoptRef(SkShader::CreatePictureShader(
        tilePicture.get(), SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode,
        &patternTransform, nullptr));

    SkPaint paint;
    paint.setShader(patternShader.get());
    paint.setXfermodeMode(compositeOp);
    paint.setColorFilter(context->colorFilter());
    context->drawRect(dstRect, paint);
}

static bool drawNeedsLayer(const SkPaint& paint)
{
    if (SkColorGetA(paint.getColor()) < 255)
        return true;

    SkXfermode::Mode xfermode;
    if (SkXfermode::AsMode(paint.getXfermode(), &xfermode)) {
        if (xfermode != SkXfermode::kSrcOver_Mode)
            return true;
    }

    return false;
}

void SVGImage::draw(SkCanvas* canvas, const SkPaint& paint, const FloatRect& dstRect, const FloatRect& srcRect, RespectImageOrientationEnum, ImageClampingMode)
{
    if (!m_page)
        return;

    FrameView* view = frameView();
    view->resize(containerSize());

    // Always call processUrlFragment, even if the url is empty, because
    // there may have been a previous url/fragment that needs to be reset.
    view->processUrlFragment(m_url);

    SkPictureBuilder imagePicture(dstRect);
    {
        ClipRecorder clipRecorder(imagePicture.context(), *this, DisplayItem::ClipNodeImage, LayoutRect(enclosingIntRect(dstRect)));

        // We can only draw the entire frame, clipped to the rect we want. So compute where the top left
        // of the image would be if we were drawing without clipping, and translate accordingly.
        FloatSize scale(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height());
        FloatSize topLeftOffset(srcRect.location().x() * scale.width(), srcRect.location().y() * scale.height());
        FloatPoint destOffset = dstRect.location() - topLeftOffset;
        AffineTransform transform = AffineTransform::translation(destOffset.x(), destOffset.y());
        transform.scale(scale.width(), scale.height());
        TransformRecorder transformRecorder(imagePicture.context(), *this, transform);

        view->updateAllLifecyclePhases();
        view->paint(&imagePicture.context(), enclosingIntRect(srcRect));
        ASSERT(!view->needsLayout());
    }

    {
        SkAutoCanvasRestore ar(canvas, false);
        if (drawNeedsLayer(paint)) {
            SkRect layerRect = dstRect;
            canvas->saveLayer(&layerRect, &paint);
        }
        RefPtr<const SkPicture> recording = imagePicture.endRecording();
        canvas->drawPicture(recording.get());
    }

    if (imageObserver())
        imageObserver()->didDraw(this);

    // Start any (SMIL) animations if needed. This will restart or continue
    // animations if preceded by calls to resetAnimation or stopAnimation
    // respectively.
    startAnimation();
}

LayoutBox* SVGImage::embeddedContentBox() const
{
    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement)
        return nullptr;
    return toLayoutBox(rootElement->layoutObject());
}

FrameView* SVGImage::frameView() const
{
    if (!m_page)
        return nullptr;

    return toLocalFrame(m_page->mainFrame())->view();
}

void SVGImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
{
    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement)
        return;

    intrinsicWidth = rootElement->intrinsicWidth();
    intrinsicHeight = rootElement->intrinsicHeight();
    if (rootElement->preserveAspectRatio()->currentValue()->align() == SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE)
        return;

    intrinsicRatio = rootElement->viewBox()->currentValue()->value().size();
    if (intrinsicRatio.isEmpty() && intrinsicWidth.isFixed() && intrinsicHeight.isFixed())
        intrinsicRatio = FloatSize(floatValueForLength(intrinsicWidth, 0), floatValueForLength(intrinsicHeight, 0));
}

// FIXME: support CatchUpAnimation = CatchUp.
void SVGImage::startAnimation(CatchUpAnimation)
{
    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement || !rootElement->animationsPaused())
        return;
    rootElement->unpauseAnimations();
}

void SVGImage::stopAnimation()
{
    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement)
        return;
    rootElement->pauseAnimations();
}

void SVGImage::resetAnimation()
{
    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement)
        return;
    rootElement->pauseAnimations();
    rootElement->setCurrentTime(0);
}

bool SVGImage::hasAnimations() const
{
    SVGSVGElement* rootElement = svgRootElement(m_page.get());
    if (!rootElement)
        return false;
    return rootElement->timeContainer()->hasAnimations() || toLocalFrame(m_page->mainFrame())->document()->timeline().hasPendingUpdates();
}

void SVGImage::updateUseCounters(Document& document) const
{
    if (SVGSVGElement* rootElement = svgRootElement(m_page.get())) {
        if (rootElement->timeContainer()->hasAnimations())
            UseCounter::countDeprecation(document, UseCounter::SVGSMILAnimationInImageRegardlessOfCache);
    }
}

bool SVGImage::dataChanged(bool allDataReceived)
{
    TRACE_EVENT0("blink", "SVGImage::dataChanged");

    // Don't do anything if is an empty image.
    if (!data()->size())
        return true;

    if (allDataReceived) {
        // SVGImage will fire events (and the default C++ handlers run) but doesn't
        // actually allow script to run so it's fine to call into it. We allow this
        // since it means an SVG data url can synchronously load like other image
        // types.
        EventDispatchForbiddenScope::AllowUserAgentEvents allowUserAgentEvents;

        static FrameLoaderClient* dummyFrameLoaderClient = new EmptyFrameLoaderClient;

        Page::PageClients pageClients;
        fillWithEmptyClients(pageClients);
        m_chromeClient = SVGImageChromeClient::create(this);
        pageClients.chromeClient = m_chromeClient.get();

        // FIXME: If this SVG ends up loading itself, we might leak the world.
        // The Cache code does not know about ImageResources holding Frames and
        // won't know to break the cycle.
        // This will become an issue when SVGImage will be able to load other
        // SVGImage objects, but we're safe now, because SVGImage can only be
        // loaded by a top-level document.
        OwnPtrWillBeRawPtr<Page> page;
        {
            TRACE_EVENT0("blink", "SVGImage::dataChanged::createPage");
            page = adoptPtrWillBeNoop(new Page(pageClients));
            page->settings().setScriptEnabled(false);
            page->settings().setPluginsEnabled(false);
            page->settings().setAcceleratedCompositingEnabled(false);

            // Because this page is detached, it can't get default font settings
            // from the embedder. Copy over font settings so we have sensible
            // defaults. These settings are fixed and will not update if changed.
            if (!Page::ordinaryPages().isEmpty()) {
                Settings& defaultSettings = (*Page::ordinaryPages().begin())->settings();
                page->settings().genericFontFamilySettings() = defaultSettings.genericFontFamilySettings();
                page->settings().setMinimumFontSize(defaultSettings.minimumFontSize());
                page->settings().setMinimumLogicalFontSize(defaultSettings.minimumLogicalFontSize());
                page->settings().setDefaultFontSize(defaultSettings.defaultFontSize());
                page->settings().setDefaultFixedFontSize(defaultSettings.defaultFixedFontSize());
            }
        }

        RefPtrWillBeRawPtr<LocalFrame> frame = nullptr;
        {
            TRACE_EVENT0("blink", "SVGImage::dataChanged::createFrame");
            frame = LocalFrame::create(dummyFrameLoaderClient, &page->frameHost(), 0);
            frame->setView(FrameView::create(frame.get()));
            frame->init();
        }

        FrameLoader& loader = frame->loader();
        loader.forceSandboxFlags(SandboxAll);

        frame->view()->setScrollbarsSuppressed(true);
        frame->view()->setCanHaveScrollbars(false); // SVG Images will always synthesize a viewBox, if it's not available, and thus never see scrollbars.
        frame->view()->setTransparent(true); // SVG Images are transparent.

        m_page = page.release();

        TRACE_EVENT0("blink", "SVGImage::dataChanged::load");
        loader.load(FrameLoadRequest(0, blankURL(), SubstituteData(data(), AtomicString("image/svg+xml", AtomicString::ConstructFromLiteral),
            AtomicString("UTF-8", AtomicString::ConstructFromLiteral), KURL(), ForceSynchronousLoad)));

        // Set the intrinsic size before a container size is available.
        m_intrinsicSize = containerSize();
    }

    return m_page;
}

String SVGImage::filenameExtension() const
{
    return "svg";
}

}


text:
.rendered_markdown {
    /* The default top/bottom margins for paragraphs are small, to make sure
       they look nice next to blockquotes, lists, etc. */
    p {
        margin: 3px 0;
    }

    /* The spacing between two paragraphs is significantly larger.  We
       arrange things so that this spacing matches the spacing between
       paragraphs in two consecutive 1-line messages. */
    p + p {
        margin-top: 10px;
    }

    /* Ensure bulleted lists are nicely centered in 1-line messages */
    ul {
        margin: 2px 0 5px 20px;
    }

    /* Swap the left and right margins of bullets for Right-To-Left languages */
    &.rtl ul {
        margin-right: 20px;
        margin-left: 0;
    }

    /* Ensure ordered lists are nicely centered in 1-line messages */
    ol {
        margin: 2px 0 5px 20px;
    }

    /* Swap the left and right margins of ordered list for Right-To-Left languages */
    &.rtl ol {
        margin-right: 8px;
        margin-left: 0;
    }

    /* Reduce top-margin when a paragraph is followed by an ordered or bulleted list */
    p + ul,
    p + ol {
        margin-top: 0;
    }

    hr {
        border-bottom: 1px solid hsl(0, 0%, 87%);
        border-top: 1px solid hsl(0, 0%, 87%);
    }

    /* Headings */
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
        font-weight: 600;
        line-height: 1.4;
        margin-top: 15px;
        margin-bottom: 5px;
    }

    /* Headings: Ensure that messages that start with a heading don't have
       a weirdly blank area at the very start of the message. */
    h1:first-child,
    h2:first-child,
    h3:first-child,
    h4:first-child,
    h5:first-child,
    h6:first-child {
        margin-top: 0;
    }

    /* We use a modest progression of heading sizes to make them stand out
       from normal next but avoid taking up too much space. */
    h1 {
        font-size: 1.4em;
    }

    h2 {
        font-size: 1.3em;
    }

    h3 {
        font-size: 1.2em;
    }

    h4 {
        font-size: 1.1em;
    }

    h5 {
        font-size: 1.05em;
    }

    h6 {
        font-size: 1em;
    }

    /* Formatting for blockquotes */
    blockquote {
        padding-left: 5px;
        margin-left: 10px;
        margin-top: 5px;
        margin-bottom: 6px;
        border-left-color: hsl(0, 0%, 87%);

        p {
            line-height: inherit;
            font-size: inherit;
        }
    }

    &.rtl blockquote {
        padding-left: unset;
        padding-right: 5px;
        margin-left: unset;
        margin-right: 10px;
        border-left: unset;
        border-right: 5px solid hsl(0, 0%, 87%);
    }

    /* Formatting for Markdown tables */
    table {
        padding-right: 10px;
        margin: 5px;
        width: 99%;
        display: block;
        max-width: fit-content;
        overflow-x: auto;
        white-space: nowrap;
    }

    thead {
        background-color: hsl(0, 0%, 93%);
    }

    tr {
        display: table-row;
        vertical-align: inherit;
    }

    tr th {
        border: 1px solid hsl(0, 0%, 80%);
        padding: 4px;
        text-align: left;
    }

    tr td {
        border: 1px solid hsl(0, 0%, 80%);
        padding: 4px;
    }

    /* Emoji; sized to be easily understood while not overwhelming text. */
    .emoji {
        height: 20px;
        width: 20px;
    }

    /* Mentions and alert words */
    .user-mention-me :not(.silent) {
        background-color: hsl(112, 88%, 87%);
    }

    .user-group-mention,
    .user-mention {
        border-radius: 3px;
        padding: 0 0.2em;
        box-shadow: 0 0 0 1px hsl(0, 0%, 80%);
        margin-right: 2px;
        margin-left: 2px;
        white-space: nowrap;
        background: linear-gradient(
            to bottom,
            hsla(0, 0%, 0%, 0.1) 0%,
            hsla(0, 0%, 0%, 0) 100%
        );
        display: inline-block;
        margin-bottom: 1px;
    }

    .alert-word {
        background-color: hsla(102, 85%, 57%, 0.5);
    }

    /* Timestamps */
    time {
        background: hsl(0, 0%, 93%);
        border-radius: 3px;
        padding: 0 0.2em;
        box-shadow: 0 0 0 1px hsl(0, 0%, 80%);
        white-space: nowrap;
        margin-left: 2px;
        margin-right: 2px;
        display: inline-block;
        margin-bottom: 1px;
    }

    /* LaTeX styling */
    .katex-display {
        /* KaTeX sometimes overdraws its bounding box by a little, so we
           enlarge its scrolling area by stealing 3px from the margin
           of the enclosing <p>. */
        margin: -3px 0;
        padding: 3px 0;
        overflow: auto hidden;
    }

    .tex-error {
        color: hsl(0, 0%, 50%);
    }

    /* Spoiler styling */
    .spoiler-block {
        border: hsl(0, 0%, 50%) 1px solid;
        padding: 2px 8px 2px 10px;
        border-radius: 10px;
        position: relative;
        top: 1px;
        display: block;
        margin: 5px 0 15px;

        .spoiler-header {
            padding: 5px;
            font-weight: bold;
        }

        .spoiler-content {
            overflow: hidden;
            border-top: hsl(0, 0%, 50%) 0 solid;
            transition: height 0.4s ease-in-out, border-top 0.4s step-end,
                padding 0.4s step-end;
            padding: 0;
            height: 0;

            &.spoiler-content-open {
                border-top: hsl(0, 0%, 50%) 1px solid;
                transition: height 0.4s ease-in-out, border-top 0.4s step-start,
                    padding 0.4s step-start;
                padding: 5px;
                height: auto;
            }
        }

        .spoiler-button {
            float: right;
            width: 25px;
            height: 25px;

            &:hover .spoiler-arrow {
                &::before,
                &::after {
                    background-color: hsl(0, 0%, 50%);
                }
            }
        }

        .spoiler-arrow {
            float: right;
            width: 13px;
            height: 13px;
            position: relative;
            bottom: -5px;
            left: -10px;
            cursor: pointer;
            transition: 0.4s ease;
            margin-top: 2px;
            text-align: left;
            transform: rotate(45deg);

            &::before,
            &::after {
                position: absolute;
                content: "";
                display: inline-block;
                width: 12px;
                height: 3px;
                background-color: hsl(0, 0%, 83%);
                transition: 0.4s ease;
            }

            &::after {
                position: absolute;
                transform: rotate(90deg);
                top: -5px;
                left: 5px;
            }

            &.spoiler-button-open {
                transform: rotate(45deg) translate(-5px, -5px);

                &::before {
                    transform: translate(10px, 0);
                }

                &::after {
                    transform: rotate(90deg) translate(10px, 0);
                }
            }
        }
    }

    /* embedded link previews */
    .message_inline_image_title {
        font-weight: bold;
    }

    .twitter-image,
    .message_inline_image {
        position: relative;
        margin-bottom: 5px;
        margin-right: 5px;

        /* Sizing CSS for inline images requires care, because images load
           asynchronously, and browsers will unfortunately jump your
           scroll position when elements load above the current
           position in the message feed in a way that changes the
           height of elements. (As of March 2022, both Firefox and
           Chrome exhibit this problem, though in Chrome it is pretty
           subtle).

           We prevent this by setting a fixed height for inline
           previews. 100px is chosen because we don't want images to
           overwhelm conversation in message feeds, as it does in chat
           tools that show images at half-screen height or larger.

           If there are several images next to each other, we display
           them in a grid format; the same considerations requires
           that either use a scrollable region or set a fixed width
           for images so that the browser statically knows whether
           it'll need to overflow. We choose fixed width here. */
        height: 100px;
        width: 150px;

        /* Inline image containers also need an inline-block display in order
           to implement the desired grid layout. */
        display: inline-block;

        /* Set a background for the image; the background will be visible for
           messages whose aspect ratio is different from that of this
           container. */
        border: solid 1px transparent;
        transition: background 0.3s ease;
        background: hsla(0, 0%, 0%, 0.03);

        &:hover {
            background: hsla(0, 0%, 0%, 0.15);
        }

        a {
            display: block;
            height: 100%;
            width: 100%;
        }
    }

    &.rtl .twitter-image,
    &.rtl .message_inline_image {
        margin-left: unset;
        margin-right: 5px;
    }

    .twitter-tweet {
        border: 1px solid hsl(0, 0%, 87%);
        padding: 0.5em 0.75em;
        margin-bottom: 0.25em;
        word-break: break-word;
        min-height: 48px;
    }

    .twitter-avatar {
        float: left;
        width: 48px;
        height: 48px;
        margin-right: 0.75em;
    }

    .message_inline_ref {
        margin-bottom: 5px;
        margin-left: 5px;
        height: 50px;
        display: block !important;
        border: none !important;
    }

    &.rtl .message_inline_ref {
        margin-left: unset;
        margin-right: 5px;
    }

    .twitter-image img,
    .message_inline_image img,
    .message_inline_ref img {
        /* We use `scale-down` so that images smaller than the container are
           neither scaled up up or cropped to fit. This preserves
           their aspect ratio, which is often helpful. */
        object-fit: scale-down;

        /* We need to explicitly specify the image dimensions to have
           object-fit work; likely because internally object-fit needs
           to know the frame it is targeting, and images don't default
           to container dimensions. */
        height: 100%;
        width: 100%;

        float: left;
        margin-right: 10px;
        border-radius: inherit;
    }

    .message_inline_image img {
        cursor: zoom-in;
    }

    .youtube-video img,
    .vimeo-video img,
    .embed-video img {
        cursor: pointer;
    }

    &.rtl .twitter-image img,
    &.rtl .message_inline_image img,
    &.rtl .message_inline_ref img {
        float: right;
        margin-right: unset;
        margin-left: 10px;
    }

    li .message_inline_image img {
        float: none;
    }

    .youtube-video .fa-play::before,
    .embed-video .fa-play::before {
        position: absolute;
        margin: var(--margin-top, 32px) 0 0 var(--margin-left, 45px);
        padding: 5px 8px 5px 10px;
        font-size: 12px;
        border-radius: 4px;
        background-color: hsl(0, 0%, 0%);
        color: hsl(0, 0%, 100%);
        opacity: 0.7;
        top: 0;
        left: 0;
    }

    .message_embed {
        display: block;
        position: relative;
        margin: 5px 0;
        border: none;
        border-left: 3px solid hsl(0, 0%, 93%);
        height: 80px;
        padding: 5px;
        z-index: 1;
        text-shadow: hsla(0, 0%, 0%, 0.01) 0 0 1px;

        .message_embed_title {
            padding-top: 0;
            /* to remove the spacing that the font has from the top of the container. */
            margin-top: -5px;

            font-size: 1.2em;
            line-height: normal;
        }

        .message_embed_description {
            position: relative;
            max-width: 500px;
            margin-top: 3px;

            /* to put it below the container gradient. */
            z-index: -1;
        }

        .message_embed_image {
            display: inline-block;
            width: 70px;
            height: 70px;
            background-size: cover;
            background-position: center;
        }

        .data-container {
            position: relative;
            padding: 0 5px;
            display: inline-block;
            vertical-align: top;
            max-width: calc(100% - 115px);
            max-height: 80px;
            overflow: hidden;
        }

        .data-container div {
            display: block;
            border: none;
        }

        .data-container::after {
            content: " ";
            position: absolute;
            width: 100%;
            height: 10%;
            bottom: 0;

            background: linear-gradient(
                0deg,
                hsl(0, 0%, 100%),
                transparent 100%
            );
        }
    }

    &.rtl .message_embed {
        border-left: unset;
        border-right: 3px solid hsl(0, 0%, 93%);
    }

    .message_embed > * {
        display: inherit;
        padding: 5px;
        border: none;
    }

    pre {
        &:hover .copy_codeblock,
        &:hover .code_external_link {
            visibility: visible;
        }
    }

    /* Style copy-to-clipboard button inside code blocks */
    .copy_codeblock {
        visibility: hidden;
        /* Having absolute positioning here ensures that the element
        doesn't scroll along with the code div in narrow windows */
        position: absolute;
        right: 2px;
        margin-top: -4px;
    }

    .code_external_link {
        visibility: hidden;
        position: absolute;
        right: 23px;
        margin-top: -3px;
        font-size: 17px;
        /* The default icon and on-hover colors are inherited from <a> tag.
        so we set our own to match the copy-to-clipbord icon */
        color: hsl(0, 0%, 47%);

        &:hover {
            color: hsl(200, 100%, 40%);
        }
    }
}

.preview_content .copy_codeblock {
    /* We avoid displaying copy_codeblock button in previews, because it
       feels odd given that you can just copy-paste the code out of
       the "edit" state.  We may change this decision when we add
       menu options for viewing the code in a coding playground. */
    display: none;
}

.informational-overlays .copy_codeblock {
    display: none;
}

.message_edit_history_content .copy_codeblock {
    /*  Copy code block button is hidden in edit history, this is done
        because of issues faced in copying code blocks in edit history
        modal. This may be changed later as we decide upon a proper ux
        for displaying edit-history. */
    display: none;
}

.message_edit_history_content .code_external_link {
    right: 5px;
}

.preview_content .code_external_link {
    right: 12px;
}

@media (width < $sm_min) {
    .rendered_markdown .message_embed {
        height: auto;

        .message_embed_image {
            width: 100%;
            height: 100px;
        }

        .data-container {
            display: block;
            max-width: 100%;
            margin-top: 10px;
        }
    }
}

/* Inline and block code.

TODO: It is likely that this CSS can and should be moved into the
rendered_markdown block; we just need to do further analysis to
confirm doing so won't break anything. */

code {
    /* 11.55px when body is the default 14px; this is chosen to be
       slightly above the 11.5px threshold where the height jumps by a
       pixel on most platforms. */
    font-size: 0.825em;
    unicode-bidi: embed;
    direction: ltr;
    color: hsl(0, 0%, 0%);
    white-space: pre;
}

.rendered_markdown code {
    white-space: pre-wrap;
    padding: 0 4px;
    background-color: hsl(0, 0%, 100%);
}

.codehilite {
    display: block !important;
    border: none !important;
    background: none !important;
}

pre {
    direction: ltr;
    /* code block text is a bit smaller than normal text */
    font-size: 0.825em;
    line-height: 1.4;
    white-space: pre;
    overflow-x: auto;
    word-wrap: normal;
    /* Bootstrap's default here is top: 0px, bottom: 10px */
    margin-top: 5px;
    margin-bottom: 5px;
    /* Bootstrap's default here is 9.5 on all sides */
    padding: 5px 7px 3px;
}

.rendered_markdown pre code {
    font-size: inherit;
    padding: 0;
    white-space: inherit;
}

/* Both the horizontal scrollbar in <pre/> as well as
   vertical scrollbar in the <textarea/> is styled similarly. */
.message_edit_form textarea,
pre {
    /* Ensure the horizontal scrollbar is visible on Mac */
    &::-webkit-scrollbar {
        height: 8px;
        width: 10px;
        background-color: hsla(0, 0%, 0%, 0.05);
    }

    &::-webkit-scrollbar-thumb {
        background-color: hsla(0, 0%, 0%, 0.3);
        border-radius: 20px;
        transition: all 0.2s ease;
    }

    &::-webkit-scrollbar-thumb:hover {
        background-color: hsla(0, 0%, 0%, 0.6);
    }
}

pre code {
    overflow-x: scroll;
    white-space: pre;
}

/* Style inline code inside a link
   to look more like a normal link */
a code {
    color: hsl(200, 100%, 40%);
}

a:hover code {
    color: hsl(200, 100%, 25%);
}

/* Search highlight used in both topics and rendered_markdown */
.highlight {
    background-color: hsl(51, 94%, 74%);
}


text:
**This is not an officially supported Google product.**

## Overview
Google Cloud Platform features a set of virtual components to facilitate the
network deployment, including virtualized cloud router, firewall, routing table,
network peering, VPN gateway and VPN tunnel, as well as other interconnections
such as direct connections and public Internet access. Though even simpler in
configuration and deployment compared with SDN, virtualized components still exhibit subtle
behavior features which once encountered with, may be hard to analysis and
reinstate. Existing efforts present in network intent verifications where a
series of user-specified checks can be launched against the current network
control plane or data plane to find out whether the current network contains a
forwarding loop, drops traffic which should be forwarded, etc.

This work fills the gap between the configuration and verification by providing
a **derivation engine** to figure out the new data plane based on the current
one and a proposed set of configuration changes. The derivation focuses on the
routing table because most, if not all, configuration changes that may cause
"chain reactions" on the data plane are ones that influencing the routes.

For easy extension with future features, the derivation engine is designed
and implemented in a generalized **configuration-based** style. With a fixed
derivation pipeline as a generalized derivation framework, some pluggable
configurations (being `ProtoBuf`s or `Python` snippets) are loaded as a complete
description of the current behavior of the real GCP under a configuration
update. The configurations are designed in a declarative style instead of
imperative style. This way decouples the configuration description and the
execution of the derivation engine and is thus considered as much easier for
reasoning and debugging.

## Derivation framework
![Derivation workflow](docs/logic-flow.png)
**Derivation workflow**

![Workflow for match](docs/subprocess-match.png)
**Workflow for match**

## Declarative configurations

The configurations are mainly divided into two categories: generation rules and generators.

A generation rule is a ProtoBuf message `RouteDerivationRule` in [this file](proto/cloud_network_model.proto).

Basically, it contains a list of filters and destinations. If any filter exactly matches a route, then the matched route is propagated to all destinations specified in this rule.

```protobuf
message RouteDerivationRule {
  optional string name = 1;

  // The filter of a route to be applied for this rule.
  // Recommended usage: set `type` or `region` to pick the routes for a single type or region
  // The matching is exact match for all present fields.
  // Can specify many filters and if any filter is an exact match, this whole rule is a match
  //
  // A limited programming ability is provided to specify some predicates based on
  // the Route proto. In each field of the Route proto where the type is "string", use
  // triple grave accent (```) in the beginning to start a Python boolean lambda function
  // body. This lambda has the following implicit parameters:
  // - *route* the route being matched
  // And the return value is converted to a boolean. If exception are raised, consider it
  // as a non-match
  // Example:
  //    filters {
  //      region: "us-west1"
  //    }
  //    and
  //    filters {
  //      region: "```route.region == 'us-west1'"
  //    }
  // Both rules match routes that in region us-west1.
  repeated Route filters = 2;

  // A limited programming ability is provided to specify some predicates based on
  // the Route proto. The predicate is expressed by a Python boolean lambda function body.
  // This lambda has the following implicit parameters:
  // - *route* the route being matched
  //
  // And the return value is converted to a boolean. If exception are raised, consider it
  // as a non-match
  // Example:
  // {
  //   lambda_filters: "route.instance_filter.attributes[0].tag"
  // }
  // This rule matches routes that are assigned with tags.
  repeated string lambda_filters = 3;

  repeated DestinationAndGeneration destinations = 6;
}

```

And the `DestinationAndGeneration` is defined as

```protobuf
message DestinationAndGeneration {
  // The new route are generated in the following priority order:
  // - generated by a series of corresponding Python functions
  // - copied from the original route, and merged from the route_template
  // - copied from the original route
  //
  // The naming convention to access the Python functions are:
  // - all .py files under src/derivation_rules are parsed and only functions are extracted.
  // - the functions should not collide in names
  // - the functions are invoked by name, in the following order:
  //    -- <destination_name>_generator
  //    -- <rule_name>_<destination name>_generator
  //        the rule_name here is the optional name of the matching RouteDerivationRule
  //
  // - each function receives three parameters: route, context, and model
  // - each function modifies the input route, and returns the same route
  // - the context is a destination-specific protobuf defined below as "DestinationContext"
  //
  // A limited programming ability is provided to specify some predicates based on
  // the Route proto. In each field of the Route proto where the type is "string", use
  // triple grave accent (```) in the beginning to start a Python lambda function
  // body. This lambda has the following implicit parameters:
  // - *route* the route being generated
  // - *root_route* the root route
  // - *region* the region to install the route, for dynamic and peering_dynamic routes.
  //
  // And the return value is converted to a string. If exception are raised, skip this field
  // Example:
  //    route_template {
  //      region: "```root_route.region"
  //    }
  optional Route route_template = 4;

  // The destinations have fixed builtin semantics in destination selection and actions.
  //   - VPC_PEERS:                  all active peering VPC networks
  //
  //   - VPC_PEERS_CUSTOM_ROUTING:   all active peering VPC networks that import custom routes
  //                                 from the route's network, and simultaneously, the route's
  //                                 network export custom routes to them.
  //
  //   - REGIONS_OF_VPC_PEERS_CUSTOM_ROUTING: all active peering VPC networks that import
  //                                 custom routes from the route's network, and simultaneously,
  //                                 the route's network export custom routes to them. The route
  //                                 is exported to all regions that the network has presence.
  //
  //   - BGP_PEERS:                  all networks that hold one or more *live* BGP session with
  //                                 the current network, and the involved VPN tunnels in current
  //                                 network enable subnet advertising.
  //
  //   - OTHER_REGIONS_WHEN_GLOBAL_ROUTING:   all regions other than the route's region, when the
  //                                 current network enables global routing.
  //
  // Some fixed actions are bound to each destination as part of the semantics of the destination.
  // These semantics are written as rules
  // For all:
  // - set name, id, url
  // - update the *instance_filter.network*
  //
  // For VPC peering:
  // - update *next_hop_peering*
  // - delete other next hops
  // - change the route type to the corresponding peering type
  //
  // For BGP peering:
  // - fill the field "region"
  // - update *next_hop_tunnel*
  // - delete other next hops
  enum Destination {
    // VPC_PEERS works as a short cut for VPC_PEERS_NO_CUSTOM_ROUTING
    // and VPC_PEERS_CUSTOM_ROUTING. It is first internally translated
    // to VPC_PEERS_NO_CUSTOM_ROUTING and VPC_PEERS_CUSTOM_ROUTING,
    // before any derivation process
    VPC_PEERS = 0;
    VPC_PEERS_CUSTOM_ROUTING = 2;
    REGIONS_OF_VPC_PEERS_CUSTOM_ROUTING = 1;
    BGP_PEERS = 3;
    OTHER_REGIONS_WHEN_GLOBAL_ROUTING = 4;
  }

  required Destination destination = 6;

  message DestinationContext {
    required string network = 1;
    // for regional routes
    optional string region = 2;
    // the vpc peering, or the vpn tunnel used in BGP peering
    optional string peer_info = 3;
  }
}
```

The generators are Python functions that are responsible to generate the derived route based on the origional route, the current network, and the generation context. These generator functions contain logics that are easy to express in Python while difficult in ProtoBuf.

The generation of a single derived route is divided into several steps, calling generators from the most generalized to the most specific, identified based on their names. The common generator is always called, while the function shares the name with the current generation destination is called later, and the function with the rule name is called last. Because a later called function has a clearer view and the ability to override the fields set by previous functions, the most specific function has the highest priority.

## Currently supported derivation rules

### Overview:
-	Cloud Router: can advertise subnet routes and user specified prefixes. Static/dynamic routes are not advertised.
-	VPC Peering: will export subnet routes. can export custom routes (with no tags, not to Internet)
-	Dynamic/static routes: only propagated for peering. Dynamic routes depend on the regional configurations.

### Detailed rules for propagation via BGP and VPC peering
-	A cloud router might not advertise subnet routes
-	A cloud router always accepts all learned routes
-	A VPC always exports subnet routes
-	A VPC always accepts subnet routes
-	A VPC might not export custom routes
-	A VPC might not import custom routes

### Possible propagation paths of routes or prefixes
-	**A static route (with tags or to the Internet)**
    *no more propagation*
-	**A static route (with no tags and not to Internet)**
    *exported to all VPC peers as peering static routes*
-	**A subnet route**
    *exported to all VPC peers as peering subnet routes and Cloud Routers as BGP prefixes*
-	**A custom prefix in a Cloud Router**
    *learned by the peering Cloud Router as a BGP prefix*
    - This is not a route, and thus not configured with a rule
-	**A dynamic route**:
    *exported to all VPC peers as peering dynamic routes*

-	**A BGP prefix**: depending on the routing mode of its network
    - [`regional mode`] *installed in the region of the VPN tunnel as a dynamic route*
    - [`global mode`] *installed in all regions as dynamic routes (with adjusted regional cost)*

-	**A peering subnet route**
    *no more propagation*
-	**A peering static route**
    *no more propagation*
-	**A peering dynamic route**
    *no more propagation*

## Use cases
### Derivation after configuration change

Dynamic routes
1. In a BGP session, an IP prefix is advertised or withdrawn from the BGP peer
2. A VPN tunnel is removed (remove learned routes and derived routes of the associated BGP session)
3. A custom IP prefix is added to or deleted from the BGP session of a VPN Tunnel, while the other end is also in GCP
4. The MED of a BGP session is changed, then the priorities of custom route and dynamic routes are all updated

Subnet routes
1. A subnet is added, (of course) with new IP ranges, or deleted.
2. An IP range is added to a subnet (the current GCP API does not support deletion of IP ranges, but deleting is supported and tested in this derivation engine)
3. An IP range of a subnet is changed (in the current GCP API, the IP range can only be enlarged, and only the primary range is adjustable)

Static routes
1. A static route is added or removed
2. The priority, tags, etc. of a static route is changed (the current GCP API does not support modification, but this feature is supported and tested in this derivation engine)

### Debugging the root cause of an unexpected routing behavior
All routes in the data plane model, together with the derivation relation as the directed edges, form a forest, where the root of each tree is the root route of all its offspring routes.
Many unexpected routing behaviors are caused by some undesired route. The derivation engine can help find the root route that generates an unexpected route, to faster the root-cause process for users (being it an end customer or some automation systems).

### Find out why a route is not generated
The user may expect a route to be inserted based on the current configuration, but in dataplane, the route is not inserted. This derivation engine can serve finding the cause by providing logs for the reference of the user.

## Run demo
The demos are also the test cases. To run it on a Ubuntu machine, please execute the following commands in shell:

```bash
sudo pip3 install protobuf
sudo apt install protobuf-compiler

git clone https://github.com/googleinterns/connectivity-test
cd connectivity-test

protoc --proto_path=./ --python_out=./ proto/*.proto

python3 -m unittest src.declarative_derivation_test.TestDataPlane
```

Single test can be executed by
```bash
python3 -m unittest src.declarative_derivation_test.TestDataPlane.test_deriveAfterSubnetAdded
```

Currently 11 tests associated with the use cases are carried out in sequence.


text:
#ifndef _BSD_SYS_LIBKERN_H_
#define	_BSD_SYS_LIBKERN_H_

#include <sys/bsd_cdefs.h>
#include <sys/bsd_types.h>
#ifdef _FREEBSD_KERNEL
#include <sys/bsd_systm.h>
#endif

#ifndef	LIBKERN_INLINE
#define	LIBKERN_INLINE  static __inline
#define	LIBKERN_BODY
#endif

#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* BCD conversions. */
extern u_char const	bcd2bin_data[];
extern u_char const	bin2bcd_data[];
extern char const	hex2ascii_data[];

#define	bcd2bin(bcd)	(bcd2bin_data[bcd])
#define	bin2bcd(bin)	(bin2bcd_data[bin])
#define	hex2ascii(hex)	(hex2ascii_data[hex])

static __inline int imax(int a, int b) { return (a > b ? a : b); }
static __inline int imin(int a, int b) { return (a < b ? a : b); }
static __inline long lmax(long a, long b) { return (a > b ? a : b); }
static __inline long lmin(long a, long b) { return (a < b ? a : b); }
static __inline u_int max(u_int a, u_int b) { return (a > b ? a : b); }
static __inline u_int min(u_int a, u_int b) { return (a < b ? a : b); }
static __inline quad_t qmax(quad_t a, quad_t b) { return (a > b ? a : b); }
static __inline quad_t qmin(quad_t a, quad_t b) { return (a < b ? a : b); }
static __inline u_long ulmax(u_long a, u_long b) { return (a > b ? a : b); }
static __inline u_long ulmin(u_long a, u_long b) { return (a < b ? a : b); }
static __inline off_t omax(off_t a, off_t b) { return (a > b ? a : b); }
static __inline off_t omin(off_t a, off_t b) { return (a < b ? a : b); }

//static __inline int abs(int a) { return (a < 0 ? -a : a); }
//static __inline long labs(long a) { return (a < 0 ? -a : a); }
//static __inline quad_t qabs(quad_t a) { return (a < 0 ? -a : a); }

/* Prototypes for non-quad routines. */
struct malloc_type;
uint32_t arc4random(void);
void	 arc4rand(void *ptr, u_int len, int reseed);
//int	 bcmp(const void *, const void *, size_t);
void	*bsearch(const void *, const void *, size_t,
	    size_t, int (*)(const void *, const void *));
#ifndef	HAVE_INLINE_FFS
int	 ffs(int);
#endif
#ifndef	HAVE_INLINE_FFSL
int	 ffsl(long);
#endif
#ifndef	HAVE_INLINE_FLS
int	 fls(int);
#endif
#ifndef	HAVE_INLINE_FLSL
int	 flsl(long);
#endif
#if 0
int	 fnmatch(const char *, const char *, int);
void	 gets(char *, size_t, int);
#endif //0
int	 locc(int, char *, u_int);
//int	 memcmp(const void *b1, const void *b2, size_t len);
//void	 qsort(void *base, size_t nmemb, size_t size,
//	    int (*compar)(const void *, const void *));
//void	 qsort_r(void *base, size_t nmemb, size_t size, void *thunk,
//	    int (*compar)(void *, const void *, const void *));
//u_long	 random(void);
//char	*index(const char *, int);
//char	*rindex(const char *, int);
int	 scanc(u_int, const u_char *, const u_char *, int);
int	 skpc(int, int, char *);
//void	 srandom(u_long);
//int	 strcasecmp(const char *, const char *);
//char	*strcat(char * __restrict, const char * __restrict);
//int	 strcmp(const char *, const char *);
//char	*strcpy(char * __restrict, const char * __restrict);
//size_t	 strcspn(const char * __restrict, const char * __restrict) __pure;
//char	*strdup(const char *__restrict, struct malloc_type *);
//size_t	 strlcat(char *, const char *, size_t);
//size_t	 strlcpy(char *, const char *, size_t);
//size_t	 strlen(const char *);
//int	 strncasecmp(const char *, const char *, size_t);
//int	 strncmp(const char *, const char *, size_t);
//char	*strncpy(char * __restrict, const char * __restrict, size_t);
//char	*strsep(char **, const char *delim);
//size_t	 strspn(const char *, const char *);
//char	*strstr(const char *, const char *);
//int	 strvalid(const char *, size_t);

extern uint32_t crc32_tab[];

static __inline uint32_t
crc32_raw(const void *buf, size_t size, uint32_t crc)
{
	const uint8_t *p = (const uint8_t *)buf;

	while (size--)
		crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
	return (crc);
}

static __inline uint32_t
crc32(const void *buf, size_t size)
{
	uint32_t crc;

	crc = crc32_raw(buf, size, ~0U);
	return (crc ^ ~0U);
}

uint32_t
calculate_crc32c(uint32_t crc32c, const unsigned char *buffer,
        unsigned int length);

#if 0
LIBKERN_INLINE void *memset(void *, int, size_t);
#ifdef LIBKERN_BODY
LIBKERN_INLINE void *
memset(void *b, int c, size_t len)
{
	char *bb;

	if (c == 0)
		bzero(b, len);
	else
		for (bb = (char *)b; len--; )
			*bb++ = c;
	return (b);
}
#endif

static __inline char *
strchr(const char *p, int ch)
{
	return (index(p, ch));
}

static __inline char *
strrchr(const char *p, int ch)
{
	return (rindex(p, ch));
}
#endif

#include <fnmatch.h>
#if 0
/* fnmatch() return values. */
#define	FNM_NOMATCH	1	/* Match failed. */

/* fnmatch() flags. */
#define	FNM_NOESCAPE	0x01	/* Disable backslash escaping. */
#define	FNM_PATHNAME	0x02	/* Slash must be matched by slash. */
#define	FNM_PERIOD	0x04	/* Period must be matched by period. */
#define	FNM_LEADING_DIR	0x08	/* Ignore /<tail> after Imatch. */
#define	FNM_CASEFOLD	0x10	/* Case insensitive search. */
#define	FNM_IGNORECASE	FNM_CASEFOLD
#define	FNM_FILE_NAME	FNM_PATHNAME
#endif //0

#endif /* !_BSD_SYS_LIBKERN_H_ */


text:
package com.opengamma.analytics.math.interpolation;

import static org.testng.AssertJUnit.assertEquals;

import org.testng.annotations.Test;

import cern.jet.random.engine.MersenneTwister;
import cern.jet.random.engine.MersenneTwister64;
import cern.jet.random.engine.RandomEngine;

import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.data.Interpolator1DDoubleQuadraticDataBundle;
import com.opengamma.util.test.TestGroup;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class DoubleQuadraticInterpolator1DNodeSensitivityCalculatorTest {
  private static final RandomEngine RANDOM = new MersenneTwister64(MersenneTwister.DEFAULT_SEED);
  private static final DoubleQuadraticInterpolator1D INTERPOLATOR = new DoubleQuadraticInterpolator1D();
  private static final Interpolator1DDoubleQuadraticDataBundle DATA;
  private static final double EPS = 1e-7;
  private static final Function1D<Double, Double> FUNCTION = new Function1D<Double, Double>() {

    private static final double a = -0.045;
    private static final double b = 0.03;
    private static final double c = 0.3;
    private static final double d = 0.05;

    @Override
    public Double evaluate(final Double x) {
      return (a + b * x) * Math.exp(-c * x) + d;
    }

  };

  static {
    final double[] t = new double[] {0.0, 0.5, 1.0, 2.0, 3.0, 5.0, 7.0, 10.0, 15.0, 17.5, 20.0, 25.0, 30.0};
    final int n = t.length;
    final double[] r = new double[n];
    for (int i = 0; i < n; i++) {
      r[i] = FUNCTION.evaluate(t[i]);
    }
    DATA = INTERPOLATOR.getDataBundleFromSortedArrays(t, r);

  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void nullInputData() {
    INTERPOLATOR.getNodeSensitivitiesForValue(null, 3.);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testHighValue() {
    INTERPOLATOR.getNodeSensitivitiesForValue(DATA, 31.);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testLowValue() {
    INTERPOLATOR.getNodeSensitivitiesForValue(DATA, -1.);
  }

  @Test
  public void testSensitivities() {
    final double tmax = DATA.lastKey();
    double t;
    double[] sensitivity, fdSensitivity;
    for (int i = 0; i < 100; i++) {
      t = tmax * RANDOM.nextDouble();
      sensitivity = INTERPOLATOR.getNodeSensitivitiesForValue(DATA, t);
      fdSensitivity = INTERPOLATOR.getNodeSensitivitiesForValue(DATA, t, true);
      for (int j = 0; j < sensitivity.length; j++) {
        assertEquals(fdSensitivity[j], sensitivity[j], EPS);
      }
    }
  }

  @Test
  public void testEdgeCase() {
    final double tmax = DATA.lastKey();
    final double[] sensitivity = INTERPOLATOR.getNodeSensitivitiesForValue(DATA, tmax);
    for (int j = 0; j < sensitivity.length - 1; j++) {
      assertEquals(0, sensitivity[j], EPS);
    }
    assertEquals(1.0, sensitivity[sensitivity.length - 1], EPS);
  }

}


text:
require 'openssl'
require 'yaml'

#
# We need this to be able to SSH encrypt larger messages. Since SSH encryption suffers from not being able to
# encrypt larger sets of data. Inspired by: http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/
#

module DTK
  class SSHCipher

    def self.decrypt_sensitive(encrypted_data, encrypted_key, encrypted_iv)
      if encrypted_data
        private_key = OpenSSL::PKey::RSA.new(File.read(R8::Config[:arbiter][:ssh][:remote][:private_key]),'')
        cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
        cipher.decrypt
        cipher.key = private_key.private_decrypt(encrypted_key)
        cipher.iv = private_key.private_decrypt(encrypted_iv)

        decrypted_data = cipher.update(encrypted_data)
        decrypted_data << cipher.final

        YAML.load(decrypted_data)
      else
        ''
      end
    end

    private

    def self.encrypt_sensitive(message)
      plain_data = message.to_yaml
      if !plain_data.empty?
        public_key = OpenSSL::PKey::RSA.new(File.read(R8::Config[:arbiter][:ssh][:remote][:private_key]),'').public_key
        cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
        cipher.encrypt
        cipher.key = random_key = cipher.random_key
        cipher.iv = random_iv = cipher.random_iv

        encrypted_data = cipher.update(plain_data)
        encrypted_data << cipher.final

        encrypted_key =  public_key.public_encrypt(random_key)
        encrypted_iv = public_key.public_encrypt(random_iv)

        [encrypted_data, encrypted_key, encrypted_iv]
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="KinematicBody2D" inherits="PhysicsBody2D" category="Core" version="3.0-alpha">
	<brief_description>
		Kinematic body 2D node.
	</brief_description>
	<description>
		Kinematic bodies are special types of bodies that are meant to be user-controlled. They are not affected by physics at all (to other types of bodies, such a character or a rigid body, these are the same as a static body). They have however, two main uses:
		Simulated Motion: When these bodies are moved manually, either from code or from an AnimationPlayer (with process mode set to fixed), the physics will automatically compute an estimate of their linear and angular velocity. This makes them very useful for moving platforms or other AnimationPlayer-controlled objects (like a door, a bridge that opens, etc).
		Kinematic Characters: KinematicBody2D also has an API for moving objects (the [method move_and_collide] and [method move_and_slide] methods) while performing collision tests. This makes them really useful to implement characters that collide against a world, but that don't require advanced physics.
	</description>
	<tutorials>
	</tutorials>
	<demos>
	</demos>
	<methods>
		<method name="get_floor_velocity" qualifiers="const">
			<return type="Vector2">
			</return>
			<description>
				Returns the velocity of the floor. Only updates when calling [method move_and_slide].
			</description>
		</method>
		<method name="get_safe_margin" qualifiers="const">
			<return type="float">
			</return>
			<description>
			</description>
		</method>
		<method name="get_slide_collision">
			<return type="KinematicCollision2D">
			</return>
			<argument index="0" name="slide_idx" type="int">
			</argument>
			<description>
				Returns a [KinematicCollision2D], which contains information about a collision that occured during the last [method move_and_slide] call. Since the body can collide several times in a single call to [method move_and_slide], you must specify the index of the collision in the range 0 to ([method get_slide_count]()-1).
			</description>
		</method>
		<method name="get_slide_count" qualifiers="const">
			<return type="int">
			</return>
			<description>
				Returns the number of times the body collided and changed direction during the last call to [method move_and_slide].
			</description>
		</method>
		<method name="is_on_ceiling" qualifiers="const">
			<return type="bool">
			</return>
			<description>
				Returns [code]true[/code] if the body is on the ceiling. Only updates when calling [method move_and_slide].
			</description>
		</method>
		<method name="is_on_floor" qualifiers="const">
			<return type="bool">
			</return>
			<description>
				Returns [code]true[/code] if the body is on the floor. Only updates when calling [method move_and_slide].
			</description>
		</method>
		<method name="is_on_wall" qualifiers="const">
			<return type="bool">
			</return>
			<description>
				Returns [code]true[/code] if the body is on a wall. Only updates when calling [method move_and_slide].
			</description>
		</method>
		<method name="move_and_collide">
			<return type="KinematicCollision2D">
			</return>
			<argument index="0" name="rel_vec" type="Vector2">
			</argument>
			<description>
				Moves the body along the vector [code]rel_vec[/code]. The body will stop if it collides. Returns a [KinematicCollision2D], which contains information about the collision.
			</description>
		</method>
		<method name="move_and_slide">
			<return type="Vector2">
			</return>
			<argument index="0" name="linear_velocity" type="Vector2">
			</argument>
			<argument index="1" name="floor_normal" type="Vector2" default="Vector2( 0, 0 )">
			</argument>
			<argument index="2" name="slope_stop_min_velocity" type="float" default="5">
			</argument>
			<argument index="3" name="max_bounces" type="int" default="4">
			</argument>
			<argument index="4" name="floor_max_angle" type="float" default="0.785398">
			</argument>
			<description>
				Moves the body along a vector. If the body collides with another, it will slide along the other body rather than stop immediately. If the other body is a [code]KinematicBody2D[/code] or [RigidBody2D], it will also be affected by the motion of the other body. You can use this to make moving or rotating platforms, or to make nodes push other nodes.
				[code]linear_velocity[/code] is a value in pixels per second. Unlike in for example [method move_and_collide], you should [i]not[/i] multiply it with [code]delta[/code] — this is done by the method.
				[code]floor_normal[/code] is the up direction, used to determine what is a wall and what is a floor or a ceiling. If set to the default value of [code]Vector2(0, 0)[/code], everything is considered a wall. This is useful for topdown games.
				If the body is standing on a slope and the horizontal speed (relative to the floor's speed) goes below [code]slope_stop_min_velocity[/code], the body will stop completely. This prevents the body from sliding down slopes when you include gravity in [code]linear_velocity[/code]. When set to lower values, the body will not be able to stand still on steep slopes.
				If the body collides, it will change direction a maximum of [code]max_bounces[/code] times before it stops.
				[code]floor_max_angle[/code] is the maximum angle (in radians) where a slope is still considered a floor (or a ceiling), rather than a wall. The default value equals 45 degrees.
				Returns the movement that remained when the body stopped. To get more detailed information about collisions that occured, use [method get_slide_collision].
			</description>
		</method>
		<method name="set_safe_margin">
			<return type="void">
			</return>
			<argument index="0" name="pixels" type="float">
			</argument>
			<description>
			</description>
		</method>
		<method name="test_move">
			<return type="bool">
			</return>
			<argument index="0" name="from" type="Transform2D">
			</argument>
			<argument index="1" name="rel_vec" type="Vector2">
			</argument>
			<description>
				Checks for collisions without moving the body. Virtually sets the node's position, scale and rotation to that of the given [Transform2D], then tries to move the body along the vector [code]rel_vec[/code]. Returns [code]true[/code] if a collision would occur.
			</description>
		</method>
	</methods>
	<members>
		<member name="collision/safe_margin" type="float" setter="set_safe_margin" getter="get_safe_margin">
			If the body is at least this close to another body, this body will consider them to be colliding.
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
XYplotter.
===============================

Drawing graphic images on paper.

Can be used as typographic builder or Bezier's curves builder.

---
### Requirements

  * Python 3.4+
  * Pillow
  * numpy

### Installation

```bash
git clone https://github.com/Alexponomarev7/plotter
cd XYplotter
python3 setup.py install
Add cleaner.py to your crontab
```

---
### Usage
To be written later.

**Only UTF-8 encoding is supported.**

---
### Corpus structure

To be written later.

---
### Texts similarities analysis

To be written later.

---


text:
import moment from "moment"

import { saleStatus } from "./helpers"

const dAdd = (date: number, amount: number, type: "day" | "days") =>
  moment(date).add(amount, type).toISOString()
const dSub = (date: number, amount: number, type: "day" | "days") =>
  moment(date).subtract(amount, type).toISOString()

describe(saleStatus, () => {
  it("returns the right sale status", () => {
    const now = Date.now()
    expect(saleStatus(dAdd(now, 1, "day"), dAdd(now, 2, "days"), dAdd(now, 1, "day"))).toBe(
      "notYetOpen"
    )
    expect(saleStatus(dAdd(now, 1, "day"), dAdd(now, 2, "days"), null)).toBe("notYetOpen")
    expect(saleStatus(dSub(now, 1, "day"), dAdd(now, 2, "days"), dAdd(now, 1, "day"))).toBe(
      "active"
    )
    expect(saleStatus(dSub(now, 1, "day"), dAdd(now, 2, "days"), null)).toBe("active")
    expect(saleStatus(dSub(now, 3, "days"), dAdd(now, 2, "days"), dSub(now, 1, "day"))).toBe(
      "closed"
    )
    expect(saleStatus(dSub(now, 3, "days"), dSub(now, 2, "days"), null)).toBe("closed")
  })
})


text:
from unittest import main, TestCase
from json import loads
from functools import partial
from os.path import join, exists, isfile
from os import close, remove
from shutil import rmtree
from tempfile import mkstemp, mkdtemp
from json import dumps

from tornado.web import HTTPError
import pandas as pd
from biom import example_table as et
from biom.util import biom_open

from qiita_db.handlers.tests.oauthbase import OauthTestingBase
import qiita_db as qdb
from qiita_db.handlers.artifact import _get_artifact

class UtilTests(TestCase):
    def test_get_artifact(self):
        obs = _get_artifact(1)
        exp = qdb.artifact.Artifact(1)
        self.assertEqual(obs, exp)

        # It does not exist
        with self.assertRaises(HTTPError):
            _get_artifact(100)

class ArtifactHandlerTests(OauthTestingBase):
    def setUp(self):
        super(ArtifactHandlerTests, self).setUp()

        self._clean_up_files = []

    def tearDown(self):
        super(ArtifactHandlerTests, self).tearDown()
        for fp in self._clean_up_files:
            if exists(fp):
                if isfile(fp):
                    remove(fp)
                else:
                    rmtree(fp)

    def test_get_artifact_does_not_exist(self):
        obs = self.get('/qiita_db/artifacts/100/', headers=self.header)
        self.assertEqual(obs.code, 404)

    def test_get_no_header(self):
        obs = self.get('/qiita_db/artifacts/100/')
        self.assertEqual(obs.code, 400)

    def test_get_artifact(self):
        obs = self.get('/qiita_db/artifacts/1/', headers=self.header)
        self.assertEqual(obs.code, 200)
        db_test_raw_dir = qdb.util.get_mountpoint('raw_data')[0][1]
        path_builder = partial(join, db_test_raw_dir)
        exp_fps = {
            "raw_forward_seqs":
                [path_builder('1_s_G1_L001_sequences.fastq.gz')],
            "raw_barcodes":
                [path_builder('1_s_G1_L001_sequences_barcodes.fastq.gz')]}
        exp = {
            'name': 'Raw data 1',
            'timestamp': '2012-10-01 09:30:27',
            'visibility': 'private',
            'type': 'FASTQ',
            'data_type': '18S',
            'can_be_submitted_to_ebi': False,
            'ebi_run_accessions': None,
            'can_be_submitted_to_vamps': False,
            'is_submitted_to_vamps': None,
            'prep_information': [1],
            'study': 1,
            'analysis': None,
            'processing_parameters': None,
            'files': exp_fps}
        self.assertEqual(loads(obs.body), exp)

        obs = self.get('/qiita_db/artifacts/9/', headers=self.header)
        self.assertEqual(obs.code, 200)
        db_test_raw_dir = qdb.util.get_mountpoint('analysis')[0][1]
        path_builder = partial(join, db_test_raw_dir)
        exp_fps = {"biom": [path_builder('1_analysis_18S.biom')]}
        exp = {
            'name': 'noname',
            'visibility': 'sandbox',
            'type': 'BIOM',
            'data_type': '18S',
            'can_be_submitted_to_ebi': False,
            'ebi_run_accessions': None,
            'can_be_submitted_to_vamps': False,
            'is_submitted_to_vamps': None,
            'prep_information': [],
            'study': None,
            'analysis': 1,
            'processing_parameters': {'biom_table': '8', 'depth': '9000',
                                      'subsample_multinomial': 'False'},
            'files': exp_fps}
        obs = loads(obs.body)
        # The timestamp is genreated at patch time, so we can't check for it
        del obs['timestamp']
        self.assertEqual(obs, exp)

    def test_patch(self):
        fd, html_fp = mkstemp(suffix=".html")
        close(fd)
        self._clean_up_files.append(html_fp)
        # correct argument with a single HTML
        arguments = {'op': 'add', 'path': '/html_summary/',
                     'value': html_fp}
        artifact = qdb.artifact.Artifact(1)
        self.assertIsNone(artifact.html_summary_fp)
        obs = self.patch('/qiita_db/artifacts/1/',
                         headers=self.header,
                         data=arguments)
        self.assertEqual(obs.code, 200)
        self.assertIsNotNone(artifact.html_summary_fp)

        # Correct argument with an HMTL and a directory
        fd, html_fp = mkstemp(suffix=".html")
        close(fd)
        self._clean_up_files.append(html_fp)
        html_dir = mkdtemp()
        self._clean_up_files.append(html_dir)
        arguments = {'op': 'add', 'path': '/html_summary/',
                     'value': dumps({'html': html_fp, 'dir': html_dir})}
        obs = self.patch('/qiita_db/artifacts/1/',
                         headers=self.header,
                         data=arguments)
        self.assertEqual(obs.code, 200)
        self.assertIsNotNone(artifact.html_summary_fp)
        html_dir = [fp for _, fp, fp_type in artifact.filepaths
                    if fp_type == 'html_summary_dir']
        self.assertEqual(len(html_dir), 1)

        # Wrong operation
        arguments = {'op': 'wrong', 'path': '/html_summary/',
                     'value': html_fp}
        obs = self.patch('/qiita_db/artifacts/1/',
                         headers=self.header,
                         data=arguments)
        self.assertEqual(obs.code, 400)
        self.assertEqual(obs.body, 'Operation "wrong" not supported. Current '
                                   'supported operations: add')

        # Wrong path parameter
        arguments = {'op': 'add', 'path': '/wrong/',
                     'value': html_fp}
        obs = self.patch('/qiita_db/artifacts/1/',
                         headers=self.header,
                         data=arguments)
        self.assertEqual(obs.code, 400)
        self.assertEqual(obs.body, 'Incorrect path parameter value')

        # Wrong value parameter
        arguments = {'op': 'add', 'path': '/html_summary/',
                     'value': html_fp}
        obs = self.patch('/qiita_db/artifacts/1/',
                         headers=self.header,
                         data=arguments)
        self.assertEqual(obs.code, 500)
        self.assertIn('No such file or directory', obs.body)

class ArtifactAPItestHandlerTests(OauthTestingBase):
    def setUp(self):
        super(ArtifactAPItestHandlerTests, self).setUp()

        metadata_dict = {
            'SKB8.640193': {'center_name': 'ANL',
                            'primer': 'GTGCCAGCMGCCGCGGTAA',
                            'barcode': 'GTCCGCAAGTTA',
                            'run_prefix': "s_G1_L001_sequences",
                            'platform': 'ILLUMINA',
                            'instrument_model': 'Illumina MiSeq',
                            'library_construction_protocol': 'AAAA',
                            'experiment_design_description': 'BBBB'}}
        metadata = pd.DataFrame.from_dict(metadata_dict, orient='index')
        self.prep_template = \
            qdb.metadata_template.prep_template.PrepTemplate.create(
                metadata, qdb.study.Study(1), "16S")

        self._clean_up_files = []

    def tearDown(self):
        super(ArtifactAPItestHandlerTests, self).tearDown()

        for f in self._clean_up_files:
            if exists(f):
                remove(f)

    def test_post(self):
        fd, fp1 = mkstemp(suffix='_seqs.fastq')
        close(fd)
        self._clean_up_files.append(fp1)
        with open(fp1, 'w') as f:
            f.write("@HWI-ST753:189:D1385ACXX:1:1101:1214:1906 1:N:0:\n"
                    "NACGTAGGGTGCAAGCGTTGTCCGGAATNA\n"
                    "+\n"
                    "#1=DDFFFHHHHHJJJJJJJJJJJJGII#0\n")

        fd, fp2 = mkstemp(suffix='_barcodes.fastq')
        close(fd)
        self._clean_up_files.append(fp2)
        with open(fp2, 'w') as f:
            f.write("@HWI-ST753:189:D1385ACXX:1:1101:1214:1906 2:N:0:\n"
                    "NNNCNNNNNNNNN\n"
                    "+\n"
                    "#############\n")

        data = {'filepaths': dumps([(fp1, 'raw_forward_seqs'),
                                    (fp2, 'raw_barcodes')]),
                'type': "FASTQ",
                'name': "New test artifact",
                'prep': self.prep_template.id}
        obs = self.post('/apitest/artifact/', headers=self.header, data=data)
        self.assertEqual(obs.code, 200)
        obs = loads(obs.body)
        self.assertEqual(obs.keys(), ['artifact'])

        a = qdb.artifact.Artifact(obs['artifact'])
        self._clean_up_files.extend([fp for _, fp, _ in a.filepaths])
        self.assertEqual(a.name, "New test artifact")

    def test_post_analysis(self):
        fd, fp = mkstemp(suffix='_table.biom')
        close(fd)
        with biom_open(fp, 'w') as f:
            et.to_hdf5(f, "test")
        self._clean_up_files.append(fp)

        data = {'filepaths': dumps([(fp, 'biom')]),
                'type': "BIOM",
                'name': "New biom artifact",
                'analysis': 1,
                'data_type': '16S'}
        obs = self.post('/apitest/artifact/', headers=self.header, data=data)
        self.assertEqual(obs.code, 200)
        obs = loads(obs.body)
        self.assertEqual(obs.keys(), ['artifact'])

        a = qdb.artifact.Artifact(obs['artifact'])
        self._clean_up_files.extend([afp for _, afp, _ in a.filepaths])
        self.assertEqual(a.name, "New biom artifact")

    def test_post_error(self):
        data = {'filepaths': dumps([('Do not exist', 'raw_forward_seqs')]),
                'type': "FASTQ",
                'name': "New test artifact",
                'prep': 1}
        obs = self.post('/apitest/artifact/', headers=self.header, data=data)
        self.assertEqual(obs.code, 500)
        self.assertIn("Prep template 1 already has an artifact associated",
                      obs.body)

class ArtifactTypeHandlerTests(OauthTestingBase):
    def test_post_no_header(self):
        obs = self.post('/qiita_db/artifacts/types/', data={})
        self.assertEqual(obs.code, 400)

    def test_post(self):
        data = {'type_name': 'new_type',
                'description': 'some_description',
                'can_be_submitted_to_ebi': False,
                'can_be_submitted_to_vamps': False,
                'filepath_types': dumps([("log", False),
                                         ("raw_forward_seqs", True)])}
        obs = self.post('/qiita_db/artifacts/types/', headers=self.header,
                        data=data)
        self.assertEqual(obs.code, 200)
        self.assertIn(['new_type', 'some_description'],
                      qdb.artifact.Artifact.types())

        obs = self.post('/qiita_db/artifacts/types/', headers=self.header,
                        data=data)
        self.assertEqual(obs.code, 200)

if __name__ == '__main__':
    main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

    public partial class OgrenciReport : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

            SqlCommand berky = new SqlCommand("select * from Grade where  UseName='" + Session["UseName"] + "'", conn);
            conn.Open();
            if (Session["UseName"] != null)
            {
                Label1.Text = "Welcome  " + Session["UseName"].ToString() +",";
            }

            string username;
            username = Session["UseName"].ToString();
            string str;
            str = "select * from Grade where  UseName='" + Session["UseName"] + "'";
            if (!(Page.IsPostBack))
            {

                dv = new DataView();
                GridView1.DataSource = ds;
                ds = new DataSet();
                GridView1.DataBind();
            }
        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            Session.Remove("UseName");
            Response.Redirect("Login.aspx");
        }

        public DataView dv { get; set; }

        public DataSet ds { get; set; }
        protected void Button3_Click(object sender, EventArgs e)
        {

        }
        protected void Button4_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default3.aspx");
        }

        protected void SqlDataSource1_Load(object sender, EventArgs e)
        {
            string value;
            value = Session["UseName"].ToString();
            SqlDataSource1.SelectCommand = "SELECT DersAdı, ogrencinot, GecerNot, Ogrenci, Ogretmen, Durumu, UseName FROM Grade WHERE (UseName = '" + value + "')";

        }
}


text:
require 'spec_helper'

describe Apns::Persistent do
  it 'has a version number' do
    expect(Apns::Persistent::VERSION).not_to be nil
  end
end


text:
import {TwingSandboxSecurityError} from "./security-error";
import {TwingSource} from "../source";

export class TwingSandboxSecurityNotAllowedFunctionError extends TwingSandboxSecurityError {
    private readonly functionName: string;

    constructor(message: string, functionName: string, lineno: number = -1, source: TwingSource = null) {
        super(message, lineno, source);
        this.functionName = functionName;
        this.name = 'TwingSandboxSecurityNotAllowedFunctionError';
    }

    getFunctionName() {
        return this.functionName;
    }
}