text:
from __future__ import division

import collections
import math
import cairocffi
import xcffib.xproto

from . import pangocffi
from . import utils

class TextLayout(object):
    def __init__(self, drawer, text, colour, font_family, font_size,
                 font_shadow, wrap=True, markup=False):
        self.drawer, self.colour = drawer, colour
        layout = drawer.ctx.create_layout()
        layout.set_alignment(pangocffi.ALIGN_CENTER)
        if not wrap:  # pango wraps by default
            layout.set_ellipsize(pangocffi.ELLIPSIZE_END)
        desc = pangocffi.FontDescription.from_string(font_family)
        desc.set_absolute_size(pangocffi.units_from_double(font_size))
        layout.set_font_description(desc)
        self.font_shadow = font_shadow
        self.layout = layout
        self.markup = markup
        self.text = text
        self._width = None

    def finalize(self):
        self.layout.finalize()

    @property
    def text(self):
        return self.layout.get_text()

    @text.setter
    def text(self, value):
        if self.markup:
            # pangocffi doesn't like None here, so we use "".
            if value is None:
                value = ''
            attrlist, value, accel_char = pangocffi.parse_markup(value)
            self.layout.set_attributes(attrlist)
        return self.layout.set_text(utils.scrub_to_utf8(value))

    @property
    def width(self):
        if self._width is not None:
            return self._width
        else:
            return self.layout.get_pixel_size()[0]

    @width.setter
    def width(self, value):
        self._width = value
        self.layout.set_width(pangocffi.units_from_double(value))

    @width.deleter
    def width(self):
        self._width = None
        self.layout.set_width(-1)

    @property
    def height(self):
        return self.layout.get_pixel_size()[1]

    def fontdescription(self):
        return self.layout.get_font_description()

    @property
    def font_family(self):
        d = self.fontdescription()
        return d.get_family()

    @font_family.setter
    def font_family(self, font):
        d = self.fontdescription()
        d.set_family(font)
        self.layout.set_font_description(d)

    @property
    def font_size(self):
        d = self.fontdescription()
        return d.get_size()

    @font_size.setter
    def font_size(self, size):
        d = self.fontdescription()
        d.set_size(size)
        d.set_absolute_size(pangocffi.units_from_double(size))
        self.layout.set_font_description(d)

    def draw(self, x, y):
        if self.font_shadow is not None:
            self.drawer.set_source_rgb(self.font_shadow)
            self.drawer.ctx.move_to(x + 1, y + 1)
            self.drawer.ctx.show_layout(self.layout)

        self.drawer.set_source_rgb(self.colour)
        self.drawer.ctx.move_to(x, y)
        self.drawer.ctx.show_layout(self.layout)

    def framed(self, border_width, border_color, pad_x, pad_y,
               highlight_color=None, line_thickness=None):
        return TextFrame(self, border_width, border_color, pad_x, pad_y,
                         highlight_color, line_thickness)

class TextFrame(object):
    def __init__(self, layout, border_width, border_color, pad_x, pad_y,
                 highlight_color, line_thickness):
        self.layout = layout
        self.border_width = border_width
        self.border_color = border_color
        self.drawer = self.layout.drawer
        self.highlight_color = highlight_color
        self.line_thickness = line_thickness

        if isinstance(pad_x, collections.Iterable):
            self.pad_left = pad_x[0]
            self.pad_right = pad_x[1]
        else:
            self.pad_left = self.pad_right = pad_x

        if isinstance(pad_y, collections.Iterable):
            self.pad_top = pad_y[0]
            self.pad_bottom = pad_y[1]
        else:
            self.pad_top = self.pad_bottom = pad_y

    def draw(self, x, y, bar_height=None, rounded=True, fill=False,
             line=False):
        self.drawer.set_source_rgb(self.border_color)
        opts = [
            x, y,
            self.layout.width + self.pad_left + self.pad_right,
            self.layout.height + self.pad_top + self.pad_bottom,
            self.border_width
        ]
        if line:
            if not bar_height:
                bar_height = self.layout.height + self.pad_top + self.pad_bottom
            highlight_opts = [
                x, 0,
                self.layout.width + self.pad_left + self.pad_right,
                bar_height,
                self.border_width
            ]
            self.drawer.set_source_rgb(self.highlight_color)
            self.drawer.fillrect(*highlight_opts)

            lineopts = [
                x,
                bar_height - self.line_thickness,
                self.layout.width + self.pad_left + self.pad_right,
                self.line_thickness,
                self.border_width
            ]

            self.drawer.set_source_rgb(self.border_color)
            self.drawer.fillrect(*lineopts)
        elif fill:
            if rounded:
                self.drawer.rounded_fillrect(*opts)
            else:
                self.drawer.fillrect(*opts)
        else:
            if rounded:
                self.drawer.rounded_rectangle(*opts)
            else:
                self.drawer.rectangle(*opts)
        self.drawer.ctx.stroke()
        self.layout.draw(
            x + self.pad_left,
            y + self.pad_top
        )

    def draw_fill(self, x, y, rounded=True):
        self.draw(x, y, rounded, fill=True)

    def draw_line(self, x, y, bar_height, rounded=False):
        self.draw(x, y, bar_height, rounded, line=True)

    @property
    def height(self):
        return self.layout.height + self.pad_top + self.pad_bottom

    @property
    def width(self):
        return self.layout.width + self.pad_left + self.pad_right

class Drawer(object):
    """
        A helper class for drawing and text layout.

        We have a drawer object for each widget in the bar. The underlying
        surface is a pixmap with the same size as the bar itself. We draw to
        the pixmap starting at offset 0, 0, and when the time comes to display
        to the window, we copy the appropriate portion of the pixmap onto the
        window.
    """
    def __init__(self, qtile, wid, width, height):
        self.qtile = qtile
        self.wid, self.width, self.height = wid, width, height

        self.pixmap = self.qtile.conn.conn.generate_id()
        self.gc = self.qtile.conn.conn.generate_id()

        self.qtile.conn.conn.core.CreatePixmap(
            self.qtile.conn.default_screen.root_depth,
            self.pixmap,
            self.wid,
            self.width,
            self.height
        )
        self.qtile.conn.conn.core.CreateGC(
            self.gc,
            self.wid,
            xcffib.xproto.GC.Foreground | xcffib.xproto.GC.Background,
            [
                self.qtile.conn.default_screen.black_pixel,
                self.qtile.conn.default_screen.white_pixel
            ]
        )
        self.surface = cairocffi.XCBSurface(
            qtile.conn.conn,
            self.pixmap,
            self.find_root_visual(),
            self.width,
            self.height,
        )
        self.ctx = self.new_ctx()
        self.clear((0, 0, 1))

    def finalize(self):
        self.qtile.conn.conn.core.FreeGC(self.gc)
        self.qtile.conn.conn.core.FreePixmap(self.pixmap)
        self.ctx = None
        self.surface = None

    def _rounded_rect(self, x, y, width, height, linewidth):
        aspect = 1.0
        corner_radius = height / 10.0
        radius = corner_radius / aspect
        degrees = math.pi / 180.0

        self.ctx.new_sub_path()

        delta = radius + linewidth / 2
        self.ctx.arc(x + width - delta, y + delta, radius,
                     -90 * degrees, 0 * degrees)
        self.ctx.arc(x + width - delta, y + height - delta,
                     radius, 0 * degrees, 90 * degrees)
        self.ctx.arc(x + delta, y + height - delta, radius,
                     90 * degrees, 180 * degrees)
        self.ctx.arc(x + delta, y + delta, radius,
                     180 * degrees, 270 * degrees)
        self.ctx.close_path()

    def rounded_rectangle(self, x, y, width, height, linewidth):
        self._rounded_rect(x, y, width, height, linewidth)
        self.ctx.set_line_width(linewidth)
        self.ctx.stroke()

    def rounded_fillrect(self, x, y, width, height, linewidth):
        self._rounded_rect(x, y, width, height, linewidth)
        self.ctx.fill()

    def rectangle(self, x, y, width, height, linewidth=2):
        self.ctx.set_line_width(linewidth)
        self.ctx.rectangle(x, y, width, height)
        self.ctx.stroke()

    def fillrect(self, x, y, width, height, linewidth=2):
        self.ctx.set_line_width(linewidth)
        self.ctx.rectangle(x, y, width, height)
        self.ctx.fill()
        self.ctx.stroke()

    def draw(self, offsetx=0, offsety=0, width=None, height=None):
        """
            offsetx: the X offset to start drawing at.
            offsety: the Y offset to start drawing at.
            width: the X portion of the canvas to draw at the starting point.
            height: the Y portion of the canvas to draw at the starting point.
        """
        self.qtile.conn.conn.core.CopyArea(
            self.pixmap,
            self.wid,
            self.gc,
            0, 0,  # srcx, srcy
            offsetx, offsety,  # dstx, dsty
            self.width if width is None else width,
            self.height if height is None else height
        )

    def find_root_visual(self):
        for i in self.qtile.conn.default_screen.allowed_depths:
            for v in i.visuals:
                if v.visual_id == self.qtile.conn.default_screen.root_visual:
                    return v

    def new_ctx(self):
        return pangocffi.CairoContext(cairocffi.Context(self.surface))

    def set_source_rgb(self, colour):
        if type(colour) == list:
            if len(colour) == 0:
                # defaults to black
                self.ctx.set_source_rgba(*utils.rgb("#000000"))
            elif len(colour) == 1:
                self.ctx.set_source_rgba(*utils.rgb(colour[0]))
            else:
                linear = cairocffi.LinearGradient(0.0, 0.0, 0.0, self.height)
                step_size = 1.0 / (len(colour) - 1)
                step = 0.0
                for c in colour:
                    rgb_col = utils.rgb(c)
                    if len(rgb_col) < 4:
                        rgb_col[3] = 1
                    linear.add_color_stop_rgba(step, *rgb_col)
                    step += step_size
                self.ctx.set_source(linear)
        else:
            self.ctx.set_source_rgba(*utils.rgb(colour))

    def clear(self, colour):
        self.set_source_rgb(colour)
        self.ctx.rectangle(0, 0, self.width, self.height)
        self.ctx.fill()
        self.ctx.stroke()

    def textlayout(self, text, colour, font_family, font_size, font_shadow,
                   markup=False, **kw):
        """
            Get a text layout.
        """
        return TextLayout(self, text, colour, font_family, font_size,
                          font_shadow, markup=markup, **kw)

    def max_layout_size(self, texts, font_family, font_size):
        sizelayout = self.textlayout(
            "", "ffffff", font_family, font_size, None)
        widths, heights = [], []
        for i in texts:
            sizelayout.text = i
            widths.append(sizelayout.width)
            heights.append(sizelayout.height)
        return max(widths), max(heights)

    # Old text layout functions, to be deprectated.
    def set_font(self, fontface, size, antialias=True):
        self.ctx.select_font_face(fontface)
        self.ctx.set_font_size(size)
        fo = self.ctx.get_font_options()
        fo.set_antialias(cairocffi.ANTIALIAS_SUBPIXEL)

    def text_extents(self, text):
        return self.ctx.text_extents(utils.scrub_to_utf8(text))

    def font_extents(self):
        return self.ctx.font_extents()

    def fit_fontsize(self, heightlimit):
        """
            Try to find a maximum font size that fits any strings within the
            height.
        """
        self.ctx.set_font_size(heightlimit)
        asc, desc, height, _, _ = self.font_extents()
        self.ctx.set_font_size(
            int(heightlimit * heightlimit / height))
        return self.font_extents()

    def fit_text(self, strings, heightlimit):
        """
            Try to find a maximum font size that fits all strings within the
            height.
        """
        self.ctx.set_font_size(heightlimit)
        _, _, _, maxheight, _, _ = self.ctx.text_extents("".join(strings))
        if not maxheight:
            return 0, 0
        self.ctx.set_font_size(
            int(heightlimit * heightlimit / maxheight))
        maxwidth, maxheight = 0, 0
        for i in strings:
            _, _, x, y, _, _ = self.ctx.text_extents(i)
            maxwidth = max(maxwidth, x)
            maxheight = max(maxheight, y)
        return maxwidth, maxheight

    def draw_vbar(self, color, x, y1, y2, linewidth=1):
        self.set_source_rgb(color)
        self.ctx.move_to(x, y1)
        self.ctx.line_to(x, y2)
        self.ctx.set_line_width(linewidth)
        self.ctx.stroke()

    def draw_hbar(self, color, x1, x2, y, linewidth=1):
        self.set_source_rgb(color)
        self.ctx.move_to(x1, y)
        self.ctx.line_to(x2, y)
        self.ctx.set_line_width(linewidth)
        self.ctx.stroke()


text:
This directory contains ops scripts used to manage room changes / update configurations.

## Adding / Removing rooms for booking

1. Create / remove google calendar with admin google account (with doris / viviean)
2. For new calendars, make cal available to public & grant access to gcal service account `calender-api-service@gds-room-booking-calendar.iam.gserviceaccount.com`
3. Run `npm run update:calendar-config` to fetch gcal config, generate updated room booking option config and generate updated bookings view page for deployment.

redpajama_set_name: RedPajamaGithub


text:
package com.taobao.api.internal.parser.json;

import com.taobao.api.ApiException;
import com.taobao.api.TaobaoParser;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.internal.mapping.Converter;

/**
 * 单个JSON对象解释器。
 *
 * @author carver.gu
 * @since 1.0, Apr 11, 2010
 */
public class ObjectJsonParser<T extends TaobaoResponse> implements TaobaoParser<T> {

	private Class<T> clazz;
	private boolean simplify;

	public ObjectJsonParser(Class<T> clazz) {
		this.clazz = clazz;
	}

	public ObjectJsonParser(Class<T> clazz, boolean simplify) {
		this.clazz = clazz;
		this.simplify = simplify;
	}

	public T parse(String rsp) throws ApiException {
		Converter converter;
		if (this.simplify) {
			converter = new SimplifyJsonConverter();
		} else {
			converter = new JsonConverter();
		}
		return converter.toResponse(rsp, clazz);
	}

	public Class<T> getResponseClass() {
		return clazz;
	}

}


text:
  <link rel="stylesheet" href="maven-theme.css">
  <title>AppSecInc. MSI Extensions</title>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

Wix

Extensions

SystemTools

DeleteFile

Public Attributes |
List of all members

Wix::Extensions::SystemTools::DeleteFile Class Reference

Public Attributes

string 	Id

string 	File

YesNoType 	DeleteOnInstall

YesNoType 	DeleteOnUnInstall

YesNoType 	CheckIfExists

Detailed Description

May be nested under Product, Module, Fragment. Deletes a file outside of component rules.

Example:

<Wix ... xmlns:AppSecIncSystemTools="http://schemas.appsecinc.com/wix/SystemToolsExtension">

 <Product ...>

  ...

  <AppSecIncSystemTools:DeleteFile Id="test1" File="[INSTALLLOCATION]OldFile.txt" DeleteOnInstall="yes" CheckIfExists="yes" />

 </Product>

</Wix>

Member Data Documentation

          YesNoType Wix::Extensions::SystemTools::DeleteFile::CheckIfExists

Check whether a file exists before deleting it. If CheckIfExists is "no" and the file doesn't exist, the custom action will fail.

          YesNoType Wix::Extensions::SystemTools::DeleteFile::DeleteOnInstall

Delete a file at install time.

          YesNoType Wix::Extensions::SystemTools::DeleteFile::DeleteOnUnInstall

Delete a file at uninstall time.

          string Wix::Extensions::SystemTools::DeleteFile::File

Name of the file to be deleted.

          string Wix::Extensions::SystemTools::DeleteFile::Id

Identifier for the file deleted operation (primary key).

The documentation for this class was generated from the following file:

src/WixExtensions/SystemToolsExtension/wixext/Xsd/SystemTools.xsd

     © Application Security Inc. - All Rights Reserved

     http://msiext.codeplex.com

  <link href="tabs.css" rel="stylesheet" type="text/css">


text:
from oslo_log import log as logging
from oslo_utils import excutils

from neutron.common import exceptions as n_exc
from neutron.db import ipam_backend_mixin
from neutron.i18n import _LE
from neutron.ipam import exceptions as ipam_exc

LOG = logging.getLogger(__name__)

class IpamPluggableBackend(ipam_backend_mixin.IpamBackendMixin):

    def _get_failed_ips(self, all_ips, success_ips):
        ips_list = (ip_dict['ip_address'] for ip_dict in success_ips)
        return (ip_dict['ip_address'] for ip_dict in all_ips
                if ip_dict['ip_address'] not in ips_list)

    def _ipam_deallocate_ips(self, context, ipam_driver, port, ips,
                             revert_on_fail=True):
        """Deallocate set of ips over IPAM.

        If any single ip deallocation fails, tries to allocate deallocated
        ip addresses with fixed ip request
        """
        deallocated = []

        try:
            for ip in ips:
                try:
                    ipam_subnet = ipam_driver.get_subnet(ip['subnet_id'])
                    ipam_subnet.deallocate(ip['ip_address'])
                    deallocated.append(ip)
                except n_exc.SubnetNotFound:
                    LOG.debug("Subnet was not found on ip deallocation: %s",
                              ip)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.debug("An exception occurred during IP deallocation.")
                if revert_on_fail and deallocated:
                    LOG.debug("Reverting deallocation")
                    self._ipam_allocate_ips(context, ipam_driver, port,
                                            deallocated, revert_on_fail=False)
                elif not revert_on_fail and ips:
                    addresses = ', '.join(self._get_failed_ips(ips,
                                                               deallocated))
                    LOG.error(_LE("IP deallocation failed on "
                                  "external system for %s"), addresses)
        return deallocated

    def _ipam_try_allocate_ip(self, context, ipam_driver, port, ip_dict):
        factory = ipam_driver.get_address_request_factory()
        ip_request = factory.get_request(context, port, ip_dict)
        ipam_subnet = ipam_driver.get_subnet(ip_dict['subnet_id'])
        return ipam_subnet.allocate(ip_request)

    def _ipam_allocate_single_ip(self, context, ipam_driver, port, subnets):
        """Allocates single ip from set of subnets

        Raises n_exc.IpAddressGenerationFailure if allocation failed for
        all subnets.
        """
        for subnet in subnets:
            try:
                return [self._ipam_try_allocate_ip(context, ipam_driver,
                                                   port, subnet),
                        subnet]
            except ipam_exc.IpAddressGenerationFailure:
                continue
        raise n_exc.IpAddressGenerationFailure(
            net_id=port['network_id'])

    def _ipam_allocate_ips(self, context, ipam_driver, port, ips,
                           revert_on_fail=True):
        """Allocate set of ips over IPAM.

        If any single ip allocation fails, tries to deallocate all
        allocated ip addresses.
        """
        allocated = []

        # we need to start with entries that asked for a specific IP in case
        # those IPs happen to be next in the line for allocation for ones that
        # didn't ask for a specific IP
        ips.sort(key=lambda x: 'ip_address' not in x)
        try:
            for ip in ips:
                # By default IP info is dict, used to allocate single ip
                # from single subnet.
                # IP info can be list, used to allocate single ip from
                # multiple subnets (i.e. first successful ip allocation
                # is returned)
                ip_list = [ip] if isinstance(ip, dict) else ip
                ip_address, ip_subnet = self._ipam_allocate_single_ip(
                    context, ipam_driver, port, ip_list)
                allocated.append({'ip_address': ip_address,
                                  'subnet_cidr': ip_subnet['subnet_cidr'],
                                  'subnet_id': ip_subnet['subnet_id']})
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.debug("An exception occurred during IP allocation.")

                if revert_on_fail and allocated:
                    LOG.debug("Reverting allocation")
                    self._ipam_deallocate_ips(context, ipam_driver, port,
                                              allocated, revert_on_fail=False)
                elif not revert_on_fail and ips:
                    addresses = ', '.join(self._get_failed_ips(ips,
                                                               allocated))
                    LOG.error(_LE("IP allocation failed on "
                                  "external system for %s"), addresses)

        return allocated


text:
package com.donpon.model.Order;

import static org.junit.Assert.*;

import java.util.Calendar;
import java.util.GregorianCalendar;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.donpon.model.Coupon.Coupon;
import com.donpon.model.Coupon.CouponImpl;
import com.donpon.model.Person.Person;
import com.donpon.model.Person.PersonImpl;

/**
* Testing Order class to make sure the Order DAO is working as expected
*
* @author Dimitri De Rose
*
*/
//TODO Need to update this class to retrieve information from database
public class OrderImplTest {

	private Order order;
	private Coupon coupon;
	private Person person;

	@Before
	public void setUp() {
		order= new OrderImpl();

		coupon= new CouponImpl();
		coupon.setCouponStartDate(this.createCalendarObject(2015, 3, 12));
		coupon.setCouponExpirationDate(this.createCalendarObject(2015, 4, 15));
		coupon.setCouponNumber("010");

		person= new PersonImpl();
		person.setFirstName("Sally");
		person.setLastName("Peters");
		person.setEmailAddress("sally.peters@amazing.com");
	}

	@After
	public void releaseResources(){
		order= null;
		coupon= null;
		person= null;
	}

	@Test
	public void testSetOrderNumber(){
		StringBuilder orderNumber= new StringBuilder("2102");
		order.setOrderNumber(orderNumber.toString());

		assertEquals(orderNumber.toString(),order.getOrderNumber());
	}

	@Test
	public void testSetConfirmationCode(){
		StringBuilder confirmationCode= new StringBuilder("1DC23");
		order.setConfirmationCode(confirmationCode.toString());

		assertEquals(confirmationCode.toString(), order.getConfirmationCode());
	}

	@Test
	public void testSetCoupon(){
		order.setCoupon(coupon);

		assertEquals(coupon, order.getCoupon());
	}

	@Test
	public void testSetPerson(){
		order.setPerson(person);

		assertEquals(person, order.getPerson());
	}

	@Test
	public void testGetOrderNumber(){
		StringBuilder orderNumber= new StringBuilder("2102");
		order.setOrderNumber(orderNumber.toString());

		assertEquals(orderNumber.toString(),order.getOrderNumber());
	}

	@Test
	public void testGetConfirmationCode(){
		StringBuilder confirmationCode= new StringBuilder("1DC23");
		order.setConfirmationCode(confirmationCode.toString());

		assertEquals(confirmationCode.toString(), order.getConfirmationCode());
	}

	@Test
	public void testGetCoupon(){
		order.setCoupon(coupon);

		assertEquals(coupon, order.getCoupon());
	}

	@Test
	public void testGetPerson(){
		order.setPerson(person);

		assertEquals(person, order.getPerson());
	}

	@Test
	public void testGetId() {
		//TODO create testcase once Graph Database is up and running
	}

	private Calendar createCalendarObject(int year, int month, int dayOfMonth){
		Calendar calendar= new GregorianCalendar(year, month, dayOfMonth);
		return calendar;
	}

}


text:
package tenus

import (
	"github.com/opencontainers/runc/libcontainer/netlink"
)

type NetworkOptions struct {
	IpAddr string
	Gw     string
	Routes []netlink.Route
}


text:
/**
 * Created by schwarzkopfb on 15/8/21.
 */

function arrayEqual(arr1, arr2) {
    if(!Array.isArray(arr1) || !Array.isArray(arr2) || arr1.length !== arr2.length)
        return false

    for(var i = 0, l = arr1.length; i < l; i++)
        if(!~arr2.indexOf(arr1[ i ]))
            return false

    return true
}

exports.arrayEqual = arrayEqual

function indexOfObjectInArray(obj, arr) {
    for(var i = 0, l = arr.length; i < l; i++)
        if(objectEqual(obj, arr[i]))
            return i

    return -1
}

function arrayDeepEqual(arr1, arr2) {
    if(!Array.isArray(arr1) || !Array.isArray(arr2) || arr1.length !== arr2.length)
        return false

    for(var i = 0, l = arr1.length; i < l; i++)
        if(!~indexOfObjectInArray(arr1[ i ], arr2))
            return false

    return true
}

exports.arrayDeepEqual = arrayDeepEqual

function objectEqual(obj1, obj2) {
    if(!(obj1 instanceof Object) || !(obj2 instanceof Object) || Object.keys(obj1).length !== Object.keys(obj2).length)
        return false

    for(var key in obj1)
        if(obj1.hasOwnProperty(key) && obj1[ key ] !== obj2[ key ])
            return false

    return true
}

exports.objectEqual = objectEqual

function objectDeepEqual(obj1, obj2) {
    if(!(obj1 instanceof Object) || !(obj2 instanceof Object) || Object.keys(obj1).length !== Object.keys(obj2).length)
        return false

    for(var key in obj1) {
        if (!obj1.hasOwnProperty(key)) continue

        if(obj1[ key ] instanceof Object) {
            if(!objectDeepEqual(obj1[ key ], obj2[ key ]))
                return false
        }
        else if(obj1[ key ] !== obj2[ key ])
            return false
    }

    return true
}

exports.objectDeepEqual = objectDeepEqual


text:
package org.tricorder.sysd.shell;

import java.io.IOException;
import java.lang.management.ManagementFactory;

public class systemdnotify {

	public String pingWatchdog() {
        String pidStr = ManagementFactory.getRuntimeMXBean().getName();
        pidStr = pidStr.split("@")[0];
        String location = System.getenv().get("FILELOC");
        if (!location.contains("systemd-notify"))
        	location = "systemd-notify";

		try {
			Process process = new ProcessBuilder(location, "MAINPID=" + pidStr, "WATCHDOG=1").start();
		} catch (IOException e) {
			e.printStackTrace();

		}
		return "Notified";
	}

}


text:
export default /* glsl */ `
#extension GL_OES_standard_derivatives : enable
varying vec3 vNormal;
varying vec3 vLight;
varying vec3 vPosition;

vec3 offSpecular(vec3 color) {
  vec3 c = 1.0 - color;
  return 1.0 - c * c;
}

vec4 getShadedColor(vec4 rgba) {

  vec3 color = rgba.xyz;
  vec3 color2 = offSpecular(rgba.xyz);

  vec3 normal = normalize(vNormal);
  vec3 light = normalize(vLight);
  vec3 position = normalize(vPosition);

  // Workaround to avoid gl_FrontFacing. See https://github.com/unconed/mathbox/pull/26
  vec3 pdx = dFdx(vPosition);
  vec3 pdy = dFdy(vPosition);
  bool frontFacting = dot(vNormal, cross(pdx, pdy)) > 0.0;

  float side = frontFacting ? 1.0 : -1.0;
  float cosine  = side * dot(normal, light);
  float diffuse = mix(max(0.0, cosine), .5 + .5 * cosine, .1);

  vec3  halfLight = normalize(light + position);
	float cosineHalf = max(0.0, side * dot(normal, halfLight));
	float specular = pow(cosineHalf, 16.0);

	return vec4(color * (diffuse * .9 + .05) + .25 * color2 * specular, rgba.a);
}
`;


text:
FROM biocontainers/biocontainers:vdebian-buster-backports_cv1
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL    software="pyvcf" \
    base_image="biocontainers/biocontainers:vdebian-buster-backports_cv1" \
    container="pyvcf" \
    about.summary="Variant Call Format (VCF) parser for Python 3" \
    about.home="https://pypi.python.org/pypi/PyVCF" \
    software.version="0.6.8git20170215.476169c-1-deb-py3" \
    upstream.version="0.6.8" \
    version="1" \
    about.copyright="2011-2015, Population Genetics Technologies Ltd, All rights reserved." \
    about.license="BSD-3-clause" \
    about.license_file="/usr/share/doc/pyvcf/copyright" \
    about.tags=""

USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && (apt-get install -t buster-backports -y python3-pyvcf || apt-get install -y python3-pyvcf) && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
Bot. J. Linn. Soc. 71:248. 1976

#### Original name
null

### Remarks
null


text:
namespace Steam.Models.DOTA2
{
    public class PlayerOfficialInfoModel
    {
        public string Name { get; set; }
        public string TeamName { get; set; }
        public string TeamTag { get; set; }
        public string Sponsor { get; set; }
        public uint FantasyRole { get; set; }
    }
}


text:
from mock import patch
import unittest
import urllib2

from weblab.experiment.devices.http import HttpDevice, WlHttpDeviceURLErrorError, WlHttpDeviceHTTPErrorError, WlHttpDeviceError
from test.util.fakeobjects import fakeaddinfourl

class HttpDeviceTestCase(unittest.TestCase):

    @patch('urllib2.urlopen')
    def test_ok_response(self, urlopen):
        urlopen.return_value = fakeaddinfourl('OK')

        device = HttpDevice("localhost", 7779)
        resp = device.send_message("command")
        self.assertEquals('OK', resp)

    @patch('urllib2.urlopen')
    def test_http_error_response(self, urlopen):
        urlopen.side_effect = urllib2.HTTPError('', 401, '', {}, None)

        device = HttpDevice("localhost", 7779)
        self.assertRaises(
            WlHttpDeviceHTTPErrorError,
            device.send_message,
            "command"
        )

    @patch('urllib2.urlopen')
    def test_url_error_response(self, urlopen):
        urlopen.side_effect = urllib2.URLError('error message')

        device = HttpDevice("localhost", 7779)
        self.assertRaises(
            WlHttpDeviceURLErrorError,
            device.send_message,
            "command"
        )

    @patch('urllib2.urlopen')
    def test_general_error_response(self, urlopen):
        urlopen.side_effect = Exception('error message')

        device = HttpDevice("localhost", 7779)
        self.assertRaises(
            WlHttpDeviceError,
            device.send_message,
            "command"
        )

def suite():
    return unittest.makeSuite(HttpDeviceTestCase)

if __name__ == '__main__':
    unittest.main()


text:
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */

#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcSimpleValue.h"
#include "ifcpp/IFC4/include/IfcBinary.h"

// TYPE IfcBinary = BINARY;
IfcBinary::IfcBinary( std::wstring value ) { m_value = value; }
shared_ptr<BuildingObject> IfcBinary::getDeepCopy( BuildingCopyOptions& options )
{
	shared_ptr<IfcBinary> copy_self( new IfcBinary() );
	copy_self->m_value = m_value;
	return copy_self;
}
void IfcBinary::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
	if( is_select_type ) { stream << "IFCBINARY("; }
	stream << "\"" << encodeStepString( m_value ) << "\"";
	if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcBinary::toString() const
{
	return m_value;
}
shared_ptr<IfcBinary> IfcBinary::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
	if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcBinary>(); }
	if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcBinary>(); }
	shared_ptr<IfcBinary> type_object( new IfcBinary() );
	readBinaryString( arg, type_object->m_value );
	return type_object;
}


text:
<?php

require_once 'Component.php';

/**
 * @property string $content This is the content of the message in the invitation
 * @property string $messageType This is the type of the message in the invitation
 */
class Message extends Component {

    private $content;
    private $messageType;

    const SUCCESS = 'success';
    const INFO = 'info';
    const WARNING = 'warning';
    const DANGER = 'danger';
/**
 * This function can create the message content and type that has to be sent to theparticipant
 * @param _construct $content Content for the message in the invitation
 * @param _construct $messageType Type of the message to be sent
 */
    public function __construct($content, $messageType='info') {
        $this->content = $content;
        $this->messageType = $messageType;
    }

    public function build() {
        echo '
messageType . ' alert-dismissible" role="alert">'
        . '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>'
        . $this->content . '
';
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace DecompileMe
{
   public class RecentFile
    {

       public static readonly string DEFAULTCONFIG = AppDomain.CurrentDomain.BaseDirectory + "base.dat";
        #region private
        private static string _ConfigPath = AppDomain.CurrentDomain.BaseDirectory + "\\Setting.xml";
        public static string ConfigPath
        {
            get { return _ConfigPath; }
            set
            {
                _ConfigPath = value;
                _CurrentDataSet = null;
            }
        }
        private static System.Data.DataSet _CurrentDataSet = null;
        private static System.Data.DataSet GetSettingDataSet()
        {
            if (_CurrentDataSet == null)
            {
                string cPath = ConfigPath;
                System.Data.DataSet ds = new System.Data.DataSet();
                if (System.IO.File.Exists(cPath))
                {
                    ds.ReadXml(cPath);
                }
                else
                {
                    System.Data.DataTable dt = new System.Data.DataTable();
                    dt.TableName = "SoftSetting";
                    dt.Columns.Add("DataKeys");
                    dt.Columns.Add("DataValues");
                    ds.Tables.Add(dt);
                    ds.DataSetName = "SystemSetting";
                    ds.WriteXml(cPath);
                }
                _CurrentDataSet = ds;
            }
            return _CurrentDataSet;

        }
        public static string GetSoftConfig(string pKey)
        {
            System.Data.DataSet ds = GetSettingDataSet();
            System.Data.DataRow[] drs = ds.Tables[0].Select("DataKeys='" + pKey + "'");
            if (drs.Length > 0)
            {
                return drs[0]["DataValues"].ToString();
            }
            else
            {
                SetSoftConfig(pKey, "");
            }
            return "";
        }
        public static void SetSoftConfig(string pKey, string pNValue)
        {
            System.Data.DataSet ds = GetSettingDataSet();
            System.Data.DataRow[] drs = ds.Tables[0].Select("DataKeys='" + pKey + "'");
            if (drs.Length > 0)
            {
                if (drs[0]["DataValues"].ToString() == pNValue) return;//值没有发生改变
                else drs[0]["DataValues"] = pNValue;
            }
            else
            {
                System.Data.DataRow dr = ds.Tables[0].NewRow();
                dr["DataKeys"] = pKey;
                dr["DataValues"] = pNValue;
                ds.Tables[0].Rows.Add(dr);
            }
            string cPath = (ConfigPath);
            ds.WriteXml(cPath);
            _CurrentDataSet = null;
        }
        #endregion

        private const string Key_RecentFile = "RecentFile";
        private const int MaxRecentFile = 10;
        /// <summary>
        /// 最近使用过的方案文件的位置
        /// </summary>
        public static string[] GetRecentFile()
        {
            List<string> lst = new List<string>();
            for (int i = 0; i < MaxRecentFile; i++)
            {
                string v = GetSoftConfig(Key_RecentFile + i);
                if (v != string.Empty)
                {
                    lst.Add(v);
                }
            }
            return lst.ToArray();
        }

        /// <summary>
        /// 设置最近使用过的方案文件的位置
        /// </summary>
        public static void SetRecentFile(string[] pValue)
        {
            for (int j = 0; j < pValue.Length; j++)
            {
                if (IsRepeated(pValue, pValue[j],j))
                {
                    pValue[j] = "";
                }
            }
            int i = 0;
            for (; i < pValue.Length&&i<MaxRecentFile; i++)
            {
                SetSoftConfig(Key_RecentFile + i, pValue[i]);
            }
            for (; i < MaxRecentFile; i++)
            {
                SetSoftConfig(Key_RecentFile + i, "");
            }

        }
       /// <summary>
       /// 是否有两个以上
       /// </summary>
       /// <param name="pSrc"></param>
       /// <param name="pValue"></param>
       /// <param name="pCurrentIndex">当前id</param>
       /// <returns></returns>
        private static bool IsRepeated(string[] pSrc, string pValue,int pCurrentIndex)
        {
            for (int i = pCurrentIndex-1; i >= 0; i--)
            {
                if (pSrc[i] == pValue) return true;
            }
            return false;
        }

        public static void UpdateMostRecent(string pValue)
        {
            string[] sall = GetRecentFile();
            string[] smore = new string[sall.Length + 1];
            smore[0] = pValue;
            for (int i = 0; i < sall.Length; i++)
            {
                smore[i + 1] = sall[i];
            }
            SetRecentFile(smore);
        }
        /// <summary>
        /// 设置最近使用过的方案文件的位置
        /// </summary>
        public static void ClearRecentFile()
        {
            for (int i = 0; i < MaxRecentFile; i++)
            {
                SetSoftConfig(Key_RecentFile + i, "");
            }
        }

        private const string Key_NETFrameworkPath = "NETFrameworkPath";
        /// <summary>
        /// .net框架的位置
        /// </summary>
        public static string NETFrameworkPath
        {
            set
            {
                try
                {
                    SetSoftConfig(Key_NETFrameworkPath, value);
                }
                catch { }
            }
            get
            {
                return GetSoftConfig(Key_NETFrameworkPath);
            }
        }
    }
}


text:
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>{% block title %} Randomized Drinking {% endblock %}</title>

  <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
  <link href="{{ url_for('static', filename = 'css/grid.css') }}" rel="stylesheet">

  {% block css %}
  {% endblock %}

  {% block script %}
  {% endblock %}

            Instructions

          {% if current_user.is_authenticated() %}

            Record

          Logout

          {% endif %}

{% block page_head %} {% endblock %}

    {% block content %}
    {% endblock %}

© Annie


text:
require 'qme_ext/quality_report'
require 'qme_ext/manual_exclusion'
require 'hds/measure.rb'


text:
<?php
include("php.php");

////////////////////////////////////
// No where, no limit, no order  //
////////////////////////////////////
$where = " where `public` = 1 and (";
$limit = "";
$order = "";

/////////////////////////
// Set up categories  //
/////////////////////////
if ($usercats != "") {

	if ($where == "") $where = " WHERE ";
	$where .= "`tags` LIKE ";
	$urlstr = htmlentities($usercats, ENT_QUOTES);
	$cats = explode(",", $urlstr);
	foreach($cats as $v) {
		$where .= "\"%$v%\" OR `tags` LIKE ";
	}
	$where = substr($where, 0, -16);
	$where .= ")";
}

if ($where == " where `public` = 1 and (") $where = " where `public` = 1";

if ($_GET["pvt"] == 1 && $where == " where `public` = 1") $where = "";

$query = "SELECT * FROM `features`$where ORDER BY id DESC";
// echo $query;
$result = mysql_query($query) or die("Fail: " . $query);

$arr = recordToArray($result);

////////////////////////////////////////////////////////
// Check if there are individual entries to prepend  //
////////////////////////////////////////////////////////

if ($userinds != "") {
	$indarray = array();
	$where2 = " WHERE ";
	$where2 .= "`id` LIKE ";
	$urlstr = htmlentities($userinds, ENT_QUOTES);
	$inds = explode(",", $urlstr);
	foreach($inds as $k => $v) {

		if ($v != 0) {
			$query2 = "SELECT * FROM `features` WHERE `id` LIKE $v AND `public` = 1 LIMIT 0,1;";
			$result = mysql_query($query2) or die("Fail: " . $query2);
			$temp = recordToArray($result);
			array_pop($temp);
			$tempid = $temp[0]['id'];

			foreach($arr as $kk => $vv) {
				if ($vv['id'] == $tempid) {
					unset($arr[$kk]);
				}
			}
			array_splice($arr, $k, 0, $temp);
		}
	}
}

//////////////////////
// Loop the array  //
//////////////////////
foreach($arr as $k=>$v) {

	//////////////////////////////////////
	// Ignore records without images  //
	//////////////////////////////////////
	if ( $v[story_images] == "" || $v[story_images] == "{}") {
		// Do nothing
	}
	else {
		$newHTML = "";

		$img_json = $arr[$k]['story_images'];
		$img_arr = json_decode($img_json);

		// Remove parent
 tags, split result by paragraph
		$arr[$k]['html'] = str_replace('
', '', trim($arr[$k]['html']));
		$split0 = explode('
', $arr[$k]['html']);

		foreach($split0 as $kk => $vv) {
			if($vv == "") unset($split0[$kk]);
		}
		$split = array_values($split0);

		// Loop each paragraph in the array
		foreach($split as $kk => $vv) {
			$currentpara = $kk + 1;
			$newHTML .= "
";
			// Loop images
			foreach ($img_arr as $kkk => $vvv) {
				// If we're currently in the paragraph for this image..
				if ($vvv->para == $currentpara) {
					$style = " style='";
					foreach ($vvv->style as $kkkk => $vvvv) {
						$style .= $kkkk . ": ". $vvvv . "; ";
					}
					//set image position
					if($vvv->position !=null && $vvv->position == 'center'){
						$style .= "display:block; margin:0 auto 10px;";
					}elseif($vvv->position !=null && $vvv->position == 'right'){
						$style .= "float:right; margin:0 0 10px 10px;";
					}else{
						$style .= "float:left; margin:0 10px 10px 0;";
					}
					//set image size
					if($vvv->width !=null){
						$width = " width='".$vvv->width."'";
					}else{
						$width = "";
					}
					$style .= "'";
					$newHTML .= "src."' alt='alt' ".$width."/>";
				}
			}
			$newHTML .= $vv . "
\n\n";
		}
		$arr[$k]['html'] = $newHTML;
		// echo $newHTML;
	}

	/////////////////////////////////////////
	// Ignore records without pullquotes //
	/////////////////////////////////////////
	if ( $v[pullquotes] == "" || $v[pullquotes] == "{}") {
		// Do nothing
	}
	else {
		$newHTML = "";

		$pq_json = $arr[$k]['pullquotes'];
		$pq_array = json_decode($pq_json);

		// Remove parent
 tags, split result by paragraph
		$arr[$k]['html'] = str_replace('
', '', trim($arr[$k]['html']));
		$split0 = explode('
', $arr[$k]['html']);

		foreach($split0 as $kk => $vv) {
			if($vv == "") unset($split0[$kk]);
		}
		$split = array_values($split0);

		// Loop each paragraph in the array
		foreach($split as $kk => $vv) {
			$currentpara = $kk + 1;
			$newHTML .= "
";
			// Loop images
			foreach ($pq_array as $kkk => $vvv) {
				$thi = $vvv;
				// If we're currently in the paragraph for this image..
				if ($vvv->para == $currentpara) {
					$newHTML .= "".$vvv->quote."";
				}
			}
			$newHTML .= $vv . "
\n\n";
		}
		$arr[$k]['html'] = $newHTML;
		// echo $newHTML;
	}
}

$arr = array_slice($arr, 0, 8);
?>

Go back to full screen

Welcome <?= $first_name?>

Victor of Engineering

We've hand picked some stories and videos that we think you'll like. Let us know what you think. We'll be updating the site frequently, so please bookmark it and come back again soon.

                            Ready to Give

				<?php
					foreach($arr as $key => $story){

						echo '

'.$story[title].'

'.$story[description].'

										'.$story[byline].'
										'.$story[html].'

';
					};
				?>


text:
package internal

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/model/exemplar"
	"github.com/prometheus/prometheus/model/labels"
	"github.com/prometheus/prometheus/model/metadata"
	"github.com/prometheus/prometheus/scrape"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/component/componenttest"
	"go.opentelemetry.io/collector/consumer/consumertest"
	"go.opentelemetry.io/collector/featuregate"
	"go.opentelemetry.io/collector/obsreport"
	"go.opentelemetry.io/collector/pdata/pcommon"
	"go.opentelemetry.io/collector/pdata/pmetric"
)

const (
	startTimestamp      = pcommon.Timestamp(1555366608340000000)
	ts                  = int64(1555366610000)
	interval            = int64(15 * 1000)
	tsNanos             = pcommon.Timestamp(ts * 1e6)
	tsPlusIntervalNanos = pcommon.Timestamp((ts + interval) * 1e6)
)

var (
	target = scrape.NewTarget(
		// processedLabels contain label values after processing (e.g. relabeling)
		labels.FromMap(map[string]string{
			model.InstanceLabel: "localhost:8080",
		}),
		// discoveredLabels contain labels prior to any processing
		labels.FromMap(map[string]string{
			model.AddressLabel: "address:8080",
			model.SchemeLabel:  "http",
		}),
		nil)

	scrapeCtx = scrape.ContextWithMetricMetadataStore(
		scrape.ContextWithTarget(context.Background(), target),
		testMetadataStore(testMetadata))
)

func TestTransactionCommitWithoutAdding(t *testing.T) {
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, consumertest.NewNop(), nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	assert.NoError(t, tr.Commit())
}

func TestTransactionRollbackDoesNothing(t *testing.T) {
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, consumertest.NewNop(), nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	assert.NoError(t, tr.Rollback())
}

func TestTransactionUpdateMetadataDoesNothing(t *testing.T) {
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, consumertest.NewNop(), nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	_, err := tr.UpdateMetadata(0, labels.New(), metadata.Metadata{})
	assert.NoError(t, err)
}

func TestTransactionAppendNoTarget(t *testing.T) {
	badLabels := labels.FromStrings(model.MetricNameLabel, "counter_test")
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, consumertest.NewNop(), nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	_, err := tr.Append(0, badLabels, time.Now().Unix()*1000, 1.0)
	assert.Error(t, err)
}

func TestTransactionAppendNoMetricName(t *testing.T) {
	jobNotFoundLb := labels.FromMap(map[string]string{
		model.InstanceLabel: "localhost:8080",
		model.JobLabel:      "test2",
	})
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, consumertest.NewNop(), nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	_, err := tr.Append(0, jobNotFoundLb, time.Now().Unix()*1000, 1.0)
	assert.ErrorIs(t, err, errMetricNameNotFound)

	assert.ErrorIs(t, tr.Commit(), errNoDataToBuild)
}

func TestTransactionAppendEmptyMetricName(t *testing.T) {
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, consumertest.NewNop(), nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	_, err := tr.Append(0, labels.FromMap(map[string]string{
		model.InstanceLabel:   "localhost:8080",
		model.JobLabel:        "test2",
		model.MetricNameLabel: "",
	}), time.Now().Unix()*1000, 1.0)
	assert.ErrorIs(t, err, errMetricNameNotFound)
}

func TestTransactionAppendResource(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	_, err := tr.Append(0, labels.FromMap(map[string]string{
		model.InstanceLabel:   "localhost:8080",
		model.JobLabel:        "test",
		model.MetricNameLabel: "counter_test",
	}), time.Now().Unix()*1000, 1.0)
	assert.NoError(t, err)
	_, err = tr.Append(0, labels.FromMap(map[string]string{
		model.InstanceLabel:   "localhost:8080",
		model.JobLabel:        "test",
		model.MetricNameLabel: startTimeMetricName,
	}), time.Now().UnixMilli(), 1.0)
	assert.NoError(t, err)
	assert.NoError(t, tr.Commit())
	expectedResource := CreateResource("test", "localhost:8080", labels.FromStrings(model.SchemeLabel, "http"))
	mds := sink.AllMetrics()
	require.Len(t, mds, 1)
	gotResource := mds[0].ResourceMetrics().At(0).Resource()
	require.Equal(t, expectedResource, gotResource)
}

func TestTransactionCommitErrorWhenAdjusterError(t *testing.T) {
	goodLabels := labels.FromMap(map[string]string{
		model.InstanceLabel:   "localhost:8080",
		model.JobLabel:        "test",
		model.MetricNameLabel: "counter_test",
	})
	sink := new(consumertest.MetricsSink)
	adjusterErr := errors.New("adjuster error")
	tr := newTransaction(scrapeCtx, &errorAdjuster{err: adjusterErr}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
	_, err := tr.Append(0, goodLabels, time.Now().Unix()*1000, 1.0)
	assert.NoError(t, err)
	assert.ErrorIs(t, tr.Commit(), adjusterErr)
}

// Ensure that we reject duplicate label keys. See https://github.com/open-telemetry/wg-prometheus/issues/44.
func TestTransactionAppendDuplicateLabels(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	dupLabels := labels.FromStrings(
		model.InstanceLabel, "0.0.0.0:8855",
		model.JobLabel, "test",
		model.MetricNameLabel, "counter_test",
		"a", "1",
		"a", "6",
		"z", "9",
	)

	_, err := tr.Append(0, dupLabels, 1917, 1.0)
	require.Error(t, err)
	assert.Contains(t, err.Error(), `invalid sample: non-unique label names: "a"`)
}

func TestTransactionAppendHistogramNoLe(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	goodLabels := labels.FromStrings(
		model.InstanceLabel, "0.0.0.0:8855",
		model.JobLabel, "test",
		model.MetricNameLabel, "hist_test_bucket",
	)

	_, err := tr.Append(0, goodLabels, 1917, 1.0)
	require.ErrorIs(t, err, errEmptyLeLabel)
}

func TestTransactionAppendSummaryNoQuantile(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	goodLabels := labels.FromStrings(
		model.InstanceLabel, "0.0.0.0:8855",
		model.JobLabel, "test",
		model.MetricNameLabel, "summary_test",
	)

	_, err := tr.Append(0, goodLabels, 1917, 1.0)
	require.ErrorIs(t, err, errEmptyQuantileLabel)
}

func TestAppendExemplarWithNoMetricName(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	labels := labels.FromStrings(
		model.InstanceLabel, "0.0.0.0:8855",
		model.JobLabel, "test",
	)

	_, err := tr.AppendExemplar(0, labels, exemplar.Exemplar{Value: 0})
	assert.Equal(t, errMetricNameNotFound, err)
}

func TestAppendExemplarWithEmptyMetricName(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	labels := labels.FromStrings(
		model.InstanceLabel, "0.0.0.0:8855",
		model.JobLabel, "test",
		model.MetricNameLabel, "",
	)
	_, err := tr.AppendExemplar(0, labels, exemplar.Exemplar{Value: 0})
	assert.Equal(t, errMetricNameNotFound, err)
}

func TestAppendExemplarWithDuplicateLabels(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	labels := labels.FromStrings(
		model.InstanceLabel, "0.0.0.0:8855",
		model.JobLabel, "test",
		model.MetricNameLabel, "",
		"a", "b",
		"a", "c",
	)
	_, err := tr.AppendExemplar(0, labels, exemplar.Exemplar{Value: 0})
	require.Error(t, err)
	assert.Contains(t, err.Error(), `invalid sample: non-unique label names: "a"`)
}

func TestAppendExemplarWithoutAddingMetric(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	labels := labels.FromStrings(
		model.InstanceLabel, "0.0.0.0:8855",
		model.JobLabel, "test",
		model.MetricNameLabel, "counter_test",
		"a", "b",
	)
	_, err := tr.AppendExemplar(0, labels, exemplar.Exemplar{Value: 0})
	assert.NoError(t, err)
}

func TestAppendExemplarWithNoLabels(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	_, err := tr.AppendExemplar(0, nil, exemplar.Exemplar{Value: 0})
	assert.Equal(t, errNoJobInstance, err)
}

func TestAppendExemplarWithEmptyLabelArray(t *testing.T) {
	sink := new(consumertest.MetricsSink)
	tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())

	_, err := tr.AppendExemplar(0, []labels.Label{}, exemplar.Exemplar{Value: 0})
	assert.Equal(t, errNoJobInstance, err)
}

func nopObsRecv(t *testing.T) *obsreport.Receiver {
	obsrecv, err := obsreport.NewReceiver(obsreport.ReceiverSettings{
		ReceiverID:             component.NewID("prometheus"),
		Transport:              transport,
		ReceiverCreateSettings: componenttest.NewNopReceiverCreateSettings(),
	})
	require.NoError(t, err)
	return obsrecv
}

func TestMetricBuilderCounters(t *testing.T) {
	tests := []buildTestData{
		{
			name: "single-item",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("counter_test", 100, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("counter_test")
				sum := m0.SetEmptySum()
				sum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				sum.SetIsMonotonic(true)
				pt0 := sum.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "single-item-with-exemplars",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint(
							"counter_test",
							100,
							[]exemplar.Exemplar{
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: model.MetricNameLabel, Value: "counter_test"}, {Name: model.JobLabel, Value: "job"}, {Name: model.InstanceLabel, Value: "instance"}, {Name: "foo", Value: "bar"}},
								},
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: ""}, {Name: "span_id", Value: ""}},
								},
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: "10a47365b8aa04e08291fab9deca84db6170"}, {Name: "span_id", Value: "719cee4a669fd7d109ff"}},
								},
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: "174137cab66dc880"}, {Name: "span_id", Value: "dfa4597a9d"}},
								},
							},
							"foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("counter_test")
				sum := m0.SetEmptySum()
				sum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				sum.SetIsMonotonic(true)
				pt0 := sum.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				e0 := pt0.Exemplars().AppendEmpty()
				e0.SetTimestamp(timestampFromMs(1663113420863))
				e0.SetDoubleValue(1)
				e0.FilteredAttributes().PutStr(model.MetricNameLabel, "counter_test")
				e0.FilteredAttributes().PutStr(model.JobLabel, "job")
				e0.FilteredAttributes().PutStr(model.InstanceLabel, "instance")
				e0.FilteredAttributes().PutStr("foo", "bar")

				e1 := pt0.Exemplars().AppendEmpty()
				e1.SetTimestamp(timestampFromMs(1663113420863))
				e1.SetDoubleValue(1)
				e1.FilteredAttributes().PutStr("foo", "bar")

				e2 := pt0.Exemplars().AppendEmpty()
				e2.SetTimestamp(timestampFromMs(1663113420863))
				e2.SetDoubleValue(1)
				e2.FilteredAttributes().PutStr("foo", "bar")
				e2.SetTraceID([16]byte{0x10, 0xa4, 0x73, 0x65, 0xb8, 0xaa, 0x04, 0xe0, 0x82, 0x91, 0xfa, 0xb9, 0xde, 0xca, 0x84, 0xdb})
				e2.SetSpanID([8]byte{0x71, 0x9c, 0xee, 0x4a, 0x66, 0x9f, 0xd7, 0xd1})

				e3 := pt0.Exemplars().AppendEmpty()
				e3.SetTimestamp(timestampFromMs(1663113420863))
				e3.SetDoubleValue(1)
				e3.FilteredAttributes().PutStr("foo", "bar")
				e3.SetTraceID([16]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x41, 0x37, 0xca, 0xb6, 0x6d, 0xc8, 0x80})
				e3.SetSpanID([8]byte{0x00, 0x00, 0x00, 0xdf, 0xa4, 0x59, 0x7a, 0x9d})

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "two-items",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("counter_test", 150, nil, "foo", "bar"),
						createDataPoint("counter_test", 25, nil, "foo", "other"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("counter_test")
				sum := m0.SetEmptySum()
				sum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				sum.SetIsMonotonic(true)
				pt0 := sum.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(150.0)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				pt1 := sum.DataPoints().AppendEmpty()
				pt1.SetDoubleValue(25.0)
				pt1.SetStartTimestamp(startTimestamp)
				pt1.SetTimestamp(tsNanos)
				pt1.Attributes().PutStr("foo", "other")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "two-metrics",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("counter_test", 150, nil, "foo", "bar"),
						createDataPoint("counter_test", 25, nil, "foo", "other"),
						createDataPoint("counter_test2", 100, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("counter_test")
				sum0 := m0.SetEmptySum()
				sum0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				sum0.SetIsMonotonic(true)
				pt0 := sum0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(150.0)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				pt1 := sum0.DataPoints().AppendEmpty()
				pt1.SetDoubleValue(25.0)
				pt1.SetStartTimestamp(startTimestamp)
				pt1.SetTimestamp(tsNanos)
				pt1.Attributes().PutStr("foo", "other")

				m1 := mL0.AppendEmpty()
				m1.SetName("counter_test2")
				sum1 := m1.SetEmptySum()
				sum1.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				sum1.SetIsMonotonic(true)
				pt2 := sum1.DataPoints().AppendEmpty()
				pt2.SetDoubleValue(100.0)
				pt2.SetStartTimestamp(startTimestamp)
				pt2.SetTimestamp(tsNanos)
				pt2.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "metrics-with-poor-names",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("poor_name_count", 100, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("poor_name_count")
				sum := m0.SetEmptySum()
				sum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				sum.SetIsMonotonic(true)
				pt0 := sum.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.run(t)
		})
	}
}

func TestMetricBuilderGauges(t *testing.T) {
	tests := []buildTestData{
		{
			name: "one-gauge",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("gauge_test", 100, nil, "foo", "bar"),
					},
				},
				{
					pts: []*testDataPoint{
						createDataPoint("gauge_test", 90, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("gauge_test")
				gauge0 := m0.SetEmptyGauge()
				pt0 := gauge0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(0)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				md1 := pmetric.NewMetrics()
				mL1 := md1.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m1 := mL1.AppendEmpty()
				m1.SetName("gauge_test")
				gauge1 := m1.SetEmptyGauge()
				pt1 := gauge1.DataPoints().AppendEmpty()
				pt1.SetDoubleValue(90.0)
				pt1.SetStartTimestamp(0)
				pt1.SetTimestamp(tsPlusIntervalNanos)
				pt1.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0, md1}
			},
		},
		{
			name: "one-gauge-with-exemplars",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint(
							"gauge_test",
							100,
							[]exemplar.Exemplar{
								{
									Value:  2,
									Ts:     1663350815890,
									Labels: []labels.Label{{Name: model.MetricNameLabel, Value: "counter_test"}, {Name: model.JobLabel, Value: "job"}, {Name: model.InstanceLabel, Value: "instance"}, {Name: "foo", Value: "bar"}},
								},
								{
									Value:  2,
									Ts:     1663350815890,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: ""}, {Name: "span_id", Value: ""}},
								},
								{
									Value:  2,
									Ts:     1663350815890,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: "10a47365b8aa04e08291fab9deca84db6170"}, {Name: "span_id", Value: "719cee4a669fd7d109ff"}},
								},
								{
									Value:  2,
									Ts:     1663350815890,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: "174137cab66dc880"}, {Name: "span_id", Value: "dfa4597a9d"}},
								},
							},
							"foo", "bar"),
					},
				},
				{
					pts: []*testDataPoint{
						createDataPoint("gauge_test", 90, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("gauge_test")
				gauge0 := m0.SetEmptyGauge()
				pt0 := gauge0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(0)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				e0 := pt0.Exemplars().AppendEmpty()
				e0.SetTimestamp(timestampFromMs(1663350815890))
				e0.SetDoubleValue(2)
				e0.FilteredAttributes().PutStr(model.MetricNameLabel, "counter_test")
				e0.FilteredAttributes().PutStr(model.JobLabel, "job")
				e0.FilteredAttributes().PutStr(model.InstanceLabel, "instance")
				e0.FilteredAttributes().PutStr("foo", "bar")

				e1 := pt0.Exemplars().AppendEmpty()
				e1.SetTimestamp(timestampFromMs(1663350815890))
				e1.SetDoubleValue(2)
				e1.FilteredAttributes().PutStr("foo", "bar")

				e2 := pt0.Exemplars().AppendEmpty()
				e2.SetTimestamp(timestampFromMs(1663350815890))
				e2.SetDoubleValue(2)
				e2.FilteredAttributes().PutStr("foo", "bar")
				e2.SetTraceID([16]byte{0x10, 0xa4, 0x73, 0x65, 0xb8, 0xaa, 0x04, 0xe0, 0x82, 0x91, 0xfa, 0xb9, 0xde, 0xca, 0x84, 0xdb})
				e2.SetSpanID([8]byte{0x71, 0x9c, 0xee, 0x4a, 0x66, 0x9f, 0xd7, 0xd1})

				e3 := pt0.Exemplars().AppendEmpty()
				e3.SetTimestamp(timestampFromMs(1663350815890))
				e3.SetDoubleValue(2)
				e3.FilteredAttributes().PutStr("foo", "bar")
				e3.SetTraceID([16]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x41, 0x37, 0xca, 0xb6, 0x6d, 0xc8, 0x80})
				e3.SetSpanID([8]byte{0x00, 0x00, 0x00, 0xdf, 0xa4, 0x59, 0x7a, 0x9d})

				md1 := pmetric.NewMetrics()
				mL1 := md1.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m1 := mL1.AppendEmpty()
				m1.SetName("gauge_test")
				gauge1 := m1.SetEmptyGauge()
				pt1 := gauge1.DataPoints().AppendEmpty()
				pt1.SetDoubleValue(90.0)
				pt1.SetStartTimestamp(0)
				pt1.SetTimestamp(tsPlusIntervalNanos)
				pt1.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0, md1}
			},
		},
		{
			name: "gauge-with-different-tags",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("gauge_test", 100, nil, "foo", "bar"),
						createDataPoint("gauge_test", 200, nil, "bar", "foo"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("gauge_test")
				gauge0 := m0.SetEmptyGauge()
				pt0 := gauge0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(0)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				pt1 := gauge0.DataPoints().AppendEmpty()
				pt1.SetDoubleValue(200.0)
				pt1.SetStartTimestamp(0)
				pt1.SetTimestamp(tsNanos)
				pt1.Attributes().PutStr("bar", "foo")

				return []pmetric.Metrics{md0}
			},
		},
		{
			// TODO: A decision need to be made. If we want to have the behavior which can generate different tag key
			//  sets because metrics come and go
			name: "gauge-comes-and-go-with-different-tagset",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("gauge_test", 100, nil, "foo", "bar"),
						createDataPoint("gauge_test", 200, nil, "bar", "foo"),
					},
				},
				{
					pts: []*testDataPoint{
						createDataPoint("gauge_test", 20, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("gauge_test")
				gauge0 := m0.SetEmptyGauge()
				pt0 := gauge0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(0)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				pt1 := gauge0.DataPoints().AppendEmpty()
				pt1.SetDoubleValue(200.0)
				pt1.SetStartTimestamp(0)
				pt1.SetTimestamp(tsNanos)
				pt1.Attributes().PutStr("bar", "foo")

				md1 := pmetric.NewMetrics()
				mL1 := md1.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m1 := mL1.AppendEmpty()
				m1.SetName("gauge_test")
				gauge1 := m1.SetEmptyGauge()
				pt2 := gauge1.DataPoints().AppendEmpty()
				pt2.SetDoubleValue(20.0)
				pt2.SetStartTimestamp(0)
				pt2.SetTimestamp(tsPlusIntervalNanos)
				pt2.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0, md1}
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.run(t)
		})
	}
}

func TestMetricBuilderUntyped(t *testing.T) {
	tests := []buildTestData{
		{
			name: "one-unknown",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("unknown_test", 100, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("unknown_test")
				gauge0 := m0.SetEmptyGauge()
				pt0 := gauge0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetStartTimestamp(0)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "no-type-hint",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("something_not_exists", 100, nil, "foo", "bar"),
						createDataPoint("theother_not_exists", 200, nil, "foo", "bar"),
						createDataPoint("theother_not_exists", 300, nil, "bar", "foo"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("something_not_exists")
				gauge0 := m0.SetEmptyGauge()
				pt0 := gauge0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				m1 := mL0.AppendEmpty()
				m1.SetName("theother_not_exists")
				gauge1 := m1.SetEmptyGauge()
				pt1 := gauge1.DataPoints().AppendEmpty()
				pt1.SetDoubleValue(200.0)
				pt1.SetTimestamp(tsNanos)
				pt1.Attributes().PutStr("foo", "bar")

				pt2 := gauge1.DataPoints().AppendEmpty()
				pt2.SetDoubleValue(300.0)
				pt2.SetTimestamp(tsNanos)
				pt2.Attributes().PutStr("bar", "foo")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "untype-metric-poor-names",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("some_count", 100, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("some_count")
				gauge0 := m0.SetEmptyGauge()
				pt0 := gauge0.DataPoints().AppendEmpty()
				pt0.SetDoubleValue(100.0)
				pt0.SetTimestamp(tsNanos)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.run(t)
		})
	}
}

func TestMetricBuilderHistogram(t *testing.T) {
	tests := []buildTestData{
		{
			name: "single item",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 1, nil, "foo", "bar", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_bucket", 10, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_sum", 99, nil, "foo", "bar"),
						createDataPoint("hist_test_count", 10, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(10)
				pt0.SetSum(99)
				pt0.ExplicitBounds().FromRaw([]float64{10, 20})
				pt0.BucketCounts().FromRaw([]uint64{1, 1, 8})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "single item with exemplars",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint(
							"hist_test_bucket",
							1,
							[]exemplar.Exemplar{
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: model.MetricNameLabel, Value: "counter_test"}, {Name: model.JobLabel, Value: "job"}, {Name: model.InstanceLabel, Value: "instance"}, {Name: "foo", Value: "bar"}},
								},
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: ""}, {Name: "span_id", Value: ""}, {Name: "le", Value: "20"}},
								},
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: "10a47365b8aa04e08291fab9deca84db6170"}, {Name: "traceid", Value: "e3688e1aa2961786"}, {Name: "span_id", Value: "719cee4a669fd7d109ff"}},
								},
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: "174137cab66dc880"}, {Name: "span_id", Value: "dfa4597a9d"}},
								},
								{
									Value:  1,
									Ts:     1663113420863,
									Labels: []labels.Label{{Name: "foo", Value: "bar"}, {Name: "trace_id", Value: "174137cab66dc88"}, {Name: "span_id", Value: "dfa4597a9"}},
								},
							},
							"foo", "bar", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_bucket", 10, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_sum", 99, nil, "foo", "bar"),
						createDataPoint("hist_test_count", 10, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(10)
				pt0.SetSum(99)
				pt0.ExplicitBounds().FromRaw([]float64{10, 20})
				pt0.BucketCounts().FromRaw([]uint64{1, 1, 8})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				e0 := pt0.Exemplars().AppendEmpty()
				e0.SetTimestamp(timestampFromMs(1663113420863))
				e0.SetDoubleValue(1)
				e0.FilteredAttributes().PutStr(model.MetricNameLabel, "counter_test")
				e0.FilteredAttributes().PutStr(model.JobLabel, "job")
				e0.FilteredAttributes().PutStr(model.InstanceLabel, "instance")
				e0.FilteredAttributes().PutStr("foo", "bar")

				e1 := pt0.Exemplars().AppendEmpty()
				e1.SetTimestamp(timestampFromMs(1663113420863))
				e1.SetDoubleValue(1)
				e1.FilteredAttributes().PutStr("foo", "bar")
				e1.FilteredAttributes().PutStr("le", "20")

				e2 := pt0.Exemplars().AppendEmpty()
				e2.SetTimestamp(timestampFromMs(1663113420863))
				e2.SetDoubleValue(1)
				e2.FilteredAttributes().PutStr("foo", "bar")
				e2.FilteredAttributes().PutStr("traceid", "e3688e1aa2961786")
				e2.SetTraceID([16]byte{0x10, 0xa4, 0x73, 0x65, 0xb8, 0xaa, 0x04, 0xe0, 0x82, 0x91, 0xfa, 0xb9, 0xde, 0xca, 0x84, 0xdb})
				e2.SetSpanID([8]byte{0x71, 0x9c, 0xee, 0x4a, 0x66, 0x9f, 0xd7, 0xd1})

				e3 := pt0.Exemplars().AppendEmpty()
				e3.SetTimestamp(timestampFromMs(1663113420863))
				e3.SetDoubleValue(1)
				e3.FilteredAttributes().PutStr("foo", "bar")
				e3.SetTraceID([16]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x41, 0x37, 0xca, 0xb6, 0x6d, 0xc8, 0x80})
				e3.SetSpanID([8]byte{0x00, 0x00, 0x00, 0xdf, 0xa4, 0x59, 0x7a, 0x9d})

				e4 := pt0.Exemplars().AppendEmpty()
				e4.SetTimestamp(timestampFromMs(1663113420863))
				e4.SetDoubleValue(1)
				e4.FilteredAttributes().PutStr("foo", "bar")
				e4.FilteredAttributes().PutStr("trace_id", "174137cab66dc88")
				e4.FilteredAttributes().PutStr("span_id", "dfa4597a9")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "multi-groups",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 1, nil, "foo", "bar", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_bucket", 10, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_sum", 99, nil, "foo", "bar"),
						createDataPoint("hist_test_count", 10, nil, "foo", "bar"),
						createDataPoint("hist_test_bucket", 1, nil, "key2", "v2", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "key2", "v2", "le", "20"),
						createDataPoint("hist_test_bucket", 3, nil, "key2", "v2", "le", "+inf"),
						createDataPoint("hist_test_sum", 50, nil, "key2", "v2"),
						createDataPoint("hist_test_count", 3, nil, "key2", "v2"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(10)
				pt0.SetSum(99)
				pt0.ExplicitBounds().FromRaw([]float64{10, 20})
				pt0.BucketCounts().FromRaw([]uint64{1, 1, 8})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				pt1 := hist0.DataPoints().AppendEmpty()
				pt1.SetCount(3)
				pt1.SetSum(50)
				pt1.ExplicitBounds().FromRaw([]float64{10, 20})
				pt1.BucketCounts().FromRaw([]uint64{1, 1, 1})
				pt1.SetTimestamp(tsNanos)
				pt1.SetStartTimestamp(startTimestamp)
				pt1.Attributes().PutStr("key2", "v2")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "multi-groups-and-families",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 1, nil, "foo", "bar", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_bucket", 10, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_sum", 99, nil, "foo", "bar"),
						createDataPoint("hist_test_count", 10, nil, "foo", "bar"),
						createDataPoint("hist_test_bucket", 1, nil, "key2", "v2", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "key2", "v2", "le", "20"),
						createDataPoint("hist_test_bucket", 3, nil, "key2", "v2", "le", "+inf"),
						createDataPoint("hist_test_sum", 50, nil, "key2", "v2"),
						createDataPoint("hist_test_count", 3, nil, "key2", "v2"),
						createDataPoint("hist_test2_bucket", 1, nil, "foo", "bar", "le", "10"),
						createDataPoint("hist_test2_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test2_bucket", 3, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test2_sum", 50, nil, "foo", "bar"),
						createDataPoint("hist_test2_count", 3, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(10)
				pt0.SetSum(99)
				pt0.ExplicitBounds().FromRaw([]float64{10, 20})
				pt0.BucketCounts().FromRaw([]uint64{1, 1, 8})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				pt1 := hist0.DataPoints().AppendEmpty()
				pt1.SetCount(3)
				pt1.SetSum(50)
				pt1.ExplicitBounds().FromRaw([]float64{10, 20})
				pt1.BucketCounts().FromRaw([]uint64{1, 1, 1})
				pt1.SetTimestamp(tsNanos)
				pt1.SetStartTimestamp(startTimestamp)
				pt1.Attributes().PutStr("key2", "v2")

				m1 := mL0.AppendEmpty()
				m1.SetName("hist_test2")
				hist1 := m1.SetEmptyHistogram()
				hist1.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt2 := hist1.DataPoints().AppendEmpty()
				pt2.SetCount(3)
				pt2.SetSum(50)
				pt2.ExplicitBounds().FromRaw([]float64{10, 20})
				pt2.BucketCounts().FromRaw([]uint64{1, 1, 1})
				pt2.SetTimestamp(tsNanos)
				pt2.SetStartTimestamp(startTimestamp)
				pt2.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "unordered-buckets",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 10, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_bucket", 1, nil, "foo", "bar", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_sum", 99, nil, "foo", "bar"),
						createDataPoint("hist_test_count", 10, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(10)
				pt0.SetSum(99)
				pt0.ExplicitBounds().FromRaw([]float64{10, 20})
				pt0.BucketCounts().FromRaw([]uint64{1, 1, 8})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			// this won't likely happen in real env, as prometheus wont generate histogram with less than 3 buckets
			name: "only-one-bucket",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 3, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_count", 3, nil, "foo", "bar"),
						createDataPoint("hist_test_sum", 100, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(3)
				pt0.SetSum(100)
				pt0.BucketCounts().FromRaw([]uint64{3})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			// this won't likely happen in real env, as prometheus wont generate histogram with less than 3 buckets
			name: "only-one-bucket-noninf",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 3, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_count", 3, nil, "foo", "bar"),
						createDataPoint("hist_test_sum", 100, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(3)
				pt0.SetSum(100)
				pt0.BucketCounts().FromRaw([]uint64{3})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "no-sum",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 1, nil, "foo", "bar", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_bucket", 3, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_count", 3, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("hist_test")
				hist0 := m0.SetEmptyHistogram()
				hist0.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
				pt0 := hist0.DataPoints().AppendEmpty()
				pt0.SetCount(3)
				pt0.ExplicitBounds().FromRaw([]float64{10, 20})
				pt0.BucketCounts().FromRaw([]uint64{1, 1, 1})
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "corrupted-no-buckets",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_sum", 99, nil),
						createDataPoint("hist_test_count", 10, nil),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				return []pmetric.Metrics{pmetric.NewMetrics()}
			},
		},
		{
			name: "corrupted-no-count",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("hist_test_bucket", 1, nil, "foo", "bar", "le", "10"),
						createDataPoint("hist_test_bucket", 2, nil, "foo", "bar", "le", "20"),
						createDataPoint("hist_test_bucket", 3, nil, "foo", "bar", "le", "+inf"),
						createDataPoint("hist_test_sum", 99, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				return []pmetric.Metrics{pmetric.NewMetrics()}
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.run(t)
		})
	}
}

func TestMetricBuilderSummary(t *testing.T) {
	tests := []buildTestData{
		{
			name: "no-sum-and-count",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("summary_test", 5, nil, "foo", "bar", "quantile", "1"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				return []pmetric.Metrics{pmetric.NewMetrics()}
			},
		},
		{
			name: "no-count",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("summary_test", 1, nil, "foo", "bar", "quantile", "0.5"),
						createDataPoint("summary_test", 2, nil, "foo", "bar", "quantile", "0.75"),
						createDataPoint("summary_test", 5, nil, "foo", "bar", "quantile", "1"),
						createDataPoint("summary_test_sum", 500, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				return []pmetric.Metrics{pmetric.NewMetrics()}
			},
		},
		{
			name: "no-sum",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("summary_test", 1, nil, "foo", "bar", "quantile", "0.5"),
						createDataPoint("summary_test", 2, nil, "foo", "bar", "quantile", "0.75"),
						createDataPoint("summary_test", 5, nil, "foo", "bar", "quantile", "1"),
						createDataPoint("summary_test_count", 500, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("summary_test")
				sum0 := m0.SetEmptySummary()
				pt0 := sum0.DataPoints().AppendEmpty()
				pt0.SetTimestamp(tsNanos)
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetCount(500)
				pt0.SetSum(0.0)
				pt0.Attributes().PutStr("foo", "bar")
				qvL := pt0.QuantileValues()
				q50 := qvL.AppendEmpty()
				q50.SetQuantile(.50)
				q50.SetValue(1.0)
				q75 := qvL.AppendEmpty()
				q75.SetQuantile(.75)
				q75.SetValue(2.0)
				q100 := qvL.AppendEmpty()
				q100.SetQuantile(1)
				q100.SetValue(5.0)
				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "empty-quantiles",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("summary_test_sum", 100, nil, "foo", "bar"),
						createDataPoint("summary_test_count", 500, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("summary_test")
				sum0 := m0.SetEmptySummary()
				pt0 := sum0.DataPoints().AppendEmpty()
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetTimestamp(tsNanos)
				pt0.SetCount(500)
				pt0.SetSum(100.0)
				pt0.Attributes().PutStr("foo", "bar")

				return []pmetric.Metrics{md0}
			},
		},
		{
			name: "regular-summary",
			inputs: []*testScrapedPage{
				{
					pts: []*testDataPoint{
						createDataPoint("summary_test", 1, nil, "foo", "bar", "quantile", "0.5"),
						createDataPoint("summary_test", 2, nil, "foo", "bar", "quantile", "0.75"),
						createDataPoint("summary_test", 5, nil, "foo", "bar", "quantile", "1"),
						createDataPoint("summary_test_sum", 100, nil, "foo", "bar"),
						createDataPoint("summary_test_count", 500, nil, "foo", "bar"),
					},
				},
			},
			wants: func() []pmetric.Metrics {
				md0 := pmetric.NewMetrics()
				mL0 := md0.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
				m0 := mL0.AppendEmpty()
				m0.SetName("summary_test")
				sum0 := m0.SetEmptySummary()
				pt0 := sum0.DataPoints().AppendEmpty()
				pt0.SetStartTimestamp(startTimestamp)
				pt0.SetTimestamp(tsNanos)
				pt0.SetCount(500)
				pt0.SetSum(100.0)
				pt0.Attributes().PutStr("foo", "bar")
				qvL := pt0.QuantileValues()
				q50 := qvL.AppendEmpty()
				q50.SetQuantile(.50)
				q50.SetValue(1.0)
				q75 := qvL.AppendEmpty()
				q75.SetQuantile(.75)
				q75.SetValue(2.0)
				q100 := qvL.AppendEmpty()
				q100.SetQuantile(1)
				q100.SetValue(5.0)

				return []pmetric.Metrics{md0}
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.run(t)
		})
	}

}

type buildTestData struct {
	name   string
	inputs []*testScrapedPage
	wants  func() []pmetric.Metrics
}

func (tt buildTestData) run(t *testing.T) {
	wants := tt.wants()
	assert.EqualValues(t, len(wants), len(tt.inputs))
	st := ts
	for i, page := range tt.inputs {
		sink := new(consumertest.MetricsSink)
		tr := newTransaction(scrapeCtx, &startTimeAdjuster{startTime: startTimestamp}, sink, nil, componenttest.NewNopReceiverCreateSettings(), nopObsRecv(t), featuregate.GetRegistry())
		for _, pt := range page.pts {
			// set ts for testing
			pt.t = st
			_, err := tr.Append(0, pt.lb, pt.t, pt.v)
			assert.NoError(t, err)

			for _, e := range pt.exemplars {
				_, err := tr.AppendExemplar(0, pt.lb, e)
				assert.NoError(t, err)
			}
		}
		assert.NoError(t, tr.Commit())
		mds := sink.AllMetrics()
		if wants[i].ResourceMetrics().Len() == 0 {
			// Receiver does not emit empty metrics, so will not have anything in the sink.
			require.Len(t, mds, 0)
			st += interval
			continue
		}
		require.Len(t, mds, 1)
		assertEquivalentMetrics(t, wants[i], mds[0])
		st += interval
	}
}

type errorAdjuster struct {
	err error
}

func (ea *errorAdjuster) AdjustMetrics(pmetric.Metrics) error {
	return ea.err
}

type startTimeAdjuster struct {
	startTime pcommon.Timestamp
}

func (s *startTimeAdjuster) AdjustMetrics(metrics pmetric.Metrics) error {
	for i := 0; i < metrics.ResourceMetrics().Len(); i++ {
		rm := metrics.ResourceMetrics().At(i)
		for j := 0; j < rm.ScopeMetrics().Len(); j++ {
			ilm := rm.ScopeMetrics().At(j)
			for k := 0; k < ilm.Metrics().Len(); k++ {
				metric := ilm.Metrics().At(k)
				switch metric.Type() {
				case pmetric.MetricTypeSum:
					dps := metric.Sum().DataPoints()
					for l := 0; l < dps.Len(); l++ {
						dps.At(l).SetStartTimestamp(s.startTime)
					}
				case pmetric.MetricTypeSummary:
					dps := metric.Summary().DataPoints()
					for l := 0; l < dps.Len(); l++ {
						dps.At(l).SetStartTimestamp(s.startTime)
					}
				case pmetric.MetricTypeHistogram:
					dps := metric.Histogram().DataPoints()
					for l := 0; l < dps.Len(); l++ {
						dps.At(l).SetStartTimestamp(s.startTime)
					}
				}
			}
		}
	}
	return nil
}

type testDataPoint struct {
	lb        labels.Labels
	t         int64
	v         float64
	exemplars []exemplar.Exemplar
}

type testScrapedPage struct {
	pts []*testDataPoint
}

func createDataPoint(mname string, value float64, es []exemplar.Exemplar, tagPairs ...string) *testDataPoint {
	var lbls []string
	lbls = append(lbls, tagPairs...)
	lbls = append(lbls, model.MetricNameLabel, mname)
	lbls = append(lbls, model.JobLabel, "job")
	lbls = append(lbls, model.InstanceLabel, "instance")

	return &testDataPoint{
		lb:        labels.FromStrings(lbls...),
		t:         ts,
		v:         value,
		exemplars: es,
	}
}

func assertEquivalentMetrics(t *testing.T, want, got pmetric.Metrics) {
	require.Equal(t, want.ResourceMetrics().Len(), got.ResourceMetrics().Len())
	if want.ResourceMetrics().Len() == 0 {
		return
	}
	for i := 0; i < want.ResourceMetrics().Len(); i++ {
		wantSm := want.ResourceMetrics().At(i).ScopeMetrics()
		gotSm := got.ResourceMetrics().At(i).ScopeMetrics()
		require.Equal(t, wantSm.Len(), gotSm.Len())
		if wantSm.Len() == 0 {
			return
		}

		for j := 0; j < wantSm.Len(); j++ {
			wantMs := wantSm.At(j).Metrics()
			gotMs := gotSm.At(j).Metrics()
			require.Equal(t, wantMs.Len(), gotMs.Len())

			wmap := map[string]pmetric.Metric{}
			gmap := map[string]pmetric.Metric{}

			for k := 0; k < wantMs.Len(); k++ {
				wi := wantMs.At(k)
				wmap[wi.Name()] = wi
				gi := gotMs.At(k)
				gmap[gi.Name()] = gi
			}
			assert.EqualValues(t, wmap, gmap)
		}
	}

}


text:
export interface IContentTypeBinding {
    ContentTypeId: string;
}


text:
module.exports = (app) => {
  app.post('/register', (req, res) => {
    res.send({

      message: `Hello ${req.body.email}Your user was registered! Have fun`
    })
  })
}


text:
using System;
using OpenQA.Selenium;

namespace OpenQA.Selenite.Setup.Environments
{
    public abstract class SimpleDriverEnvironment<TWebDriver> : IDriverEnvironment
        where TWebDriver : IWebDriver, new()
    {
        protected SimpleDriverEnvironment() : this(TimeSpan.FromSeconds(5))
        {
        }

        protected SimpleDriverEnvironment(TimeSpan timeToWait)
        {
            TimeToWait = timeToWait;
            DriverFactory = () => new TWebDriver();
        }

        protected TimeSpan TimeToWait { get; }

        public virtual IWebDriver CreateWebDriver()
        {
            var driver = DriverFactory();

            InitializeDriver(driver);
            return driver;
        }

        public virtual IWebDriver CreateWebDriver(string proxy)
        {
            return CreateWebDriver();
        }

        protected Func<IWebDriver> DriverFactory { get; set; }

        protected virtual IWebDriver InitializeDriver(IWebDriver driver)
        {
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().ImplicitlyWait(TimeToWait);
            return driver;
        }
    }
}