code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1 value |
|---|---|---|---|---|---|
package parser
import (
"github.com/z-micro/ddl-parser/gen"
)
const (
_ int = iota
LongVarBinary
LongVarChar
GeometryCollection
GeomCollection
LineString
MultiLineString
MultiPoint
MultiPolygon
Point
Polygon
Json
Geometry
Enum
Set
Bit
Time
Timestamp
DateTime
Binary
VarBinary
Blob
Year
Decimal
Dec
Fixed
Numeric
Float
Float4
Float8
Double
Real
TinyInt
SmallInt
MediumInt
Int
Integer
BigInt
MiddleInt
Int1
Int2
Int3
Int4
Int8
Date
TinyBlob
MediumBlob
LongBlob
Bool
Boolean
Serial
NVarChar
NChar
Char
Character
VarChar
TinyText
Text
MediumText
LongText
)
// DataType describes the data type and value of the column in table
type DataType interface {
Type() int
// Value returns the values if the data type is Enum or Set
Value() []string
}
var _ DataType = (*NormalDataType)(nil)
var _ DataType = (*EnumSetDataType)(nil)
// NormalDataType describes the data type which not contains Enum and Set of column
type NormalDataType struct {
tp int
}
// Type returns the data type of column
func (n *NormalDataType) Type() int {
return n.tp
}
// Value returns nil default
func (n *NormalDataType) Value() []string {
return nil
}
func with(tp int, value ...string) DataType {
if len(value) > 0 {
return &EnumSetDataType{
tp: tp,
value: value,
}
}
return &NormalDataType{tp: tp}
}
// EnumSetDataType describes the data type Enum and Set of column
type EnumSetDataType struct {
tp int
value []string
}
// Type returns the data type of column
func (e *EnumSetDataType) Type() int {
return e.tp
}
// Value returns the value of data type Enum and Set
func (e *EnumSetDataType) Value() []string {
return e.value
}
// visitDataType visits data type by switch-case
func (v *visitor) visitDataType(ctx gen.IDataTypeContext) DataType {
v.trace("VisitDataType")
switch t := ctx.(type) {
case *gen.StringDataTypeContext:
return v.visitStringDataType(t)
case *gen.NationalStringDataTypeContext:
return v.visitNationalStringDataType(t)
case *gen.NationalVaryingStringDataTypeContext:
return v.visitNationalVaryingStringDataType(t)
case *gen.DimensionDataTypeContext:
return v.visitDimensionDataType(t)
case *gen.SimpleDataTypeContext:
return v.visitSimpleDataType(t)
case *gen.CollectionDataTypeContext:
return v.visitCollectionDataType(t)
case *gen.SpatialDataTypeContext:
return v.visitSpatialDataType(t)
case *gen.LongVarcharDataTypeContext:
return v.visitLongVarcharDataType(t)
case *gen.LongVarbinaryDataTypeContext:
return v.visitLongVarbinaryDataType(t)
}
v.panicWithExpr(ctx.GetStart(), "invalid data type: "+ctx.GetText())
return nil
}
// visitStringDataType visits a parse tree produced by MySqlParser#stringDataType.
func (v *visitor) visitStringDataType(ctx *gen.StringDataTypeContext) DataType {
v.trace(`VisitStringDataType`)
text := parseToken(ctx.GetTypeName(), withUpperCase(), withTrim("`"))
switch text {
case `CHAR`:
return with(Char)
case `CHARACTER`:
return with(Character)
case `VARCHAR`:
return with(VarChar)
case `TINYTEXT`:
return with(TinyText)
case `TEXT`:
return with(Text)
case `MEDIUMTEXT`:
return with(MediumText)
case `LONGTEXT`:
return with(LongText)
case `NCHAR`:
return with(NChar)
case `NVARCHAR`:
return with(NVarChar)
case `LONG`:
return with(LongVarChar)
}
v.panicWithExpr(ctx.GetTypeName(), "invalid data type: "+text)
return nil
}
// visitNationalStringDataType visits a parse tree produced by MySqlParser#nationalVaryingStringDataType.
func (v *visitor) visitNationalStringDataType(ctx *gen.NationalStringDataTypeContext) DataType {
v.trace(`VisitNationalStringDataType`)
text := parseToken(ctx.GetTypeName(), withUpperCase(), withTrim("`"))
switch text {
case `VARCHAR`:
return with(NVarChar)
case `CHARACTER`:
return with(NChar)
}
v.panicWithExpr(ctx.GetTypeName(), "invalid data type: "+text)
return nil
}
// visitNationalVaryingStringDataType visits a parse tree produced by MySqlParser#nationalVaryingStringDataType.
func (v *visitor) visitNationalVaryingStringDataType(_ *gen.NationalVaryingStringDataTypeContext) DataType {
v.trace("VisitNationalVaryingStringDataType")
return with(NVarChar)
}
// visitDimensionDataType visits a parse tree produced by MySqlParser#dimensionDataType.
func (v *visitor) visitDimensionDataType(ctx *gen.DimensionDataTypeContext) DataType {
v.trace("VisitDimensionDataType")
text := parseToken(ctx.GetTypeName(), withUpperCase(), withTrim("`"))
switch text {
case `BIT`:
return with(Bit)
case `TIME`:
return with(Time)
case `TIMESTAMP`:
return with(Timestamp)
case `DATETIME`:
return with(DateTime)
case `BINARY`:
return with(Binary)
case `VARBINARY`:
return with(VarBinary)
case `BLOB`:
return with(Blob)
case `YEAR`:
return with(Year)
case `DECIMAL`:
return with(Decimal)
case `DEC`:
return with(Dec)
case `FIXED`:
return with(Fixed)
case `NUMERIC`:
return with(Numeric)
case `FLOAT`:
return with(Float)
case `FLOAT4`:
return with(Float4)
case `FLOAT8`:
return with(Float8)
case `DOUBLE`:
return with(Double)
case `REAL`:
return with(Real)
case `TINYINT`:
return with(TinyInt)
case `SMALLINT`:
return with(SmallInt)
case `MEDIUMINT`:
return with(MediumInt)
case `INT`:
return with(Int)
case `INTEGER`:
return with(Integer)
case `BIGINT`:
return with(BigInt)
case `MIDDLEINT`:
return with(MiddleInt)
case `INT1`:
return with(Int1)
case `INT2`:
return with(Int2)
case `INT3`:
return with(Int3)
case `INT4`:
return with(Int4)
case `INT8`:
return with(Int8)
}
v.panicWithExpr(ctx.GetTypeName(), "invalid data type: "+text)
return nil
}
// visitSimpleDataType visits a parse tree produced by MySqlParser#simpleDataType.
func (v *visitor) visitSimpleDataType(ctx *gen.SimpleDataTypeContext) DataType {
v.trace("VisitSimpleDataType")
text := parseToken(
ctx.GetTypeName(),
withUpperCase(),
withTrim("`"),
)
switch text {
case `DATE`:
return with(Date)
case `TINYBLOB`:
return with(TinyBlob)
case `MEDIUMBLOB`:
return with(MediumBlob)
case `LONGBLOB`:
return with(LongBlob)
case `BOOL`:
return with(Bool)
case `BOOLEAN`:
return with(Boolean)
case `SERIAL`:
return with(Serial)
}
v.panicWithExpr(ctx.GetTypeName(), "invalid data type: "+text)
return nil
}
// visitCollectionDataType visits a parse tree produced by MySqlParser#collectionDataType.
func (v *visitor) visitCollectionDataType(ctx *gen.CollectionDataTypeContext) DataType {
v.trace("VisitCollectionDataType")
text := parseToken(
ctx.GetTypeName(),
withUpperCase(),
withTrim("`"),
)
var values []string
if ctx.CollectionOptions() != nil {
optionsCtx, ok := ctx.CollectionOptions().(*gen.CollectionOptionsContext)
if ok {
for _, e := range optionsCtx.AllSTRING_LITERAL() {
value := parseTerminalNode(
e, withTrim("`"),
withTrim(`"`),
withTrim(`'`),
)
values = append(values, value)
}
}
}
switch text {
case `ENUM`:
return with(Enum, values...)
case `SET`:
return with(Set, values...)
}
v.panicWithExpr(ctx.GetTypeName(), "invalid data type: "+text)
return nil
}
// visitSpatialDataType visits a parse tree produced by MySqlParser#spatialDataType.
func (v *visitor) visitSpatialDataType(ctx *gen.SpatialDataTypeContext) DataType {
v.trace("VisitSpatialDataType")
text := parseToken(
ctx.GetTypeName(),
withUpperCase(),
withTrim("`"),
)
switch text {
case `GEOMETRYCOLLECTION`:
return with(GeometryCollection)
case `GEOMCOLLECTION`:
return with(GeomCollection)
case `LINESTRING`:
return with(LineString)
case `MULTILINESTRING`:
return with(MultiLineString)
case `MULTIPOINT`:
return with(MultiPoint)
case `MULTIPOLYGON`:
return with(MultiPolygon)
case `POINT`:
return with(Point)
case `POLYGON`:
return with(Polygon)
case `JSON`:
return with(Json)
case `GEOMETRY`:
return with(Geometry)
}
v.panicWithExpr(ctx.GetTypeName(), "invalid data type: "+text)
return nil
}
// visitLongVarcharDataType visits a parse tree produced by MySqlParser#longVarcharDataType.
func (v *visitor) visitLongVarcharDataType(_ *gen.LongVarcharDataTypeContext) DataType {
v.trace("VisitLongVarcharDataType")
return with(LongVarChar)
}
// visitLongVarbinaryDataType visits a parse tree produced by MySqlParser#longVarbinaryDataType.
func (v *visitor) visitLongVarbinaryDataType(_ *gen.LongVarbinaryDataTypeContext) DataType {
v.trace("VisitLongVarbinaryDataType")
return with(LongVarBinary)
} | parser/datatype_visitor.go | 0.658966 | 0.417182 | datatype_visitor.go | starcoder |
package plaid
import (
"encoding/json"
"time"
)
// TransactionAllOf struct for TransactionAllOf
type TransactionAllOf struct {
// The channel used to make a payment. `online:` transactions that took place online. `in store:` transactions that were made at a physical location. `other:` transactions that relate to banks, e.g. fees or deposits. This field replaces the `transaction_type` field.
PaymentChannel string `json:"payment_channel"`
// The merchant name, as extracted by Plaid from the `name` field.
MerchantName NullableString `json:"merchant_name"`
// The date that the transaction was authorized. Dates are returned in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format ( `YYYY-MM-DD` ).
AuthorizedDate NullableString `json:"authorized_date"`
// Date and time when a transaction was authorized in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format ( `YYYY-MM-DDTHH:mm:ssZ` ). This field is only populated for UK institutions. For institutions in other countries, will be `null`.
AuthorizedDatetime NullableTime `json:"authorized_datetime"`
// Date and time when a transaction was posted in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format ( `YYYY-MM-DDTHH:mm:ssZ` ). This field is only populated for UK institutions. For institutions in other countries, will be `null`.
Datetime NullableTime `json:"datetime"`
// The check number of the transaction. This field is only populated for check transactions.
CheckNumber NullableString `json:"check_number"`
TransactionCode NullableTransactionCode `json:"transaction_code"`
PersonalFinanceCategory NullablePersonalFinanceCategory `json:"personal_finance_category,omitempty"`
}
// NewTransactionAllOf instantiates a new TransactionAllOf object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewTransactionAllOf(paymentChannel string, merchantName NullableString, authorizedDate NullableString, authorizedDatetime NullableTime, datetime NullableTime, checkNumber NullableString, transactionCode NullableTransactionCode) *TransactionAllOf {
this := TransactionAllOf{}
this.PaymentChannel = paymentChannel
this.MerchantName = merchantName
this.AuthorizedDate = authorizedDate
this.AuthorizedDatetime = authorizedDatetime
this.Datetime = datetime
this.CheckNumber = checkNumber
this.TransactionCode = transactionCode
return &this
}
// NewTransactionAllOfWithDefaults instantiates a new TransactionAllOf object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewTransactionAllOfWithDefaults() *TransactionAllOf {
this := TransactionAllOf{}
return &this
}
// GetPaymentChannel returns the PaymentChannel field value
func (o *TransactionAllOf) GetPaymentChannel() string {
if o == nil {
var ret string
return ret
}
return o.PaymentChannel
}
// GetPaymentChannelOk returns a tuple with the PaymentChannel field value
// and a boolean to check if the value has been set.
func (o *TransactionAllOf) GetPaymentChannelOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.PaymentChannel, true
}
// SetPaymentChannel sets field value
func (o *TransactionAllOf) SetPaymentChannel(v string) {
o.PaymentChannel = v
}
// GetMerchantName returns the MerchantName field value
// If the value is explicit nil, the zero value for string will be returned
func (o *TransactionAllOf) GetMerchantName() string {
if o == nil || o.MerchantName.Get() == nil {
var ret string
return ret
}
return *o.MerchantName.Get()
}
// GetMerchantNameOk returns a tuple with the MerchantName field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransactionAllOf) GetMerchantNameOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.MerchantName.Get(), o.MerchantName.IsSet()
}
// SetMerchantName sets field value
func (o *TransactionAllOf) SetMerchantName(v string) {
o.MerchantName.Set(&v)
}
// GetAuthorizedDate returns the AuthorizedDate field value
// If the value is explicit nil, the zero value for string will be returned
func (o *TransactionAllOf) GetAuthorizedDate() string {
if o == nil || o.AuthorizedDate.Get() == nil {
var ret string
return ret
}
return *o.AuthorizedDate.Get()
}
// GetAuthorizedDateOk returns a tuple with the AuthorizedDate field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransactionAllOf) GetAuthorizedDateOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.AuthorizedDate.Get(), o.AuthorizedDate.IsSet()
}
// SetAuthorizedDate sets field value
func (o *TransactionAllOf) SetAuthorizedDate(v string) {
o.AuthorizedDate.Set(&v)
}
// GetAuthorizedDatetime returns the AuthorizedDatetime field value
// If the value is explicit nil, the zero value for time.Time will be returned
func (o *TransactionAllOf) GetAuthorizedDatetime() time.Time {
if o == nil || o.AuthorizedDatetime.Get() == nil {
var ret time.Time
return ret
}
return *o.AuthorizedDatetime.Get()
}
// GetAuthorizedDatetimeOk returns a tuple with the AuthorizedDatetime field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransactionAllOf) GetAuthorizedDatetimeOk() (*time.Time, bool) {
if o == nil {
return nil, false
}
return o.AuthorizedDatetime.Get(), o.AuthorizedDatetime.IsSet()
}
// SetAuthorizedDatetime sets field value
func (o *TransactionAllOf) SetAuthorizedDatetime(v time.Time) {
o.AuthorizedDatetime.Set(&v)
}
// GetDatetime returns the Datetime field value
// If the value is explicit nil, the zero value for time.Time will be returned
func (o *TransactionAllOf) GetDatetime() time.Time {
if o == nil || o.Datetime.Get() == nil {
var ret time.Time
return ret
}
return *o.Datetime.Get()
}
// GetDatetimeOk returns a tuple with the Datetime field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransactionAllOf) GetDatetimeOk() (*time.Time, bool) {
if o == nil {
return nil, false
}
return o.Datetime.Get(), o.Datetime.IsSet()
}
// SetDatetime sets field value
func (o *TransactionAllOf) SetDatetime(v time.Time) {
o.Datetime.Set(&v)
}
// GetCheckNumber returns the CheckNumber field value
// If the value is explicit nil, the zero value for string will be returned
func (o *TransactionAllOf) GetCheckNumber() string {
if o == nil || o.CheckNumber.Get() == nil {
var ret string
return ret
}
return *o.CheckNumber.Get()
}
// GetCheckNumberOk returns a tuple with the CheckNumber field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransactionAllOf) GetCheckNumberOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.CheckNumber.Get(), o.CheckNumber.IsSet()
}
// SetCheckNumber sets field value
func (o *TransactionAllOf) SetCheckNumber(v string) {
o.CheckNumber.Set(&v)
}
// GetTransactionCode returns the TransactionCode field value
// If the value is explicit nil, the zero value for TransactionCode will be returned
func (o *TransactionAllOf) GetTransactionCode() TransactionCode {
if o == nil || o.TransactionCode.Get() == nil {
var ret TransactionCode
return ret
}
return *o.TransactionCode.Get()
}
// GetTransactionCodeOk returns a tuple with the TransactionCode field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransactionAllOf) GetTransactionCodeOk() (*TransactionCode, bool) {
if o == nil {
return nil, false
}
return o.TransactionCode.Get(), o.TransactionCode.IsSet()
}
// SetTransactionCode sets field value
func (o *TransactionAllOf) SetTransactionCode(v TransactionCode) {
o.TransactionCode.Set(&v)
}
// GetPersonalFinanceCategory returns the PersonalFinanceCategory field value if set, zero value otherwise (both if not set or set to explicit null).
func (o *TransactionAllOf) GetPersonalFinanceCategory() PersonalFinanceCategory {
if o == nil || o.PersonalFinanceCategory.Get() == nil {
var ret PersonalFinanceCategory
return ret
}
return *o.PersonalFinanceCategory.Get()
}
// GetPersonalFinanceCategoryOk returns a tuple with the PersonalFinanceCategory field value if set, nil otherwise
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransactionAllOf) GetPersonalFinanceCategoryOk() (*PersonalFinanceCategory, bool) {
if o == nil {
return nil, false
}
return o.PersonalFinanceCategory.Get(), o.PersonalFinanceCategory.IsSet()
}
// HasPersonalFinanceCategory returns a boolean if a field has been set.
func (o *TransactionAllOf) HasPersonalFinanceCategory() bool {
if o != nil && o.PersonalFinanceCategory.IsSet() {
return true
}
return false
}
// SetPersonalFinanceCategory gets a reference to the given NullablePersonalFinanceCategory and assigns it to the PersonalFinanceCategory field.
func (o *TransactionAllOf) SetPersonalFinanceCategory(v PersonalFinanceCategory) {
o.PersonalFinanceCategory.Set(&v)
}
// SetPersonalFinanceCategoryNil sets the value for PersonalFinanceCategory to be an explicit nil
func (o *TransactionAllOf) SetPersonalFinanceCategoryNil() {
o.PersonalFinanceCategory.Set(nil)
}
// UnsetPersonalFinanceCategory ensures that no value is present for PersonalFinanceCategory, not even an explicit nil
func (o *TransactionAllOf) UnsetPersonalFinanceCategory() {
o.PersonalFinanceCategory.Unset()
}
func (o TransactionAllOf) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["payment_channel"] = o.PaymentChannel
}
if true {
toSerialize["merchant_name"] = o.MerchantName.Get()
}
if true {
toSerialize["authorized_date"] = o.AuthorizedDate.Get()
}
if true {
toSerialize["authorized_datetime"] = o.AuthorizedDatetime.Get()
}
if true {
toSerialize["datetime"] = o.Datetime.Get()
}
if true {
toSerialize["check_number"] = o.CheckNumber.Get()
}
if true {
toSerialize["transaction_code"] = o.TransactionCode.Get()
}
if o.PersonalFinanceCategory.IsSet() {
toSerialize["personal_finance_category"] = o.PersonalFinanceCategory.Get()
}
return json.Marshal(toSerialize)
}
type NullableTransactionAllOf struct {
value *TransactionAllOf
isSet bool
}
func (v NullableTransactionAllOf) Get() *TransactionAllOf {
return v.value
}
func (v *NullableTransactionAllOf) Set(val *TransactionAllOf) {
v.value = val
v.isSet = true
}
func (v NullableTransactionAllOf) IsSet() bool {
return v.isSet
}
func (v *NullableTransactionAllOf) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableTransactionAllOf(val *TransactionAllOf) *NullableTransactionAllOf {
return &NullableTransactionAllOf{value: val, isSet: true}
}
func (v NullableTransactionAllOf) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableTransactionAllOf) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | plaid/model_transaction_all_of.go | 0.86592 | 0.513303 | model_transaction_all_of.go | starcoder |
package views
import (
"github.com/zyedidia/tcell"
)
// BoxLayout is a container Widget that lays out its child widgets in
// either a horizontal row or a vertical column.
type BoxLayout struct {
view View
orient Orientation
style tcell.Style // backing style
cells []*boxLayoutCell
width int
height int
changed bool
WidgetWatchers
}
type boxLayoutCell struct {
widget Widget
fill float64 // fill factor - 0.0 means no expansion
pad int // count of padding spaces (stretch)
frac float64 // calculated residual spacing, used internally
view *ViewPort
}
func (b *BoxLayout) hLayout() {
w, h := b.view.Size()
totf := 0.0
for _, c := range b.cells {
x, y := c.widget.Size()
totf += c.fill
b.width += x
if y > b.height {
b.height = y
}
c.pad = 0
c.frac = 0
}
extra := w - b.width
if extra < 0 {
extra = 0
}
resid := extra
if totf == 0 {
resid = 0
}
for _, c := range b.cells {
if c.fill > 0 {
c.frac = float64(extra) * c.fill / totf
c.pad = int(c.frac)
c.frac -= float64(c.pad)
resid -= c.pad
}
}
// Distribute any left over padding. We try to give it to the
// the cells with the highest residual fraction. It should be
// the case that no single cell gets more than one more cell.
for resid > 0 {
var best *boxLayoutCell
for _, c := range b.cells {
if c.fill == 0 {
continue
}
if best == nil || c.frac > best.frac {
best = c
}
}
best.pad++
best.frac = 0
resid--
}
x, y, xinc := 0, 0, 0
for _, c := range b.cells {
cw, _ := c.widget.Size()
xinc = cw + c.pad
cw += c.pad
c.view.Resize(x, y, cw, h)
x += xinc
}
}
func (b *BoxLayout) vLayout() {
w, h := b.view.Size()
totf := 0.0
for _, c := range b.cells {
x, y := c.widget.Size()
b.height += y
totf += c.fill
if x > b.width {
b.width = x
}
c.pad = 0
c.frac = 0
}
extra := h - b.height
if extra < 0 {
extra = 0
}
resid := extra
if totf == 0 {
resid = 0
}
for _, c := range b.cells {
if c.fill > 0 {
c.frac = float64(extra) * c.fill / totf
c.pad = int(c.frac)
c.frac -= float64(c.pad)
resid -= c.pad
}
}
// Distribute any left over padding. We try to give it to the
// the cells with the highest residual fraction. It should be
// the case that no single cell gets more than one more cell.
for resid > 0 {
var best *boxLayoutCell
for _, c := range b.cells {
if c.fill == 0 {
continue
}
if best == nil || c.frac > best.frac {
best = c
}
}
best.pad++
best.frac = 0
resid--
}
x, y, yinc := 0, 0, 0
for _, c := range b.cells {
_, ch := c.widget.Size()
yinc = ch + c.pad
ch += c.pad
c.view.Resize(x, y, w, ch)
y += yinc
}
}
func (b *BoxLayout) layout() {
if b.view == nil {
return
}
b.width, b.height = 0, 0
switch b.orient {
case Horizontal:
b.hLayout()
case Vertical:
b.vLayout()
default:
panic("Bad orientation")
}
b.changed = false
}
// Resize adjusts the layout when the underlying View changes size.
func (b *BoxLayout) Resize() {
b.layout()
// Now also let the children know we resized.
for i := range b.cells {
b.cells[i].widget.Resize()
}
b.PostEventWidgetResize(b)
}
// Draw is called to update the displayed content.
func (b *BoxLayout) Draw() {
if b.view == nil {
return
}
if b.changed {
b.layout()
}
b.view.Fill('*', b.style)
w, h := b.view.Size()
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
b.view.SetContent(x, y, ' ', nil, b.style)
}
}
for i := range b.cells {
b.cells[i].widget.Draw()
}
}
// Size returns the preferred size in character cells (width, height).
func (b *BoxLayout) Size() (int, int) {
return b.width, b.height
}
// SetView sets the View object used for the text bar.
func (b *BoxLayout) SetView(view View) {
b.changed = true
b.view = view
for _, c := range b.cells {
c.view.SetView(view)
}
}
// HandleEvent implements a tcell.EventHandler. The only events
// we care about are Widget change events from our children. We
// watch for those so that if the child changes, we can arrange
// to update our layout.
func (b *BoxLayout) HandleEvent(ev tcell.Event) bool {
switch ev.(type) {
case *EventWidgetContent:
// This can only have come from one of our children.
b.changed = true
b.PostEventWidgetContent(b)
return true
}
for _, c := range b.cells {
if c.widget.HandleEvent(ev) {
return true
}
}
return false
}
// AddWidget adds a widget to the end of the BoxLayout.
func (b *BoxLayout) AddWidget(widget Widget, fill float64) {
c := &boxLayoutCell{
widget: widget,
fill: fill,
view: NewViewPort(b.view, 0, 0, 0, 0),
}
widget.SetView(c.view)
b.cells = append(b.cells, c)
b.changed = true
widget.Watch(b)
b.layout()
b.PostEventWidgetContent(b)
}
// InsertWidget inserts a widget at the given offset. Offset 0 is the
// front. If the index is longer than the number of widgets, then it
// just gets appended to the end.
func (b *BoxLayout) InsertWidget(index int, widget Widget, fill float64) {
c := &boxLayoutCell{
widget: widget,
fill: fill,
view: NewViewPort(b.view, 0, 0, 0, 0),
}
c.widget.SetView(c.view)
if index < 0 {
index = 0
}
if index > len(b.cells) {
index = len(b.cells)
}
b.cells = append(b.cells, c)
copy(b.cells[index+1:], b.cells[index:])
b.cells[index] = c
widget.Watch(b)
b.layout()
b.PostEventWidgetContent(b)
}
// RemoveWidget removes a Widget from the layout.
func (b *BoxLayout) RemoveWidget(widget Widget) {
for i := 0; i < len(b.cells); i++ {
if b.cells[i].widget == widget {
b.cells = append(b.cells[:i], b.cells[i+1:]...)
return
}
}
b.changed = true
widget.Unwatch(b)
b.layout()
b.PostEventWidgetContent(b)
}
// Widgets returns the list of Widgets for this BoxLayout.
func (b *BoxLayout) Widgets() []Widget {
w := make([]Widget, 0, len(b.cells))
for _, c := range b.cells {
w = append(w, c.widget)
}
return w
}
// SetOrientation sets the orientation as either Horizontal or Vertical.
func (b *BoxLayout) SetOrientation(orient Orientation) {
if b.orient != orient {
b.orient = orient
b.changed = true
b.PostEventWidgetContent(b)
}
}
// SetStyle sets the style used.
func (b *BoxLayout) SetStyle(style tcell.Style) {
b.style = style
b.PostEventWidgetContent(b)
}
// NewBoxLayout creates an empty BoxLayout.
func NewBoxLayout(orient Orientation) *BoxLayout {
return &BoxLayout{orient: orient}
} | views/boxlayout.go | 0.585338 | 0.409044 | boxlayout.go | starcoder |
package hamt32
import (
"fmt"
"hash/fnv"
"strconv"
"strings"
"github.com/pkg/errors"
)
// HashVal sets the numberer of bits of the hash value by being an alias to
// uint32 and establishes a type we can hang methods, like Index(), off of.
type HashVal uint32
// CalcHash deterministically calculates a randomized uint32 of a given byte
// slice .
func CalcHash(bs []byte) HashVal {
return HashVal(fold(hash(bs), remainder))
}
func hash(bs []byte) uint32 {
var h = fnv.New32()
h.Write(bs)
return h.Sum32()
}
func mask(size uint) uint32 {
return uint32(1<<size) - 1
}
func fold(hash uint32, rem uint) uint32 {
return (hash >> (hashSize - rem)) ^ (hash & mask(hashSize-rem))
}
func indexMask(depth uint) HashVal {
return HashVal((1<<NumIndexBits)-1) << (depth * NumIndexBits)
}
// Index returns the NumIndexBits bit value of the HashVal at 'depth' number of
// NumIndexBits number of bits into HashVal.
func (hv HashVal) Index(depth uint) uint {
_ = assertOn && assert(depth < DepthLimit, "Index: depth > maxDepth")
var idxMask = indexMask(depth)
return uint((hv & idxMask) >> (depth * NumIndexBits))
}
func hashPathMask(depth uint) HashVal {
return HashVal(1<<((depth)*NumIndexBits)) - 1
}
// hashPath calculates the path required to read the given depth. In other words
// it returns a HashVal that preserves the first depth-1 NumIndexBits index
// values. For depth=0 it always returns no path (aka a 0 value).
// For depth=maxDepth it returns all but the last index value.
func (hv HashVal) hashPath(depth uint) HashVal {
_ = assertOn && assert(depth < DepthLimit, "hashPath(): dept > maxDepth")
if depth == 0 {
return 0
}
return hv & hashPathMask(depth)
}
// buildHashPath method adds a idx at depth level of the hashPath. Given a
// hash Path = "/11/07/13" and you call hashPath.buildHashPath(23, 3) the method
// will return hashPath "/11/07/13/23". hashPath is shown here in the string
// representation, but the real value is HashVal (aka uint32).
func (hv HashVal) buildHashPath(idx, depth uint) HashVal {
_ = assertOn && assert(idx < DepthLimit, "buildHashPath: idx > maxIndex")
hv &= hashPathMask(depth)
return hv | HashVal(idx<<(depth*NumIndexBits))
}
// HashPathString returns a string representation of the index path of a
// HashVal. It will be string of the form "/idx0/idx1/..." where each idxN value
// will be a zero padded number between 0 and maxIndex. There will be limit
// number of such values where limit <= DepthLimit.
// If the limit parameter is 0 then the method will simply return "/".
// Example: "/00/24/46/17" for limit=4 of a NumIndexBits=5 hash value
// represented by "/00/24/46/17/34/08".
func (hv HashVal) HashPathString(limit uint) string {
_ = assertOn && assertf(limit <= DepthLimit,
"HashPathString: limit,%d > DepthLimit,%d\n", limit, DepthLimit)
if limit == 0 {
return "/"
}
var strs = make([]string, limit)
for d := uint(0); d < limit; d++ {
var idx = hv.Index(d)
strs[d] = fmt.Sprintf("%02d", idx)
}
return "/" + strings.Join(strs, "/")
}
// bitString returns a HashVal as a string of bits separated into groups of
// NumIndexBits bits.
func (hv HashVal) bitString() string {
var strs = make([]string, DepthLimit)
var fmtStr = fmt.Sprintf("%%0%db", NumIndexBits)
for d := uint(0); d < DepthLimit; d++ {
strs[maxDepth-d] = fmt.Sprintf(fmtStr, hv.Index(d))
}
var remStr string
if remainder > 0 {
remStr = strings.Repeat("0", int(remainder)) + " "
}
return remStr + strings.Join(strs, " ")
}
// String returns a string representation of a full HashVal. This is simply
// hv.HashPathString(DepthLimit).
func (hv HashVal) String() string {
return hv.HashPathString(DepthLimit)
}
// parseHashPath
func parseHashPath(s string) (HashVal, error) {
if !strings.HasPrefix(s, "/") {
return 0, errors.Errorf(
"parseHashPath: input, %q, does not start with '/'", s)
}
if len(s) == 1 { // s="/"
return 0, nil
}
if strings.HasSuffix(s, "/") {
return 0, errors.Errorf("parseHashPath: input, %q, ends with '/'", s)
}
var s0 = s[1:] //take the leading '/' off
var idxStrs = strings.Split(s0, "/")
var hv HashVal
for i, idxStr := range idxStrs {
var idx, err = strconv.ParseUint(idxStr, 10, int(NumIndexBits))
if err != nil {
return 0, errors.Wrapf(err,
"parseHashPath: the %d'th index string failed to parse.", i)
}
//hv |= HashVal(idx << (uint(i) * NumIndexBits))
hv = hv.buildHashPath(uint(idx), uint(i))
}
return hv, nil
} | hamt32/hashval.go | 0.730386 | 0.441613 | hashval.go | starcoder |
package primitives
import (
"errors"
"github.com/phoreproject/synapse/pb"
)
// ProposerSlashing is a slashing request for a proposal violation.
type ProposerSlashing struct {
ProposerIndex uint32
ProposalData1 ProposalSignedData
ProposalSignature1 [48]byte
ProposalData2 ProposalSignedData
ProposalSignature2 [48]byte
}
// Copy returns a copy of the proposer slashing.
func (ps *ProposerSlashing) Copy() ProposerSlashing {
return *ps
}
// ToProto gets the protobuf representation of the proposer slashing.
func (ps *ProposerSlashing) ToProto() *pb.ProposerSlashing {
newPS := &pb.ProposerSlashing{
ProposerIndex: ps.ProposerIndex,
ProposalData1: ps.ProposalData1.ToProto(),
ProposalData2: ps.ProposalData2.ToProto(),
}
newPS.ProposalSignature1 = ps.ProposalSignature1[:]
newPS.ProposalSignature2 = ps.ProposalSignature2[:]
return newPS
}
// ProposerSlashingFromProto gets the proposer slashing from the protobuf representation
func ProposerSlashingFromProto(slashing *pb.ProposerSlashing) (*ProposerSlashing, error) {
if len(slashing.ProposalSignature1) > 48 {
return nil, errors.New("proposalSignature1 should be 48 bytes long")
}
if len(slashing.ProposalSignature2) > 48 {
return nil, errors.New("proposalSignature2 should be 48 bytes long")
}
pd1, err := ProposalSignedDataFromProto(slashing.ProposalData1)
if err != nil {
return nil, err
}
pd2, err := ProposalSignedDataFromProto(slashing.ProposalData2)
if err != nil {
return nil, err
}
ps := &ProposerSlashing{
ProposalData1: *pd1,
ProposalData2: *pd2,
ProposerIndex: slashing.ProposerIndex,
}
copy(ps.ProposalSignature1[:], slashing.ProposalSignature1)
copy(ps.ProposalSignature2[:], slashing.ProposalSignature2)
return ps, nil
}
// SlashableVoteData is the vote data that should be slashed.
type SlashableVoteData struct {
AggregateSignaturePoC0Indices []uint32
AggregateSignaturePoC1Indices []uint32
Data AttestationData
AggregateSignature [48]byte
}
// Copy returns a copy of the slashable vote data.
func (svd *SlashableVoteData) Copy() SlashableVoteData {
return SlashableVoteData{
AggregateSignaturePoC0Indices: append([]uint32{}, svd.AggregateSignaturePoC0Indices[:]...),
AggregateSignaturePoC1Indices: append([]uint32{}, svd.AggregateSignaturePoC1Indices[:]...),
Data: svd.Data.Copy(),
AggregateSignature: svd.AggregateSignature,
}
}
// ToProto returns the protobuf representation of the slashable vote data.
func (svd *SlashableVoteData) ToProto() *pb.SlashableVoteData {
newSvd := &pb.SlashableVoteData{
AggregateSignaturePoC0Indices: append([]uint32{}, svd.AggregateSignaturePoC0Indices[:]...),
AggregateSignaturePoC1Indices: append([]uint32{}, svd.AggregateSignaturePoC1Indices[:]...),
Data: svd.Data.ToProto(),
}
newSvd.AggregateSignature = append([]byte{}, svd.AggregateSignature[:]...)
return newSvd
}
// SlashableVoteDataFromProto returns the vote data from the protobuf representation
func SlashableVoteDataFromProto(voteData *pb.SlashableVoteData) (*SlashableVoteData, error) {
if len(voteData.AggregateSignature) > 48 {
return nil, errors.New("aggregateSignature should be 48 bytes")
}
svd := &SlashableVoteData{}
svd.AggregateSignaturePoC0Indices = append([]uint32{}, voteData.AggregateSignaturePoC0Indices...)
svd.AggregateSignaturePoC1Indices = append([]uint32{}, voteData.AggregateSignaturePoC1Indices...)
copy(svd.AggregateSignature[:], voteData.AggregateSignature)
data, err := AttestationDataFromProto(voteData.Data)
if err != nil {
return nil, err
}
svd.Data = *data
return svd, nil
}
// CasperSlashing is a claim to slash based on two votes.
type CasperSlashing struct {
Votes1 SlashableVoteData
Votes2 SlashableVoteData
}
// Copy returns a copy of the casper slashing.
func (cs *CasperSlashing) Copy() CasperSlashing {
return CasperSlashing{
cs.Votes1.Copy(),
cs.Votes2.Copy(),
}
}
// ToProto gets the protobuf representaton of the casper slashing.
func (cs *CasperSlashing) ToProto() *pb.CasperSlashing {
return &pb.CasperSlashing{
Vote0: cs.Votes1.ToProto(),
Vote1: cs.Votes2.ToProto(),
}
}
// CasperSlashingFromProto returns the casper slashing from the protobuf representation.
func CasperSlashingFromProto(slashing *pb.CasperSlashing) (*CasperSlashing, error) {
votes1, err := SlashableVoteDataFromProto(slashing.Vote0)
if err != nil {
return nil, err
}
votes2, err := SlashableVoteDataFromProto(slashing.Vote1)
if err != nil {
return nil, err
}
return &CasperSlashing{
Votes1: *votes1,
Votes2: *votes2,
}, nil
} | primitives/slashings.go | 0.712332 | 0.412353 | slashings.go | starcoder |
package data
import "strings"
// TypeKind is the kind of a type.
type TypeKind int
const (
// IntType is an int
IntType TypeKind = iota
// StringType is a string
StringType
// BoolType is a bool
BoolType
// JSValueType is js.Value
JSValueType
// NamedType is any named type that is not an int, a string or a bool.
NamedType
// ArrayType is an array
ArrayType
// MapType is a map
MapType
// ChanType is a chan
ChanType
// FuncType is a func
FuncType
// PointerType is a pointer
PointerType
)
// ParamType is the type of a handler or controller method parameter.
type ParamType struct {
Kind TypeKind
// used when Kind == NamedType
Name string
// used when Kind == MapType
KeyType *ParamType
// used when Kind in [ArrayType, MapType, PointerType, FuncType (return type)]
ValueType *ParamType
// used when Kind == FuncType
Params []Param
}
func (pt ParamType) String() string {
switch pt.Kind {
case IntType:
return "int"
case StringType:
return "string"
case BoolType:
return "bool"
case JSValueType:
return "js.Value"
case NamedType:
return pt.Name
case ArrayType:
return "[]" + pt.ValueType.String()
case MapType:
return "map[" + pt.KeyType.String() + "]" + pt.ValueType.String()
case ChanType:
return "chan " + pt.ValueType.String()
case FuncType:
var sb strings.Builder
sb.WriteString("func(")
for _, p := range pt.Params {
sb.WriteString(p.Name)
sb.WriteByte(' ')
sb.WriteString(p.Type.String())
sb.WriteByte(',')
}
sb.WriteString(") ")
if pt.ValueType != nil {
sb.WriteString(pt.ValueType.String())
}
return sb.String()
case PointerType:
return "*" + pt.ValueType.String()
default:
panic("unexpected type kind")
}
}
// Param is a parameter of a handler or controller method.
type Param struct {
Name string
Type *ParamType
}
func (p *Param) String() string {
return p.Name + " " + p.Type.String()
}
// Field is a declared field of a component.
type Field struct {
Name string
Type *ParamType
DefaultValue *string
} | data/types.go | 0.506347 | 0.432423 | types.go | starcoder |
package playgo
import (
"fmt"
)
// TreeNode is the definition for a binary tree type
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// TreeHeight returns the maximum height of the btree
func TreeHeight(r *TreeNode) int {
if r == nil {
return 0
}
hl, hr := 0, 0
if r.Left != nil {
hl = TreeHeight(r.Left)
}
if r.Right != nil {
hr = TreeHeight(r.Right)
}
if hl > hr {
return hl + 1
}
return hr + 1
}
// IsBalanced returns true if the difference between the left and right
// subtrees of any node in the tree is less than one.
func IsBalanced(root *TreeNode) bool {
bal, _ := isBalancedTree(root)
return bal
}
// IsBalanced returns true if the difference between the left and right
// subtrees of any node in the tree is less than one. It returns
// the height of the tree to aid computation
func isBalancedTree(root *TreeNode) (bool, int) {
if root == nil {
return true, 0
}
rb, rh := isBalancedTree(root.Right)
lb, lh := isBalancedTree(root.Left)
if rb == false || lb == false {
return false, 0
}
delta := lh - rh
if delta < -1 || delta > 1 {
return false, 0
}
height := lh
if rh > height {
height = rh
}
return true, height + 1
}
func printTreeLine(n *TreeNode, l, level int, line *[]string) {
if l == level {
if n == nil {
*line = append(*line, "- ")
} else {
*line = append(*line, fmt.Sprintf("%d ", n.Val))
}
}
if l < level {
if n == nil {
*line = append(*line, "- ")
*line = append(*line, "- ")
} else {
printTreeLine(n.Left, l+1, level, line)
printTreeLine(n.Right, l+1, level, line)
}
}
}
// PrintTree is a pretty print for a tree
func PrintTree(n *TreeNode) {
h := TreeHeight(n)
if h > 4 {
fmt.Printf("Warning: this function will print at most 4 levels")
}
for l := 0; l < h && l < 4; l = l + 1 {
line := make([]string, 0)
printTreeLine(n, 0, l, &line)
switch l {
case 0:
fmt.Printf(" %s\n", line[0])
case 1:
fmt.Printf(" / \\ \n")
fmt.Printf(" %s %s \n", line[0], line[1])
case 2:
fmt.Printf(" / \\ / \\\n")
fmt.Printf(" %s %s %s %s\n",
line[0], line[1], line[2], line[3])
case 3:
fmt.Printf(" /\\ /\\ /\\ /\\\n")
fmt.Printf("%s%s%s%s %s%s%s%s\n",
line[0], line[1], line[2], line[3],
line[4], line[5], line[6], line[7])
}
}
fmt.Println()
}
func invertNode(n *TreeNode) {
t := n.Left
n.Left = n.Right
n.Right = t
}
// inverTree solve the LeetCode problem
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return root
}
if root.Left != nil {
invertTree(root.Left)
}
if root.Right != nil {
invertTree(root.Right)
}
invertNode(root)
return root
}
// InvertTree swap the left and right children on all the nodes
func InvertTree(root *TreeNode) *TreeNode {
invertTree(root)
PrintTree(root)
return root
}
// CompareTree will compare all the nodes and make sure the values are same
func CompareTree(n *TreeNode, p *TreeNode) bool {
if n.Val != p.Val {
return false
}
leftE, rightE := false, false
if n.Left != nil {
if p.Left != nil {
leftE = CompareTree(n.Left, p.Left)
}
}
if leftE == false {
return false
}
if n.Right != nil {
if p.Right != nil {
rightE = CompareTree(n.Right, p.Right)
}
}
if rightE == false {
return false
}
return true
} | tree/invertBtree.go | 0.770465 | 0.433981 | invertBtree.go | starcoder |
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
)
// Counter is a Metric that represents a single numerical value that only ever
// goes up.
type Counter interface {
// Inc increments the counter by 1. Use Add to increment it by arbitrary
// non-negative values.
Inc()
// Add adds the given value to the counter. It panics if the value is <
// 0.
Add(float64)
}
type counter struct {
name string
labels map[string]string
inner prometheus.Counter
changes chan<- CountChange
}
func (c *counter) Inc() {
c.inner.Inc()
c.signal(1)
}
func (c *counter) Add(f float64) {
c.inner.Add(f)
c.signal(f)
}
func (c *counter) signal(v float64) {
if c.inner == nil {
return
}
if c.changes != nil {
c.changes <- CountChange{
Name: c.name,
Increment: v,
Labels: c.labels,
}
}
}
// Gauge is a Metric that represents a single numerical value that can
// arbitrarily go up and down.
type Gauge interface {
// Set sets the Gauge to an arbitrary value.
Set(float64)
// Inc increments the Gauge by 1. Use Add to increment it by arbitrary
// values.
Inc()
// Dec decrements the Gauge by 1. Use Sub to decrement it by arbitrary
// values.
Dec()
// Add adds the given value to the Gauge. (The value can be negative,
// resulting in a decrease of the Gauge.)
Add(float64)
// Sub subtracts the given value from the Gauge. (The value can be
// negative, resulting in an increase of the Gauge.)
Sub(float64)
}
type gauge struct {
name string
labels map[string]string
inner prometheus.Gauge
changes chan<- GaugeChange
}
func (g *gauge) Set(f float64) {
g.inner.Set(f)
g.signal(f)
}
func (g *gauge) Inc() {
g.inner.Inc()
g.signal(1)
}
func (g *gauge) Dec() {
g.inner.Dec()
g.signal(-1)
}
func (g *gauge) Add(f float64) {
g.inner.Add(f)
g.signal(f)
}
func (g *gauge) Sub(f float64) {
g.inner.Sub(f)
g.signal(-1 * f)
}
func (g *gauge) signal(f float64) {
if g.changes == nil {
return
}
g.changes <- GaugeChange{
Name: g.name,
Value: f,
Labels: g.labels,
}
}
// CountChange represents a change to counter. This instance contains the increment, not the resulting value.
type CountChange struct {
Name string
Increment float64
Labels map[string]string
}
// GaugeChange represents a change to a gauge. This instance contains the value that the gauge was changed by, not the
// resulting value.
type GaugeChange struct {
Name string
Value float64
Labels map[string]string
} | metrics/types.go | 0.778018 | 0.400661 | types.go | starcoder |
package fp
// MergeIntPtr takes two inputs: map[int]int and map[int]int and merge two maps and returns a new map[int]int.
func MergeIntPtr(map1, map2 map[*int]*int) map[*int]*int {
if map1 == nil && map2 == nil {
return map[*int]*int{}
}
newMap := make(map[*int]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntInt64Ptr takes two inputs: map[int]int64 and map[int]int64 and merge two maps and returns a new map[int]int64.
func MergeIntInt64Ptr(map1, map2 map[*int]*int64) map[*int]*int64 {
if map1 == nil && map2 == nil {
return map[*int]*int64{}
}
newMap := make(map[*int]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntInt32Ptr takes two inputs: map[int]int32 and map[int]int32 and merge two maps and returns a new map[int]int32.
func MergeIntInt32Ptr(map1, map2 map[*int]*int32) map[*int]*int32 {
if map1 == nil && map2 == nil {
return map[*int]*int32{}
}
newMap := make(map[*int]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntInt16Ptr takes two inputs: map[int]int16 and map[int]int16 and merge two maps and returns a new map[int]int16.
func MergeIntInt16Ptr(map1, map2 map[*int]*int16) map[*int]*int16 {
if map1 == nil && map2 == nil {
return map[*int]*int16{}
}
newMap := make(map[*int]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntInt8Ptr takes two inputs: map[int]int8 and map[int]int8 and merge two maps and returns a new map[int]int8.
func MergeIntInt8Ptr(map1, map2 map[*int]*int8) map[*int]*int8 {
if map1 == nil && map2 == nil {
return map[*int]*int8{}
}
newMap := make(map[*int]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntUintPtr takes two inputs: map[int]uint and map[int]uint and merge two maps and returns a new map[int]uint.
func MergeIntUintPtr(map1, map2 map[*int]*uint) map[*int]*uint {
if map1 == nil && map2 == nil {
return map[*int]*uint{}
}
newMap := make(map[*int]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntUint64Ptr takes two inputs: map[int]uint64 and map[int]uint64 and merge two maps and returns a new map[int]uint64.
func MergeIntUint64Ptr(map1, map2 map[*int]*uint64) map[*int]*uint64 {
if map1 == nil && map2 == nil {
return map[*int]*uint64{}
}
newMap := make(map[*int]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntUint32Ptr takes two inputs: map[int]uint32 and map[int]uint32 and merge two maps and returns a new map[int]uint32.
func MergeIntUint32Ptr(map1, map2 map[*int]*uint32) map[*int]*uint32 {
if map1 == nil && map2 == nil {
return map[*int]*uint32{}
}
newMap := make(map[*int]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntUint16Ptr takes two inputs: map[int]uint16 and map[int]uint16 and merge two maps and returns a new map[int]uint16.
func MergeIntUint16Ptr(map1, map2 map[*int]*uint16) map[*int]*uint16 {
if map1 == nil && map2 == nil {
return map[*int]*uint16{}
}
newMap := make(map[*int]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntUint8Ptr takes two inputs: map[int]uint8 and map[int]uint8 and merge two maps and returns a new map[int]uint8.
func MergeIntUint8Ptr(map1, map2 map[*int]*uint8) map[*int]*uint8 {
if map1 == nil && map2 == nil {
return map[*int]*uint8{}
}
newMap := make(map[*int]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntStrPtr takes two inputs: map[int]string and map[int]string and merge two maps and returns a new map[int]string.
func MergeIntStrPtr(map1, map2 map[*int]*string) map[*int]*string {
if map1 == nil && map2 == nil {
return map[*int]*string{}
}
newMap := make(map[*int]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntBoolPtr takes two inputs: map[int]bool and map[int]bool and merge two maps and returns a new map[int]bool.
func MergeIntBoolPtr(map1, map2 map[*int]*bool) map[*int]*bool {
if map1 == nil && map2 == nil {
return map[*int]*bool{}
}
newMap := make(map[*int]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntFloat32Ptr takes two inputs: map[int]float32 and map[int]float32 and merge two maps and returns a new map[int]float32.
func MergeIntFloat32Ptr(map1, map2 map[*int]*float32) map[*int]*float32 {
if map1 == nil && map2 == nil {
return map[*int]*float32{}
}
newMap := make(map[*int]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeIntFloat64Ptr takes two inputs: map[int]float64 and map[int]float64 and merge two maps and returns a new map[int]float64.
func MergeIntFloat64Ptr(map1, map2 map[*int]*float64) map[*int]*float64 {
if map1 == nil && map2 == nil {
return map[*int]*float64{}
}
newMap := make(map[*int]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64IntPtr takes two inputs: map[int64]int and map[int64]int and merge two maps and returns a new map[int64]int.
func MergeInt64IntPtr(map1, map2 map[*int64]*int) map[*int64]*int {
if map1 == nil && map2 == nil {
return map[*int64]*int{}
}
newMap := make(map[*int64]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Ptr takes two inputs: map[int64]int64 and map[int64]int64 and merge two maps and returns a new map[int64]int64.
func MergeInt64Ptr(map1, map2 map[*int64]*int64) map[*int64]*int64 {
if map1 == nil && map2 == nil {
return map[*int64]*int64{}
}
newMap := make(map[*int64]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Int32Ptr takes two inputs: map[int64]int32 and map[int64]int32 and merge two maps and returns a new map[int64]int32.
func MergeInt64Int32Ptr(map1, map2 map[*int64]*int32) map[*int64]*int32 {
if map1 == nil && map2 == nil {
return map[*int64]*int32{}
}
newMap := make(map[*int64]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Int16Ptr takes two inputs: map[int64]int16 and map[int64]int16 and merge two maps and returns a new map[int64]int16.
func MergeInt64Int16Ptr(map1, map2 map[*int64]*int16) map[*int64]*int16 {
if map1 == nil && map2 == nil {
return map[*int64]*int16{}
}
newMap := make(map[*int64]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Int8Ptr takes two inputs: map[int64]int8 and map[int64]int8 and merge two maps and returns a new map[int64]int8.
func MergeInt64Int8Ptr(map1, map2 map[*int64]*int8) map[*int64]*int8 {
if map1 == nil && map2 == nil {
return map[*int64]*int8{}
}
newMap := make(map[*int64]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64UintPtr takes two inputs: map[int64]uint and map[int64]uint and merge two maps and returns a new map[int64]uint.
func MergeInt64UintPtr(map1, map2 map[*int64]*uint) map[*int64]*uint {
if map1 == nil && map2 == nil {
return map[*int64]*uint{}
}
newMap := make(map[*int64]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Uint64Ptr takes two inputs: map[int64]uint64 and map[int64]uint64 and merge two maps and returns a new map[int64]uint64.
func MergeInt64Uint64Ptr(map1, map2 map[*int64]*uint64) map[*int64]*uint64 {
if map1 == nil && map2 == nil {
return map[*int64]*uint64{}
}
newMap := make(map[*int64]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Uint32Ptr takes two inputs: map[int64]uint32 and map[int64]uint32 and merge two maps and returns a new map[int64]uint32.
func MergeInt64Uint32Ptr(map1, map2 map[*int64]*uint32) map[*int64]*uint32 {
if map1 == nil && map2 == nil {
return map[*int64]*uint32{}
}
newMap := make(map[*int64]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Uint16Ptr takes two inputs: map[int64]uint16 and map[int64]uint16 and merge two maps and returns a new map[int64]uint16.
func MergeInt64Uint16Ptr(map1, map2 map[*int64]*uint16) map[*int64]*uint16 {
if map1 == nil && map2 == nil {
return map[*int64]*uint16{}
}
newMap := make(map[*int64]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Uint8Ptr takes two inputs: map[int64]uint8 and map[int64]uint8 and merge two maps and returns a new map[int64]uint8.
func MergeInt64Uint8Ptr(map1, map2 map[*int64]*uint8) map[*int64]*uint8 {
if map1 == nil && map2 == nil {
return map[*int64]*uint8{}
}
newMap := make(map[*int64]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64StrPtr takes two inputs: map[int64]string and map[int64]string and merge two maps and returns a new map[int64]string.
func MergeInt64StrPtr(map1, map2 map[*int64]*string) map[*int64]*string {
if map1 == nil && map2 == nil {
return map[*int64]*string{}
}
newMap := make(map[*int64]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64BoolPtr takes two inputs: map[int64]bool and map[int64]bool and merge two maps and returns a new map[int64]bool.
func MergeInt64BoolPtr(map1, map2 map[*int64]*bool) map[*int64]*bool {
if map1 == nil && map2 == nil {
return map[*int64]*bool{}
}
newMap := make(map[*int64]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Float32Ptr takes two inputs: map[int64]float32 and map[int64]float32 and merge two maps and returns a new map[int64]float32.
func MergeInt64Float32Ptr(map1, map2 map[*int64]*float32) map[*int64]*float32 {
if map1 == nil && map2 == nil {
return map[*int64]*float32{}
}
newMap := make(map[*int64]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt64Float64Ptr takes two inputs: map[int64]float64 and map[int64]float64 and merge two maps and returns a new map[int64]float64.
func MergeInt64Float64Ptr(map1, map2 map[*int64]*float64) map[*int64]*float64 {
if map1 == nil && map2 == nil {
return map[*int64]*float64{}
}
newMap := make(map[*int64]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32IntPtr takes two inputs: map[int32]int and map[int32]int and merge two maps and returns a new map[int32]int.
func MergeInt32IntPtr(map1, map2 map[*int32]*int) map[*int32]*int {
if map1 == nil && map2 == nil {
return map[*int32]*int{}
}
newMap := make(map[*int32]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Int64Ptr takes two inputs: map[int32]int64 and map[int32]int64 and merge two maps and returns a new map[int32]int64.
func MergeInt32Int64Ptr(map1, map2 map[*int32]*int64) map[*int32]*int64 {
if map1 == nil && map2 == nil {
return map[*int32]*int64{}
}
newMap := make(map[*int32]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Ptr takes two inputs: map[int32]int32 and map[int32]int32 and merge two maps and returns a new map[int32]int32.
func MergeInt32Ptr(map1, map2 map[*int32]*int32) map[*int32]*int32 {
if map1 == nil && map2 == nil {
return map[*int32]*int32{}
}
newMap := make(map[*int32]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Int16Ptr takes two inputs: map[int32]int16 and map[int32]int16 and merge two maps and returns a new map[int32]int16.
func MergeInt32Int16Ptr(map1, map2 map[*int32]*int16) map[*int32]*int16 {
if map1 == nil && map2 == nil {
return map[*int32]*int16{}
}
newMap := make(map[*int32]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Int8Ptr takes two inputs: map[int32]int8 and map[int32]int8 and merge two maps and returns a new map[int32]int8.
func MergeInt32Int8Ptr(map1, map2 map[*int32]*int8) map[*int32]*int8 {
if map1 == nil && map2 == nil {
return map[*int32]*int8{}
}
newMap := make(map[*int32]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32UintPtr takes two inputs: map[int32]uint and map[int32]uint and merge two maps and returns a new map[int32]uint.
func MergeInt32UintPtr(map1, map2 map[*int32]*uint) map[*int32]*uint {
if map1 == nil && map2 == nil {
return map[*int32]*uint{}
}
newMap := make(map[*int32]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Uint64Ptr takes two inputs: map[int32]uint64 and map[int32]uint64 and merge two maps and returns a new map[int32]uint64.
func MergeInt32Uint64Ptr(map1, map2 map[*int32]*uint64) map[*int32]*uint64 {
if map1 == nil && map2 == nil {
return map[*int32]*uint64{}
}
newMap := make(map[*int32]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Uint32Ptr takes two inputs: map[int32]uint32 and map[int32]uint32 and merge two maps and returns a new map[int32]uint32.
func MergeInt32Uint32Ptr(map1, map2 map[*int32]*uint32) map[*int32]*uint32 {
if map1 == nil && map2 == nil {
return map[*int32]*uint32{}
}
newMap := make(map[*int32]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Uint16Ptr takes two inputs: map[int32]uint16 and map[int32]uint16 and merge two maps and returns a new map[int32]uint16.
func MergeInt32Uint16Ptr(map1, map2 map[*int32]*uint16) map[*int32]*uint16 {
if map1 == nil && map2 == nil {
return map[*int32]*uint16{}
}
newMap := make(map[*int32]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Uint8Ptr takes two inputs: map[int32]uint8 and map[int32]uint8 and merge two maps and returns a new map[int32]uint8.
func MergeInt32Uint8Ptr(map1, map2 map[*int32]*uint8) map[*int32]*uint8 {
if map1 == nil && map2 == nil {
return map[*int32]*uint8{}
}
newMap := make(map[*int32]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32StrPtr takes two inputs: map[int32]string and map[int32]string and merge two maps and returns a new map[int32]string.
func MergeInt32StrPtr(map1, map2 map[*int32]*string) map[*int32]*string {
if map1 == nil && map2 == nil {
return map[*int32]*string{}
}
newMap := make(map[*int32]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32BoolPtr takes two inputs: map[int32]bool and map[int32]bool and merge two maps and returns a new map[int32]bool.
func MergeInt32BoolPtr(map1, map2 map[*int32]*bool) map[*int32]*bool {
if map1 == nil && map2 == nil {
return map[*int32]*bool{}
}
newMap := make(map[*int32]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Float32Ptr takes two inputs: map[int32]float32 and map[int32]float32 and merge two maps and returns a new map[int32]float32.
func MergeInt32Float32Ptr(map1, map2 map[*int32]*float32) map[*int32]*float32 {
if map1 == nil && map2 == nil {
return map[*int32]*float32{}
}
newMap := make(map[*int32]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt32Float64Ptr takes two inputs: map[int32]float64 and map[int32]float64 and merge two maps and returns a new map[int32]float64.
func MergeInt32Float64Ptr(map1, map2 map[*int32]*float64) map[*int32]*float64 {
if map1 == nil && map2 == nil {
return map[*int32]*float64{}
}
newMap := make(map[*int32]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16IntPtr takes two inputs: map[int16]int and map[int16]int and merge two maps and returns a new map[int16]int.
func MergeInt16IntPtr(map1, map2 map[*int16]*int) map[*int16]*int {
if map1 == nil && map2 == nil {
return map[*int16]*int{}
}
newMap := make(map[*int16]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Int64Ptr takes two inputs: map[int16]int64 and map[int16]int64 and merge two maps and returns a new map[int16]int64.
func MergeInt16Int64Ptr(map1, map2 map[*int16]*int64) map[*int16]*int64 {
if map1 == nil && map2 == nil {
return map[*int16]*int64{}
}
newMap := make(map[*int16]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Int32Ptr takes two inputs: map[int16]int32 and map[int16]int32 and merge two maps and returns a new map[int16]int32.
func MergeInt16Int32Ptr(map1, map2 map[*int16]*int32) map[*int16]*int32 {
if map1 == nil && map2 == nil {
return map[*int16]*int32{}
}
newMap := make(map[*int16]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Ptr takes two inputs: map[int16]int16 and map[int16]int16 and merge two maps and returns a new map[int16]int16.
func MergeInt16Ptr(map1, map2 map[*int16]*int16) map[*int16]*int16 {
if map1 == nil && map2 == nil {
return map[*int16]*int16{}
}
newMap := make(map[*int16]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Int8Ptr takes two inputs: map[int16]int8 and map[int16]int8 and merge two maps and returns a new map[int16]int8.
func MergeInt16Int8Ptr(map1, map2 map[*int16]*int8) map[*int16]*int8 {
if map1 == nil && map2 == nil {
return map[*int16]*int8{}
}
newMap := make(map[*int16]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16UintPtr takes two inputs: map[int16]uint and map[int16]uint and merge two maps and returns a new map[int16]uint.
func MergeInt16UintPtr(map1, map2 map[*int16]*uint) map[*int16]*uint {
if map1 == nil && map2 == nil {
return map[*int16]*uint{}
}
newMap := make(map[*int16]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Uint64Ptr takes two inputs: map[int16]uint64 and map[int16]uint64 and merge two maps and returns a new map[int16]uint64.
func MergeInt16Uint64Ptr(map1, map2 map[*int16]*uint64) map[*int16]*uint64 {
if map1 == nil && map2 == nil {
return map[*int16]*uint64{}
}
newMap := make(map[*int16]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Uint32Ptr takes two inputs: map[int16]uint32 and map[int16]uint32 and merge two maps and returns a new map[int16]uint32.
func MergeInt16Uint32Ptr(map1, map2 map[*int16]*uint32) map[*int16]*uint32 {
if map1 == nil && map2 == nil {
return map[*int16]*uint32{}
}
newMap := make(map[*int16]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Uint16Ptr takes two inputs: map[int16]uint16 and map[int16]uint16 and merge two maps and returns a new map[int16]uint16.
func MergeInt16Uint16Ptr(map1, map2 map[*int16]*uint16) map[*int16]*uint16 {
if map1 == nil && map2 == nil {
return map[*int16]*uint16{}
}
newMap := make(map[*int16]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Uint8Ptr takes two inputs: map[int16]uint8 and map[int16]uint8 and merge two maps and returns a new map[int16]uint8.
func MergeInt16Uint8Ptr(map1, map2 map[*int16]*uint8) map[*int16]*uint8 {
if map1 == nil && map2 == nil {
return map[*int16]*uint8{}
}
newMap := make(map[*int16]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16StrPtr takes two inputs: map[int16]string and map[int16]string and merge two maps and returns a new map[int16]string.
func MergeInt16StrPtr(map1, map2 map[*int16]*string) map[*int16]*string {
if map1 == nil && map2 == nil {
return map[*int16]*string{}
}
newMap := make(map[*int16]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16BoolPtr takes two inputs: map[int16]bool and map[int16]bool and merge two maps and returns a new map[int16]bool.
func MergeInt16BoolPtr(map1, map2 map[*int16]*bool) map[*int16]*bool {
if map1 == nil && map2 == nil {
return map[*int16]*bool{}
}
newMap := make(map[*int16]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Float32Ptr takes two inputs: map[int16]float32 and map[int16]float32 and merge two maps and returns a new map[int16]float32.
func MergeInt16Float32Ptr(map1, map2 map[*int16]*float32) map[*int16]*float32 {
if map1 == nil && map2 == nil {
return map[*int16]*float32{}
}
newMap := make(map[*int16]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt16Float64Ptr takes two inputs: map[int16]float64 and map[int16]float64 and merge two maps and returns a new map[int16]float64.
func MergeInt16Float64Ptr(map1, map2 map[*int16]*float64) map[*int16]*float64 {
if map1 == nil && map2 == nil {
return map[*int16]*float64{}
}
newMap := make(map[*int16]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8IntPtr takes two inputs: map[int8]int and map[int8]int and merge two maps and returns a new map[int8]int.
func MergeInt8IntPtr(map1, map2 map[*int8]*int) map[*int8]*int {
if map1 == nil && map2 == nil {
return map[*int8]*int{}
}
newMap := make(map[*int8]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Int64Ptr takes two inputs: map[int8]int64 and map[int8]int64 and merge two maps and returns a new map[int8]int64.
func MergeInt8Int64Ptr(map1, map2 map[*int8]*int64) map[*int8]*int64 {
if map1 == nil && map2 == nil {
return map[*int8]*int64{}
}
newMap := make(map[*int8]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Int32Ptr takes two inputs: map[int8]int32 and map[int8]int32 and merge two maps and returns a new map[int8]int32.
func MergeInt8Int32Ptr(map1, map2 map[*int8]*int32) map[*int8]*int32 {
if map1 == nil && map2 == nil {
return map[*int8]*int32{}
}
newMap := make(map[*int8]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Int16Ptr takes two inputs: map[int8]int16 and map[int8]int16 and merge two maps and returns a new map[int8]int16.
func MergeInt8Int16Ptr(map1, map2 map[*int8]*int16) map[*int8]*int16 {
if map1 == nil && map2 == nil {
return map[*int8]*int16{}
}
newMap := make(map[*int8]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Ptr takes two inputs: map[int8]int8 and map[int8]int8 and merge two maps and returns a new map[int8]int8.
func MergeInt8Ptr(map1, map2 map[*int8]*int8) map[*int8]*int8 {
if map1 == nil && map2 == nil {
return map[*int8]*int8{}
}
newMap := make(map[*int8]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8UintPtr takes two inputs: map[int8]uint and map[int8]uint and merge two maps and returns a new map[int8]uint.
func MergeInt8UintPtr(map1, map2 map[*int8]*uint) map[*int8]*uint {
if map1 == nil && map2 == nil {
return map[*int8]*uint{}
}
newMap := make(map[*int8]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Uint64Ptr takes two inputs: map[int8]uint64 and map[int8]uint64 and merge two maps and returns a new map[int8]uint64.
func MergeInt8Uint64Ptr(map1, map2 map[*int8]*uint64) map[*int8]*uint64 {
if map1 == nil && map2 == nil {
return map[*int8]*uint64{}
}
newMap := make(map[*int8]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Uint32Ptr takes two inputs: map[int8]uint32 and map[int8]uint32 and merge two maps and returns a new map[int8]uint32.
func MergeInt8Uint32Ptr(map1, map2 map[*int8]*uint32) map[*int8]*uint32 {
if map1 == nil && map2 == nil {
return map[*int8]*uint32{}
}
newMap := make(map[*int8]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Uint16Ptr takes two inputs: map[int8]uint16 and map[int8]uint16 and merge two maps and returns a new map[int8]uint16.
func MergeInt8Uint16Ptr(map1, map2 map[*int8]*uint16) map[*int8]*uint16 {
if map1 == nil && map2 == nil {
return map[*int8]*uint16{}
}
newMap := make(map[*int8]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Uint8Ptr takes two inputs: map[int8]uint8 and map[int8]uint8 and merge two maps and returns a new map[int8]uint8.
func MergeInt8Uint8Ptr(map1, map2 map[*int8]*uint8) map[*int8]*uint8 {
if map1 == nil && map2 == nil {
return map[*int8]*uint8{}
}
newMap := make(map[*int8]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8StrPtr takes two inputs: map[int8]string and map[int8]string and merge two maps and returns a new map[int8]string.
func MergeInt8StrPtr(map1, map2 map[*int8]*string) map[*int8]*string {
if map1 == nil && map2 == nil {
return map[*int8]*string{}
}
newMap := make(map[*int8]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8BoolPtr takes two inputs: map[int8]bool and map[int8]bool and merge two maps and returns a new map[int8]bool.
func MergeInt8BoolPtr(map1, map2 map[*int8]*bool) map[*int8]*bool {
if map1 == nil && map2 == nil {
return map[*int8]*bool{}
}
newMap := make(map[*int8]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Float32Ptr takes two inputs: map[int8]float32 and map[int8]float32 and merge two maps and returns a new map[int8]float32.
func MergeInt8Float32Ptr(map1, map2 map[*int8]*float32) map[*int8]*float32 {
if map1 == nil && map2 == nil {
return map[*int8]*float32{}
}
newMap := make(map[*int8]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeInt8Float64Ptr takes two inputs: map[int8]float64 and map[int8]float64 and merge two maps and returns a new map[int8]float64.
func MergeInt8Float64Ptr(map1, map2 map[*int8]*float64) map[*int8]*float64 {
if map1 == nil && map2 == nil {
return map[*int8]*float64{}
}
newMap := make(map[*int8]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintIntPtr takes two inputs: map[uint]int and map[uint]int and merge two maps and returns a new map[uint]int.
func MergeUintIntPtr(map1, map2 map[*uint]*int) map[*uint]*int {
if map1 == nil && map2 == nil {
return map[*uint]*int{}
}
newMap := make(map[*uint]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintInt64Ptr takes two inputs: map[uint]int64 and map[uint]int64 and merge two maps and returns a new map[uint]int64.
func MergeUintInt64Ptr(map1, map2 map[*uint]*int64) map[*uint]*int64 {
if map1 == nil && map2 == nil {
return map[*uint]*int64{}
}
newMap := make(map[*uint]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintInt32Ptr takes two inputs: map[uint]int32 and map[uint]int32 and merge two maps and returns a new map[uint]int32.
func MergeUintInt32Ptr(map1, map2 map[*uint]*int32) map[*uint]*int32 {
if map1 == nil && map2 == nil {
return map[*uint]*int32{}
}
newMap := make(map[*uint]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintInt16Ptr takes two inputs: map[uint]int16 and map[uint]int16 and merge two maps and returns a new map[uint]int16.
func MergeUintInt16Ptr(map1, map2 map[*uint]*int16) map[*uint]*int16 {
if map1 == nil && map2 == nil {
return map[*uint]*int16{}
}
newMap := make(map[*uint]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintInt8Ptr takes two inputs: map[uint]int8 and map[uint]int8 and merge two maps and returns a new map[uint]int8.
func MergeUintInt8Ptr(map1, map2 map[*uint]*int8) map[*uint]*int8 {
if map1 == nil && map2 == nil {
return map[*uint]*int8{}
}
newMap := make(map[*uint]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintPtr takes two inputs: map[uint]uint and map[uint]uint and merge two maps and returns a new map[uint]uint.
func MergeUintPtr(map1, map2 map[*uint]*uint) map[*uint]*uint {
if map1 == nil && map2 == nil {
return map[*uint]*uint{}
}
newMap := make(map[*uint]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintUint64Ptr takes two inputs: map[uint]uint64 and map[uint]uint64 and merge two maps and returns a new map[uint]uint64.
func MergeUintUint64Ptr(map1, map2 map[*uint]*uint64) map[*uint]*uint64 {
if map1 == nil && map2 == nil {
return map[*uint]*uint64{}
}
newMap := make(map[*uint]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintUint32Ptr takes two inputs: map[uint]uint32 and map[uint]uint32 and merge two maps and returns a new map[uint]uint32.
func MergeUintUint32Ptr(map1, map2 map[*uint]*uint32) map[*uint]*uint32 {
if map1 == nil && map2 == nil {
return map[*uint]*uint32{}
}
newMap := make(map[*uint]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintUint16Ptr takes two inputs: map[uint]uint16 and map[uint]uint16 and merge two maps and returns a new map[uint]uint16.
func MergeUintUint16Ptr(map1, map2 map[*uint]*uint16) map[*uint]*uint16 {
if map1 == nil && map2 == nil {
return map[*uint]*uint16{}
}
newMap := make(map[*uint]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintUint8Ptr takes two inputs: map[uint]uint8 and map[uint]uint8 and merge two maps and returns a new map[uint]uint8.
func MergeUintUint8Ptr(map1, map2 map[*uint]*uint8) map[*uint]*uint8 {
if map1 == nil && map2 == nil {
return map[*uint]*uint8{}
}
newMap := make(map[*uint]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintStrPtr takes two inputs: map[uint]string and map[uint]string and merge two maps and returns a new map[uint]string.
func MergeUintStrPtr(map1, map2 map[*uint]*string) map[*uint]*string {
if map1 == nil && map2 == nil {
return map[*uint]*string{}
}
newMap := make(map[*uint]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintBoolPtr takes two inputs: map[uint]bool and map[uint]bool and merge two maps and returns a new map[uint]bool.
func MergeUintBoolPtr(map1, map2 map[*uint]*bool) map[*uint]*bool {
if map1 == nil && map2 == nil {
return map[*uint]*bool{}
}
newMap := make(map[*uint]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintFloat32Ptr takes two inputs: map[uint]float32 and map[uint]float32 and merge two maps and returns a new map[uint]float32.
func MergeUintFloat32Ptr(map1, map2 map[*uint]*float32) map[*uint]*float32 {
if map1 == nil && map2 == nil {
return map[*uint]*float32{}
}
newMap := make(map[*uint]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUintFloat64Ptr takes two inputs: map[uint]float64 and map[uint]float64 and merge two maps and returns a new map[uint]float64.
func MergeUintFloat64Ptr(map1, map2 map[*uint]*float64) map[*uint]*float64 {
if map1 == nil && map2 == nil {
return map[*uint]*float64{}
}
newMap := make(map[*uint]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64IntPtr takes two inputs: map[uint64]int and map[uint64]int and merge two maps and returns a new map[uint64]int.
func MergeUint64IntPtr(map1, map2 map[*uint64]*int) map[*uint64]*int {
if map1 == nil && map2 == nil {
return map[*uint64]*int{}
}
newMap := make(map[*uint64]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Int64Ptr takes two inputs: map[uint64]int64 and map[uint64]int64 and merge two maps and returns a new map[uint64]int64.
func MergeUint64Int64Ptr(map1, map2 map[*uint64]*int64) map[*uint64]*int64 {
if map1 == nil && map2 == nil {
return map[*uint64]*int64{}
}
newMap := make(map[*uint64]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Int32Ptr takes two inputs: map[uint64]int32 and map[uint64]int32 and merge two maps and returns a new map[uint64]int32.
func MergeUint64Int32Ptr(map1, map2 map[*uint64]*int32) map[*uint64]*int32 {
if map1 == nil && map2 == nil {
return map[*uint64]*int32{}
}
newMap := make(map[*uint64]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Int16Ptr takes two inputs: map[uint64]int16 and map[uint64]int16 and merge two maps and returns a new map[uint64]int16.
func MergeUint64Int16Ptr(map1, map2 map[*uint64]*int16) map[*uint64]*int16 {
if map1 == nil && map2 == nil {
return map[*uint64]*int16{}
}
newMap := make(map[*uint64]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Int8Ptr takes two inputs: map[uint64]int8 and map[uint64]int8 and merge two maps and returns a new map[uint64]int8.
func MergeUint64Int8Ptr(map1, map2 map[*uint64]*int8) map[*uint64]*int8 {
if map1 == nil && map2 == nil {
return map[*uint64]*int8{}
}
newMap := make(map[*uint64]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64UintPtr takes two inputs: map[uint64]uint and map[uint64]uint and merge two maps and returns a new map[uint64]uint.
func MergeUint64UintPtr(map1, map2 map[*uint64]*uint) map[*uint64]*uint {
if map1 == nil && map2 == nil {
return map[*uint64]*uint{}
}
newMap := make(map[*uint64]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Ptr takes two inputs: map[uint64]uint64 and map[uint64]uint64 and merge two maps and returns a new map[uint64]uint64.
func MergeUint64Ptr(map1, map2 map[*uint64]*uint64) map[*uint64]*uint64 {
if map1 == nil && map2 == nil {
return map[*uint64]*uint64{}
}
newMap := make(map[*uint64]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Uint32Ptr takes two inputs: map[uint64]uint32 and map[uint64]uint32 and merge two maps and returns a new map[uint64]uint32.
func MergeUint64Uint32Ptr(map1, map2 map[*uint64]*uint32) map[*uint64]*uint32 {
if map1 == nil && map2 == nil {
return map[*uint64]*uint32{}
}
newMap := make(map[*uint64]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Uint16Ptr takes two inputs: map[uint64]uint16 and map[uint64]uint16 and merge two maps and returns a new map[uint64]uint16.
func MergeUint64Uint16Ptr(map1, map2 map[*uint64]*uint16) map[*uint64]*uint16 {
if map1 == nil && map2 == nil {
return map[*uint64]*uint16{}
}
newMap := make(map[*uint64]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Uint8Ptr takes two inputs: map[uint64]uint8 and map[uint64]uint8 and merge two maps and returns a new map[uint64]uint8.
func MergeUint64Uint8Ptr(map1, map2 map[*uint64]*uint8) map[*uint64]*uint8 {
if map1 == nil && map2 == nil {
return map[*uint64]*uint8{}
}
newMap := make(map[*uint64]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64StrPtr takes two inputs: map[uint64]string and map[uint64]string and merge two maps and returns a new map[uint64]string.
func MergeUint64StrPtr(map1, map2 map[*uint64]*string) map[*uint64]*string {
if map1 == nil && map2 == nil {
return map[*uint64]*string{}
}
newMap := make(map[*uint64]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64BoolPtr takes two inputs: map[uint64]bool and map[uint64]bool and merge two maps and returns a new map[uint64]bool.
func MergeUint64BoolPtr(map1, map2 map[*uint64]*bool) map[*uint64]*bool {
if map1 == nil && map2 == nil {
return map[*uint64]*bool{}
}
newMap := make(map[*uint64]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Float32Ptr takes two inputs: map[uint64]float32 and map[uint64]float32 and merge two maps and returns a new map[uint64]float32.
func MergeUint64Float32Ptr(map1, map2 map[*uint64]*float32) map[*uint64]*float32 {
if map1 == nil && map2 == nil {
return map[*uint64]*float32{}
}
newMap := make(map[*uint64]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint64Float64Ptr takes two inputs: map[uint64]float64 and map[uint64]float64 and merge two maps and returns a new map[uint64]float64.
func MergeUint64Float64Ptr(map1, map2 map[*uint64]*float64) map[*uint64]*float64 {
if map1 == nil && map2 == nil {
return map[*uint64]*float64{}
}
newMap := make(map[*uint64]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32IntPtr takes two inputs: map[uint32]int and map[uint32]int and merge two maps and returns a new map[uint32]int.
func MergeUint32IntPtr(map1, map2 map[*uint32]*int) map[*uint32]*int {
if map1 == nil && map2 == nil {
return map[*uint32]*int{}
}
newMap := make(map[*uint32]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Int64Ptr takes two inputs: map[uint32]int64 and map[uint32]int64 and merge two maps and returns a new map[uint32]int64.
func MergeUint32Int64Ptr(map1, map2 map[*uint32]*int64) map[*uint32]*int64 {
if map1 == nil && map2 == nil {
return map[*uint32]*int64{}
}
newMap := make(map[*uint32]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Int32Ptr takes two inputs: map[uint32]int32 and map[uint32]int32 and merge two maps and returns a new map[uint32]int32.
func MergeUint32Int32Ptr(map1, map2 map[*uint32]*int32) map[*uint32]*int32 {
if map1 == nil && map2 == nil {
return map[*uint32]*int32{}
}
newMap := make(map[*uint32]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Int16Ptr takes two inputs: map[uint32]int16 and map[uint32]int16 and merge two maps and returns a new map[uint32]int16.
func MergeUint32Int16Ptr(map1, map2 map[*uint32]*int16) map[*uint32]*int16 {
if map1 == nil && map2 == nil {
return map[*uint32]*int16{}
}
newMap := make(map[*uint32]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Int8Ptr takes two inputs: map[uint32]int8 and map[uint32]int8 and merge two maps and returns a new map[uint32]int8.
func MergeUint32Int8Ptr(map1, map2 map[*uint32]*int8) map[*uint32]*int8 {
if map1 == nil && map2 == nil {
return map[*uint32]*int8{}
}
newMap := make(map[*uint32]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32UintPtr takes two inputs: map[uint32]uint and map[uint32]uint and merge two maps and returns a new map[uint32]uint.
func MergeUint32UintPtr(map1, map2 map[*uint32]*uint) map[*uint32]*uint {
if map1 == nil && map2 == nil {
return map[*uint32]*uint{}
}
newMap := make(map[*uint32]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Uint64Ptr takes two inputs: map[uint32]uint64 and map[uint32]uint64 and merge two maps and returns a new map[uint32]uint64.
func MergeUint32Uint64Ptr(map1, map2 map[*uint32]*uint64) map[*uint32]*uint64 {
if map1 == nil && map2 == nil {
return map[*uint32]*uint64{}
}
newMap := make(map[*uint32]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Ptr takes two inputs: map[uint32]uint32 and map[uint32]uint32 and merge two maps and returns a new map[uint32]uint32.
func MergeUint32Ptr(map1, map2 map[*uint32]*uint32) map[*uint32]*uint32 {
if map1 == nil && map2 == nil {
return map[*uint32]*uint32{}
}
newMap := make(map[*uint32]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Uint16Ptr takes two inputs: map[uint32]uint16 and map[uint32]uint16 and merge two maps and returns a new map[uint32]uint16.
func MergeUint32Uint16Ptr(map1, map2 map[*uint32]*uint16) map[*uint32]*uint16 {
if map1 == nil && map2 == nil {
return map[*uint32]*uint16{}
}
newMap := make(map[*uint32]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Uint8Ptr takes two inputs: map[uint32]uint8 and map[uint32]uint8 and merge two maps and returns a new map[uint32]uint8.
func MergeUint32Uint8Ptr(map1, map2 map[*uint32]*uint8) map[*uint32]*uint8 {
if map1 == nil && map2 == nil {
return map[*uint32]*uint8{}
}
newMap := make(map[*uint32]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32StrPtr takes two inputs: map[uint32]string and map[uint32]string and merge two maps and returns a new map[uint32]string.
func MergeUint32StrPtr(map1, map2 map[*uint32]*string) map[*uint32]*string {
if map1 == nil && map2 == nil {
return map[*uint32]*string{}
}
newMap := make(map[*uint32]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32BoolPtr takes two inputs: map[uint32]bool and map[uint32]bool and merge two maps and returns a new map[uint32]bool.
func MergeUint32BoolPtr(map1, map2 map[*uint32]*bool) map[*uint32]*bool {
if map1 == nil && map2 == nil {
return map[*uint32]*bool{}
}
newMap := make(map[*uint32]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Float32Ptr takes two inputs: map[uint32]float32 and map[uint32]float32 and merge two maps and returns a new map[uint32]float32.
func MergeUint32Float32Ptr(map1, map2 map[*uint32]*float32) map[*uint32]*float32 {
if map1 == nil && map2 == nil {
return map[*uint32]*float32{}
}
newMap := make(map[*uint32]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint32Float64Ptr takes two inputs: map[uint32]float64 and map[uint32]float64 and merge two maps and returns a new map[uint32]float64.
func MergeUint32Float64Ptr(map1, map2 map[*uint32]*float64) map[*uint32]*float64 {
if map1 == nil && map2 == nil {
return map[*uint32]*float64{}
}
newMap := make(map[*uint32]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16IntPtr takes two inputs: map[uint16]int and map[uint16]int and merge two maps and returns a new map[uint16]int.
func MergeUint16IntPtr(map1, map2 map[*uint16]*int) map[*uint16]*int {
if map1 == nil && map2 == nil {
return map[*uint16]*int{}
}
newMap := make(map[*uint16]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Int64Ptr takes two inputs: map[uint16]int64 and map[uint16]int64 and merge two maps and returns a new map[uint16]int64.
func MergeUint16Int64Ptr(map1, map2 map[*uint16]*int64) map[*uint16]*int64 {
if map1 == nil && map2 == nil {
return map[*uint16]*int64{}
}
newMap := make(map[*uint16]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Int32Ptr takes two inputs: map[uint16]int32 and map[uint16]int32 and merge two maps and returns a new map[uint16]int32.
func MergeUint16Int32Ptr(map1, map2 map[*uint16]*int32) map[*uint16]*int32 {
if map1 == nil && map2 == nil {
return map[*uint16]*int32{}
}
newMap := make(map[*uint16]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Int16Ptr takes two inputs: map[uint16]int16 and map[uint16]int16 and merge two maps and returns a new map[uint16]int16.
func MergeUint16Int16Ptr(map1, map2 map[*uint16]*int16) map[*uint16]*int16 {
if map1 == nil && map2 == nil {
return map[*uint16]*int16{}
}
newMap := make(map[*uint16]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Int8Ptr takes two inputs: map[uint16]int8 and map[uint16]int8 and merge two maps and returns a new map[uint16]int8.
func MergeUint16Int8Ptr(map1, map2 map[*uint16]*int8) map[*uint16]*int8 {
if map1 == nil && map2 == nil {
return map[*uint16]*int8{}
}
newMap := make(map[*uint16]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16UintPtr takes two inputs: map[uint16]uint and map[uint16]uint and merge two maps and returns a new map[uint16]uint.
func MergeUint16UintPtr(map1, map2 map[*uint16]*uint) map[*uint16]*uint {
if map1 == nil && map2 == nil {
return map[*uint16]*uint{}
}
newMap := make(map[*uint16]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Uint64Ptr takes two inputs: map[uint16]uint64 and map[uint16]uint64 and merge two maps and returns a new map[uint16]uint64.
func MergeUint16Uint64Ptr(map1, map2 map[*uint16]*uint64) map[*uint16]*uint64 {
if map1 == nil && map2 == nil {
return map[*uint16]*uint64{}
}
newMap := make(map[*uint16]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Uint32Ptr takes two inputs: map[uint16]uint32 and map[uint16]uint32 and merge two maps and returns a new map[uint16]uint32.
func MergeUint16Uint32Ptr(map1, map2 map[*uint16]*uint32) map[*uint16]*uint32 {
if map1 == nil && map2 == nil {
return map[*uint16]*uint32{}
}
newMap := make(map[*uint16]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Ptr takes two inputs: map[uint16]uint16 and map[uint16]uint16 and merge two maps and returns a new map[uint16]uint16.
func MergeUint16Ptr(map1, map2 map[*uint16]*uint16) map[*uint16]*uint16 {
if map1 == nil && map2 == nil {
return map[*uint16]*uint16{}
}
newMap := make(map[*uint16]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Uint8Ptr takes two inputs: map[uint16]uint8 and map[uint16]uint8 and merge two maps and returns a new map[uint16]uint8.
func MergeUint16Uint8Ptr(map1, map2 map[*uint16]*uint8) map[*uint16]*uint8 {
if map1 == nil && map2 == nil {
return map[*uint16]*uint8{}
}
newMap := make(map[*uint16]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16StrPtr takes two inputs: map[uint16]string and map[uint16]string and merge two maps and returns a new map[uint16]string.
func MergeUint16StrPtr(map1, map2 map[*uint16]*string) map[*uint16]*string {
if map1 == nil && map2 == nil {
return map[*uint16]*string{}
}
newMap := make(map[*uint16]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16BoolPtr takes two inputs: map[uint16]bool and map[uint16]bool and merge two maps and returns a new map[uint16]bool.
func MergeUint16BoolPtr(map1, map2 map[*uint16]*bool) map[*uint16]*bool {
if map1 == nil && map2 == nil {
return map[*uint16]*bool{}
}
newMap := make(map[*uint16]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Float32Ptr takes two inputs: map[uint16]float32 and map[uint16]float32 and merge two maps and returns a new map[uint16]float32.
func MergeUint16Float32Ptr(map1, map2 map[*uint16]*float32) map[*uint16]*float32 {
if map1 == nil && map2 == nil {
return map[*uint16]*float32{}
}
newMap := make(map[*uint16]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint16Float64Ptr takes two inputs: map[uint16]float64 and map[uint16]float64 and merge two maps and returns a new map[uint16]float64.
func MergeUint16Float64Ptr(map1, map2 map[*uint16]*float64) map[*uint16]*float64 {
if map1 == nil && map2 == nil {
return map[*uint16]*float64{}
}
newMap := make(map[*uint16]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8IntPtr takes two inputs: map[uint8]int and map[uint8]int and merge two maps and returns a new map[uint8]int.
func MergeUint8IntPtr(map1, map2 map[*uint8]*int) map[*uint8]*int {
if map1 == nil && map2 == nil {
return map[*uint8]*int{}
}
newMap := make(map[*uint8]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Int64Ptr takes two inputs: map[uint8]int64 and map[uint8]int64 and merge two maps and returns a new map[uint8]int64.
func MergeUint8Int64Ptr(map1, map2 map[*uint8]*int64) map[*uint8]*int64 {
if map1 == nil && map2 == nil {
return map[*uint8]*int64{}
}
newMap := make(map[*uint8]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Int32Ptr takes two inputs: map[uint8]int32 and map[uint8]int32 and merge two maps and returns a new map[uint8]int32.
func MergeUint8Int32Ptr(map1, map2 map[*uint8]*int32) map[*uint8]*int32 {
if map1 == nil && map2 == nil {
return map[*uint8]*int32{}
}
newMap := make(map[*uint8]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Int16Ptr takes two inputs: map[uint8]int16 and map[uint8]int16 and merge two maps and returns a new map[uint8]int16.
func MergeUint8Int16Ptr(map1, map2 map[*uint8]*int16) map[*uint8]*int16 {
if map1 == nil && map2 == nil {
return map[*uint8]*int16{}
}
newMap := make(map[*uint8]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Int8Ptr takes two inputs: map[uint8]int8 and map[uint8]int8 and merge two maps and returns a new map[uint8]int8.
func MergeUint8Int8Ptr(map1, map2 map[*uint8]*int8) map[*uint8]*int8 {
if map1 == nil && map2 == nil {
return map[*uint8]*int8{}
}
newMap := make(map[*uint8]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8UintPtr takes two inputs: map[uint8]uint and map[uint8]uint and merge two maps and returns a new map[uint8]uint.
func MergeUint8UintPtr(map1, map2 map[*uint8]*uint) map[*uint8]*uint {
if map1 == nil && map2 == nil {
return map[*uint8]*uint{}
}
newMap := make(map[*uint8]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Uint64Ptr takes two inputs: map[uint8]uint64 and map[uint8]uint64 and merge two maps and returns a new map[uint8]uint64.
func MergeUint8Uint64Ptr(map1, map2 map[*uint8]*uint64) map[*uint8]*uint64 {
if map1 == nil && map2 == nil {
return map[*uint8]*uint64{}
}
newMap := make(map[*uint8]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Uint32Ptr takes two inputs: map[uint8]uint32 and map[uint8]uint32 and merge two maps and returns a new map[uint8]uint32.
func MergeUint8Uint32Ptr(map1, map2 map[*uint8]*uint32) map[*uint8]*uint32 {
if map1 == nil && map2 == nil {
return map[*uint8]*uint32{}
}
newMap := make(map[*uint8]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Uint16Ptr takes two inputs: map[uint8]uint16 and map[uint8]uint16 and merge two maps and returns a new map[uint8]uint16.
func MergeUint8Uint16Ptr(map1, map2 map[*uint8]*uint16) map[*uint8]*uint16 {
if map1 == nil && map2 == nil {
return map[*uint8]*uint16{}
}
newMap := make(map[*uint8]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Ptr takes two inputs: map[uint8]uint8 and map[uint8]uint8 and merge two maps and returns a new map[uint8]uint8.
func MergeUint8Ptr(map1, map2 map[*uint8]*uint8) map[*uint8]*uint8 {
if map1 == nil && map2 == nil {
return map[*uint8]*uint8{}
}
newMap := make(map[*uint8]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8StrPtr takes two inputs: map[uint8]string and map[uint8]string and merge two maps and returns a new map[uint8]string.
func MergeUint8StrPtr(map1, map2 map[*uint8]*string) map[*uint8]*string {
if map1 == nil && map2 == nil {
return map[*uint8]*string{}
}
newMap := make(map[*uint8]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8BoolPtr takes two inputs: map[uint8]bool and map[uint8]bool and merge two maps and returns a new map[uint8]bool.
func MergeUint8BoolPtr(map1, map2 map[*uint8]*bool) map[*uint8]*bool {
if map1 == nil && map2 == nil {
return map[*uint8]*bool{}
}
newMap := make(map[*uint8]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Float32Ptr takes two inputs: map[uint8]float32 and map[uint8]float32 and merge two maps and returns a new map[uint8]float32.
func MergeUint8Float32Ptr(map1, map2 map[*uint8]*float32) map[*uint8]*float32 {
if map1 == nil && map2 == nil {
return map[*uint8]*float32{}
}
newMap := make(map[*uint8]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeUint8Float64Ptr takes two inputs: map[uint8]float64 and map[uint8]float64 and merge two maps and returns a new map[uint8]float64.
func MergeUint8Float64Ptr(map1, map2 map[*uint8]*float64) map[*uint8]*float64 {
if map1 == nil && map2 == nil {
return map[*uint8]*float64{}
}
newMap := make(map[*uint8]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrIntPtr takes two inputs: map[string]int and map[string]int and merge two maps and returns a new map[string]int.
func MergeStrIntPtr(map1, map2 map[*string]*int) map[*string]*int {
if map1 == nil && map2 == nil {
return map[*string]*int{}
}
newMap := make(map[*string]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrInt64Ptr takes two inputs: map[string]int64 and map[string]int64 and merge two maps and returns a new map[string]int64.
func MergeStrInt64Ptr(map1, map2 map[*string]*int64) map[*string]*int64 {
if map1 == nil && map2 == nil {
return map[*string]*int64{}
}
newMap := make(map[*string]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrInt32Ptr takes two inputs: map[string]int32 and map[string]int32 and merge two maps and returns a new map[string]int32.
func MergeStrInt32Ptr(map1, map2 map[*string]*int32) map[*string]*int32 {
if map1 == nil && map2 == nil {
return map[*string]*int32{}
}
newMap := make(map[*string]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrInt16Ptr takes two inputs: map[string]int16 and map[string]int16 and merge two maps and returns a new map[string]int16.
func MergeStrInt16Ptr(map1, map2 map[*string]*int16) map[*string]*int16 {
if map1 == nil && map2 == nil {
return map[*string]*int16{}
}
newMap := make(map[*string]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrInt8Ptr takes two inputs: map[string]int8 and map[string]int8 and merge two maps and returns a new map[string]int8.
func MergeStrInt8Ptr(map1, map2 map[*string]*int8) map[*string]*int8 {
if map1 == nil && map2 == nil {
return map[*string]*int8{}
}
newMap := make(map[*string]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrUintPtr takes two inputs: map[string]uint and map[string]uint and merge two maps and returns a new map[string]uint.
func MergeStrUintPtr(map1, map2 map[*string]*uint) map[*string]*uint {
if map1 == nil && map2 == nil {
return map[*string]*uint{}
}
newMap := make(map[*string]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrUint64Ptr takes two inputs: map[string]uint64 and map[string]uint64 and merge two maps and returns a new map[string]uint64.
func MergeStrUint64Ptr(map1, map2 map[*string]*uint64) map[*string]*uint64 {
if map1 == nil && map2 == nil {
return map[*string]*uint64{}
}
newMap := make(map[*string]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrUint32Ptr takes two inputs: map[string]uint32 and map[string]uint32 and merge two maps and returns a new map[string]uint32.
func MergeStrUint32Ptr(map1, map2 map[*string]*uint32) map[*string]*uint32 {
if map1 == nil && map2 == nil {
return map[*string]*uint32{}
}
newMap := make(map[*string]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrUint16Ptr takes two inputs: map[string]uint16 and map[string]uint16 and merge two maps and returns a new map[string]uint16.
func MergeStrUint16Ptr(map1, map2 map[*string]*uint16) map[*string]*uint16 {
if map1 == nil && map2 == nil {
return map[*string]*uint16{}
}
newMap := make(map[*string]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrUint8Ptr takes two inputs: map[string]uint8 and map[string]uint8 and merge two maps and returns a new map[string]uint8.
func MergeStrUint8Ptr(map1, map2 map[*string]*uint8) map[*string]*uint8 {
if map1 == nil && map2 == nil {
return map[*string]*uint8{}
}
newMap := make(map[*string]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrPtr takes two inputs: map[string]string and map[string]string and merge two maps and returns a new map[string]string.
func MergeStrPtr(map1, map2 map[*string]*string) map[*string]*string {
if map1 == nil && map2 == nil {
return map[*string]*string{}
}
newMap := make(map[*string]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrBoolPtr takes two inputs: map[string]bool and map[string]bool and merge two maps and returns a new map[string]bool.
func MergeStrBoolPtr(map1, map2 map[*string]*bool) map[*string]*bool {
if map1 == nil && map2 == nil {
return map[*string]*bool{}
}
newMap := make(map[*string]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrFloat32Ptr takes two inputs: map[string]float32 and map[string]float32 and merge two maps and returns a new map[string]float32.
func MergeStrFloat32Ptr(map1, map2 map[*string]*float32) map[*string]*float32 {
if map1 == nil && map2 == nil {
return map[*string]*float32{}
}
newMap := make(map[*string]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeStrFloat64Ptr takes two inputs: map[string]float64 and map[string]float64 and merge two maps and returns a new map[string]float64.
func MergeStrFloat64Ptr(map1, map2 map[*string]*float64) map[*string]*float64 {
if map1 == nil && map2 == nil {
return map[*string]*float64{}
}
newMap := make(map[*string]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolIntPtr takes two inputs: map[bool]int and map[bool]int and merge two maps and returns a new map[bool]int.
func MergeBoolIntPtr(map1, map2 map[*bool]*int) map[*bool]*int {
if map1 == nil && map2 == nil {
return map[*bool]*int{}
}
newMap := make(map[*bool]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolInt64Ptr takes two inputs: map[bool]int64 and map[bool]int64 and merge two maps and returns a new map[bool]int64.
func MergeBoolInt64Ptr(map1, map2 map[*bool]*int64) map[*bool]*int64 {
if map1 == nil && map2 == nil {
return map[*bool]*int64{}
}
newMap := make(map[*bool]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolInt32Ptr takes two inputs: map[bool]int32 and map[bool]int32 and merge two maps and returns a new map[bool]int32.
func MergeBoolInt32Ptr(map1, map2 map[*bool]*int32) map[*bool]*int32 {
if map1 == nil && map2 == nil {
return map[*bool]*int32{}
}
newMap := make(map[*bool]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolInt16Ptr takes two inputs: map[bool]int16 and map[bool]int16 and merge two maps and returns a new map[bool]int16.
func MergeBoolInt16Ptr(map1, map2 map[*bool]*int16) map[*bool]*int16 {
if map1 == nil && map2 == nil {
return map[*bool]*int16{}
}
newMap := make(map[*bool]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolInt8Ptr takes two inputs: map[bool]int8 and map[bool]int8 and merge two maps and returns a new map[bool]int8.
func MergeBoolInt8Ptr(map1, map2 map[*bool]*int8) map[*bool]*int8 {
if map1 == nil && map2 == nil {
return map[*bool]*int8{}
}
newMap := make(map[*bool]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolUintPtr takes two inputs: map[bool]uint and map[bool]uint and merge two maps and returns a new map[bool]uint.
func MergeBoolUintPtr(map1, map2 map[*bool]*uint) map[*bool]*uint {
if map1 == nil && map2 == nil {
return map[*bool]*uint{}
}
newMap := make(map[*bool]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolUint64Ptr takes two inputs: map[bool]uint64 and map[bool]uint64 and merge two maps and returns a new map[bool]uint64.
func MergeBoolUint64Ptr(map1, map2 map[*bool]*uint64) map[*bool]*uint64 {
if map1 == nil && map2 == nil {
return map[*bool]*uint64{}
}
newMap := make(map[*bool]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolUint32Ptr takes two inputs: map[bool]uint32 and map[bool]uint32 and merge two maps and returns a new map[bool]uint32.
func MergeBoolUint32Ptr(map1, map2 map[*bool]*uint32) map[*bool]*uint32 {
if map1 == nil && map2 == nil {
return map[*bool]*uint32{}
}
newMap := make(map[*bool]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolUint16Ptr takes two inputs: map[bool]uint16 and map[bool]uint16 and merge two maps and returns a new map[bool]uint16.
func MergeBoolUint16Ptr(map1, map2 map[*bool]*uint16) map[*bool]*uint16 {
if map1 == nil && map2 == nil {
return map[*bool]*uint16{}
}
newMap := make(map[*bool]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolUint8Ptr takes two inputs: map[bool]uint8 and map[bool]uint8 and merge two maps and returns a new map[bool]uint8.
func MergeBoolUint8Ptr(map1, map2 map[*bool]*uint8) map[*bool]*uint8 {
if map1 == nil && map2 == nil {
return map[*bool]*uint8{}
}
newMap := make(map[*bool]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolStrPtr takes two inputs: map[bool]string and map[bool]string and merge two maps and returns a new map[bool]string.
func MergeBoolStrPtr(map1, map2 map[*bool]*string) map[*bool]*string {
if map1 == nil && map2 == nil {
return map[*bool]*string{}
}
newMap := make(map[*bool]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolPtr takes two inputs: map[bool]bool and map[bool]bool and merge two maps and returns a new map[bool]bool.
func MergeBoolPtr(map1, map2 map[*bool]*bool) map[*bool]*bool {
if map1 == nil && map2 == nil {
return map[*bool]*bool{}
}
newMap := make(map[*bool]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolFloat32Ptr takes two inputs: map[bool]float32 and map[bool]float32 and merge two maps and returns a new map[bool]float32.
func MergeBoolFloat32Ptr(map1, map2 map[*bool]*float32) map[*bool]*float32 {
if map1 == nil && map2 == nil {
return map[*bool]*float32{}
}
newMap := make(map[*bool]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeBoolFloat64Ptr takes two inputs: map[bool]float64 and map[bool]float64 and merge two maps and returns a new map[bool]float64.
func MergeBoolFloat64Ptr(map1, map2 map[*bool]*float64) map[*bool]*float64 {
if map1 == nil && map2 == nil {
return map[*bool]*float64{}
}
newMap := make(map[*bool]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32IntPtr takes two inputs: map[float32]int and map[float32]int and merge two maps and returns a new map[float32]int.
func MergeFloat32IntPtr(map1, map2 map[*float32]*int) map[*float32]*int {
if map1 == nil && map2 == nil {
return map[*float32]*int{}
}
newMap := make(map[*float32]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Int64Ptr takes two inputs: map[float32]int64 and map[float32]int64 and merge two maps and returns a new map[float32]int64.
func MergeFloat32Int64Ptr(map1, map2 map[*float32]*int64) map[*float32]*int64 {
if map1 == nil && map2 == nil {
return map[*float32]*int64{}
}
newMap := make(map[*float32]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Int32Ptr takes two inputs: map[float32]int32 and map[float32]int32 and merge two maps and returns a new map[float32]int32.
func MergeFloat32Int32Ptr(map1, map2 map[*float32]*int32) map[*float32]*int32 {
if map1 == nil && map2 == nil {
return map[*float32]*int32{}
}
newMap := make(map[*float32]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Int16Ptr takes two inputs: map[float32]int16 and map[float32]int16 and merge two maps and returns a new map[float32]int16.
func MergeFloat32Int16Ptr(map1, map2 map[*float32]*int16) map[*float32]*int16 {
if map1 == nil && map2 == nil {
return map[*float32]*int16{}
}
newMap := make(map[*float32]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Int8Ptr takes two inputs: map[float32]int8 and map[float32]int8 and merge two maps and returns a new map[float32]int8.
func MergeFloat32Int8Ptr(map1, map2 map[*float32]*int8) map[*float32]*int8 {
if map1 == nil && map2 == nil {
return map[*float32]*int8{}
}
newMap := make(map[*float32]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32UintPtr takes two inputs: map[float32]uint and map[float32]uint and merge two maps and returns a new map[float32]uint.
func MergeFloat32UintPtr(map1, map2 map[*float32]*uint) map[*float32]*uint {
if map1 == nil && map2 == nil {
return map[*float32]*uint{}
}
newMap := make(map[*float32]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Uint64Ptr takes two inputs: map[float32]uint64 and map[float32]uint64 and merge two maps and returns a new map[float32]uint64.
func MergeFloat32Uint64Ptr(map1, map2 map[*float32]*uint64) map[*float32]*uint64 {
if map1 == nil && map2 == nil {
return map[*float32]*uint64{}
}
newMap := make(map[*float32]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Uint32Ptr takes two inputs: map[float32]uint32 and map[float32]uint32 and merge two maps and returns a new map[float32]uint32.
func MergeFloat32Uint32Ptr(map1, map2 map[*float32]*uint32) map[*float32]*uint32 {
if map1 == nil && map2 == nil {
return map[*float32]*uint32{}
}
newMap := make(map[*float32]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Uint16Ptr takes two inputs: map[float32]uint16 and map[float32]uint16 and merge two maps and returns a new map[float32]uint16.
func MergeFloat32Uint16Ptr(map1, map2 map[*float32]*uint16) map[*float32]*uint16 {
if map1 == nil && map2 == nil {
return map[*float32]*uint16{}
}
newMap := make(map[*float32]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Uint8Ptr takes two inputs: map[float32]uint8 and map[float32]uint8 and merge two maps and returns a new map[float32]uint8.
func MergeFloat32Uint8Ptr(map1, map2 map[*float32]*uint8) map[*float32]*uint8 {
if map1 == nil && map2 == nil {
return map[*float32]*uint8{}
}
newMap := make(map[*float32]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32StrPtr takes two inputs: map[float32]string and map[float32]string and merge two maps and returns a new map[float32]string.
func MergeFloat32StrPtr(map1, map2 map[*float32]*string) map[*float32]*string {
if map1 == nil && map2 == nil {
return map[*float32]*string{}
}
newMap := make(map[*float32]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32BoolPtr takes two inputs: map[float32]bool and map[float32]bool and merge two maps and returns a new map[float32]bool.
func MergeFloat32BoolPtr(map1, map2 map[*float32]*bool) map[*float32]*bool {
if map1 == nil && map2 == nil {
return map[*float32]*bool{}
}
newMap := make(map[*float32]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Ptr takes two inputs: map[float32]float32 and map[float32]float32 and merge two maps and returns a new map[float32]float32.
func MergeFloat32Ptr(map1, map2 map[*float32]*float32) map[*float32]*float32 {
if map1 == nil && map2 == nil {
return map[*float32]*float32{}
}
newMap := make(map[*float32]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat32Float64Ptr takes two inputs: map[float32]float64 and map[float32]float64 and merge two maps and returns a new map[float32]float64.
func MergeFloat32Float64Ptr(map1, map2 map[*float32]*float64) map[*float32]*float64 {
if map1 == nil && map2 == nil {
return map[*float32]*float64{}
}
newMap := make(map[*float32]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64IntPtr takes two inputs: map[float64]int and map[float64]int and merge two maps and returns a new map[float64]int.
func MergeFloat64IntPtr(map1, map2 map[*float64]*int) map[*float64]*int {
if map1 == nil && map2 == nil {
return map[*float64]*int{}
}
newMap := make(map[*float64]*int)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Int64Ptr takes two inputs: map[float64]int64 and map[float64]int64 and merge two maps and returns a new map[float64]int64.
func MergeFloat64Int64Ptr(map1, map2 map[*float64]*int64) map[*float64]*int64 {
if map1 == nil && map2 == nil {
return map[*float64]*int64{}
}
newMap := make(map[*float64]*int64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Int32Ptr takes two inputs: map[float64]int32 and map[float64]int32 and merge two maps and returns a new map[float64]int32.
func MergeFloat64Int32Ptr(map1, map2 map[*float64]*int32) map[*float64]*int32 {
if map1 == nil && map2 == nil {
return map[*float64]*int32{}
}
newMap := make(map[*float64]*int32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Int16Ptr takes two inputs: map[float64]int16 and map[float64]int16 and merge two maps and returns a new map[float64]int16.
func MergeFloat64Int16Ptr(map1, map2 map[*float64]*int16) map[*float64]*int16 {
if map1 == nil && map2 == nil {
return map[*float64]*int16{}
}
newMap := make(map[*float64]*int16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Int8Ptr takes two inputs: map[float64]int8 and map[float64]int8 and merge two maps and returns a new map[float64]int8.
func MergeFloat64Int8Ptr(map1, map2 map[*float64]*int8) map[*float64]*int8 {
if map1 == nil && map2 == nil {
return map[*float64]*int8{}
}
newMap := make(map[*float64]*int8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64UintPtr takes two inputs: map[float64]uint and map[float64]uint and merge two maps and returns a new map[float64]uint.
func MergeFloat64UintPtr(map1, map2 map[*float64]*uint) map[*float64]*uint {
if map1 == nil && map2 == nil {
return map[*float64]*uint{}
}
newMap := make(map[*float64]*uint)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Uint64Ptr takes two inputs: map[float64]uint64 and map[float64]uint64 and merge two maps and returns a new map[float64]uint64.
func MergeFloat64Uint64Ptr(map1, map2 map[*float64]*uint64) map[*float64]*uint64 {
if map1 == nil && map2 == nil {
return map[*float64]*uint64{}
}
newMap := make(map[*float64]*uint64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Uint32Ptr takes two inputs: map[float64]uint32 and map[float64]uint32 and merge two maps and returns a new map[float64]uint32.
func MergeFloat64Uint32Ptr(map1, map2 map[*float64]*uint32) map[*float64]*uint32 {
if map1 == nil && map2 == nil {
return map[*float64]*uint32{}
}
newMap := make(map[*float64]*uint32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Uint16Ptr takes two inputs: map[float64]uint16 and map[float64]uint16 and merge two maps and returns a new map[float64]uint16.
func MergeFloat64Uint16Ptr(map1, map2 map[*float64]*uint16) map[*float64]*uint16 {
if map1 == nil && map2 == nil {
return map[*float64]*uint16{}
}
newMap := make(map[*float64]*uint16)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Uint8Ptr takes two inputs: map[float64]uint8 and map[float64]uint8 and merge two maps and returns a new map[float64]uint8.
func MergeFloat64Uint8Ptr(map1, map2 map[*float64]*uint8) map[*float64]*uint8 {
if map1 == nil && map2 == nil {
return map[*float64]*uint8{}
}
newMap := make(map[*float64]*uint8)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64StrPtr takes two inputs: map[float64]string and map[float64]string and merge two maps and returns a new map[float64]string.
func MergeFloat64StrPtr(map1, map2 map[*float64]*string) map[*float64]*string {
if map1 == nil && map2 == nil {
return map[*float64]*string{}
}
newMap := make(map[*float64]*string)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64BoolPtr takes two inputs: map[float64]bool and map[float64]bool and merge two maps and returns a new map[float64]bool.
func MergeFloat64BoolPtr(map1, map2 map[*float64]*bool) map[*float64]*bool {
if map1 == nil && map2 == nil {
return map[*float64]*bool{}
}
newMap := make(map[*float64]*bool)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Float32Ptr takes two inputs: map[float64]float32 and map[float64]float32 and merge two maps and returns a new map[float64]float32.
func MergeFloat64Float32Ptr(map1, map2 map[*float64]*float32) map[*float64]*float32 {
if map1 == nil && map2 == nil {
return map[*float64]*float32{}
}
newMap := make(map[*float64]*float32)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
// MergeFloat64Ptr takes two inputs: map[float64]float64 and map[float64]float64 and merge two maps and returns a new map[float64]float64.
func MergeFloat64Ptr(map1, map2 map[*float64]*float64) map[*float64]*float64 {
if map1 == nil && map2 == nil {
return map[*float64]*float64{}
}
newMap := make(map[*float64]*float64)
if map1 == nil {
for k, v := range map2 {
newMap[k] = v
}
return newMap
}
if map2 == nil {
for k, v := range map1 {
newMap[k] = v
}
return newMap
}
for k, v := range map1 {
newMap[k] = v
}
for k, v := range map2 {
newMap[k] = v
}
return newMap
} | fp/mergeptr.go | 0.656988 | 0.580709 | mergeptr.go | starcoder |
Bushing for the Box Joint Jig
https://woodgears.ca/box_joint/jig.html
*/
//-----------------------------------------------------------------------------
package main
import . "github.com/deadsy/sdfx/sdf"
//-----------------------------------------------------------------------------
// center hole
const ch_d = 0.755 * MillimetresPerInch
const ch_r = ch_d / 2.0
//-----------------------------------------------------------------------------
func bushing() SDF3 {
// R6-2RS 3/8 x 7/8 x 9/32 bearing
bearing_outer_od := (7.0 / 8.0) * MillimetresPerInch // outer diameter of outer race
//bearing_outer_id := 19.0 // inner diameter of outer race
bearing_inner_id := (3.0 / 8.0) * MillimetresPerInch // inner diameter of inner race
bearing_inner_od := 12.0 // outer diameter of inner race
bearing_thickness := (9.0 / 32.0) * MillimetresPerInch // bearing thickness
// Adjust clearance to give good interference fits for the bearing
clearance := 0.0
r0 := 2.3 // radius of central screw
r1 := (bearing_outer_od + bearing_inner_od) / 4.0
r2 := (bearing_inner_id / 2.0) - clearance
h0 := 3.0 // height of cap
h1 := h0 + bearing_thickness + 1.0
p := NewPolygon()
p.Add(r0, 0)
p.Add(r1, 0)
p.Add(r1, h0)
p.Add(r2, h0)
p.Add(r2, h1)
p.Add(r0, h1)
return Revolve3D(Polygon2D(p.Vertices()))
}
//-----------------------------------------------------------------------------
// 4 holes to attach the plate to the gear stack.
func plate_holes_2d() SDF2 {
d := 17.0
h := Circle2D(1.2)
s0 := Transform2D(h, Translate2d(V2{d, d}))
s1 := Transform2D(h, Translate2d(V2{-d, -d}))
s2 := Transform2D(h, Translate2d(V2{-d, d}))
s3 := Transform2D(h, Translate2d(V2{d, -d}))
return Union2D(s0, s1, s2, s3)
}
const rod_r = (1.0 / 16.0) * MillimetresPerInch * 1.10
func locking_rod() SDF3 {
l := 62.0
s0 := Circle2D(rod_r)
s1 := Box2D(V2{2 * rod_r, rod_r}, 0)
s1 = Transform2D(s1, Translate2d(V2{0, -0.5 * rod_r}))
s2 := Union2D(s0, s1)
return Extrude3D(s2, l)
}
func plate() SDF3 {
r := (16.0 * gear_module / 2.0) * 0.83
h := 5.0
// plate
s0 := Cylinder3D(h, r, 0)
// holes for attachment screws
s1 := Extrude3D(plate_holes_2d(), h)
// center hole
s2 := Cylinder3D(h, ch_r, 0)
// indent for locking rod
m := Translate3d(V3{0, 0, h/2 - rod_r}).Mul(RotateX(DtoR(-90.0)))
s3 := Transform3D(locking_rod(), m)
return Difference3D(s0, Union3D(s1, s2, s3))
}
//-----------------------------------------------------------------------------
var gear_module = 80.0 / 16.0
var pressure_angle = 20.0
var involute_facets = 10
func gears() SDF3 {
g_height := 10.0
// 12 tooth spur gear
g0_teeth := 12
g0_pd := float64(g0_teeth) * gear_module
g0_2d := InvoluteGear(
g0_teeth,
gear_module,
DtoR(pressure_angle),
0.0,
0.0,
g0_pd/2.0,
involute_facets,
)
g0 := Extrude3D(g0_2d, g_height)
// 16 tooth spur gear
g1_teeth := 16
g1_pd := float64(g1_teeth) * gear_module
g1_2d := InvoluteGear(
g1_teeth,
gear_module,
DtoR(pressure_angle),
0.0,
0.0,
g1_pd/2.0,
involute_facets,
)
g1 := Extrude3D(g1_2d, g_height)
s0 := Transform3D(g0, Translate3d(V3{0, 0, g_height / 2.0}))
s1 := Transform3D(g1, Translate3d(V3{0, 0, -g_height / 2.0}))
// center hole
s2 := Cylinder3D(2.0*g_height, ch_r, 0)
// holes for attachment screws
screw_depth := 10.0
s3 := Extrude3D(plate_holes_2d(), screw_depth)
s3 = Transform3D(s3, Translate3d(V3{0, 0, screw_depth/2.0 - g_height}))
return Difference3D(Union3D(s0, s1), Union3D(s2, s3))
}
//-----------------------------------------------------------------------------
func main() {
RenderSTL(bushing(), 100, "bushing.stl")
RenderSTL(gears(), 300, "gear.stl")
RenderSTL(plate(), 300, "plate.stl")
}
//----------------------------------------------------------------------------- | examples/bjj/main.go | 0.677687 | 0.411466 | main.go | starcoder |
package expression
import (
"fmt"
"math"
)
type binaryExpression struct {
first Expression
second Expression
calcFunc func(float64, float64) (float64, error)
format string
}
func (exp binaryExpression) Calculate(vals SymbolValues) (float64, error) {
var err error
firstValue, err := exp.first.Calculate(vals)
if err != nil {
return 0, err
}
secondValue, err := exp.second.Calculate(vals)
if err != nil {
return 0, err
}
return exp.calcFunc(firstValue, secondValue)
}
func (exp binaryExpression) RequiresSymbols() []string {
return mergeSymbols(exp.first.RequiresSymbols(), exp.second.RequiresSymbols())
}
func (exp binaryExpression) String() string {
return fmt.Sprintf(exp.format, exp.first.String(), exp.second.String())
}
// Addition creates an addition expression with the given expressions as its terms
func Addition(first, second Expression) Expression {
return binaryExpression{
first: first,
second: second,
calcFunc: func(x, y float64) (float64, error) { return x + y, nil },
format: "(%s + %s)",
}
}
// Subtraction creates a subtraction expression with the given expressions as its terms
func Subtraction(first, second Expression) Expression {
return binaryExpression{
first: first,
second: second,
calcFunc: func(x, y float64) (float64, error) { return x - y, nil },
format: "(%s - %s)",
}
}
// Multiplication creates a multiplication expression with the given expressions as its terms
func Multiplication(first, second Expression) Expression {
return binaryExpression{
first: first,
second: second,
calcFunc: func(x, y float64) (float64, error) { return x * y, nil },
format: "(%s * %s)",
}
}
// Division creates a division expression with the given expressions as its terms
func Division(first, second Expression) Expression {
return binaryExpression{
first: first,
second: second,
calcFunc: func(x, y float64) (float64, error) {
if result, ok := safeDivision(x, y); ok {
return result, nil
}
return 0, fmt.Errorf("Divide by zero error: %f / %f", x, y)
},
format: "(%s / %s)",
}
}
func safeDivision(x, y float64) (float64, bool) {
defer func() {
recover()
}()
return x / y, true
}
// Exponentiation creates an exponentiation expression with the given expressions as its terms
func Exponentiation(first, second Expression) Expression {
return binaryExpression{
first: first,
second: second,
calcFunc: func(x, y float64) (float64, error) { return math.Pow(x, y), nil },
format: "(%s ^ %s)",
}
}
// Logarithm creates a logarithm expression with the given expressions as its terms
func Logarithm(exponent, base Expression) Expression {
return binaryExpression{
first: exponent,
second: base,
calcFunc: func(x float64, y float64) (float64, error) {
if result, ok := safeDivision(math.Log(x), math.Log(y)); ok {
return result, nil
}
return 0, fmt.Errorf("Divide by zero error while calculating: %f log %f", x, y)
},
format: "(%s log %s)",
}
} | binary_expr.go | 0.820901 | 0.549399 | binary_expr.go | starcoder |
package crds
const PolicyCRD = `
{
"group": "kyverno.io",
"names": {
"kind": "Policy",
"listKind": "PolicyList",
"plural": "policies",
"shortNames": [
"pol"
],
"singular": "policy"
},
"scope": "Namespaced",
"versions": [
{
"additionalPrinterColumns": [
{
"jsonPath": ".spec.background",
"name": "Background",
"type": "string"
},
{
"jsonPath": ".spec.validationFailureAction",
"name": "Action",
"type": "string"
}
],
"name": "v1",
"schema": {
"openAPIV3Schema": {
"description": "Policy declares validation, mutation, and generation behaviors for matching resources. See: https://kyverno.io/docs/writing-policies/ for more information.",
"properties": {
"apiVersion": {
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
"type": "string"
},
"kind": {
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
"type": "string"
},
"metadata": {
"type": "object"
},
"spec": {
"description": "Spec defines policy behaviors and contains one or rules.",
"properties": {
"background": {
"description": "Background controls if rules are applied to existing resources during a background scan. Optional. Default value is \"true\". The value must be set to \"false\" if the policy rule uses variables that are only available in the admission review request (e.g. user name).",
"type": "boolean"
},
"rules": {
"description": "Rules is a list of Rule instances. A Policy contains multiple rules and each rule can validate, mutate, or generate resources.",
"items": {
"schema": {
"description": "Rule defines a validation, mutation, or generation control for matching resources. Each rules contains a match declaration to select resources, and an optional exclude declaration to specify which resources to exclude.",
"properties": {
"context": {
"description": "Context defines variables and data sources that can be used during rule execution.",
"items": {
"schema": {
"description": "ContextEntry adds variables and data sources to a rule Context. Either a ConfigMap reference or a APILookup must be provided.",
"properties": {
"apiCall": {
"description": "APICall defines an HTTP request to the Kubernetes API server. The JSON data retrieved is stored in the context.",
"properties": {
"jmesPath": {
"description": "JMESPath is an optional JSON Match Expression that can be used to transform the JSON response returned from the API server. For example a JMESPath of \"items | length(@)\" applied to the API server response to the URLPath \"/apis/apps/v1/deployments\" will return the total count of deployments across all namespaces.",
"type": "string"
},
"urlPath": {
"description": "URLPath is the URL path to be used in the HTTP GET request to the Kubernetes API server (e.g. \"/api/v1/namespaces\" or \"/apis/apps/v1/deployments\"). The format required is the same format used by the 'kubectl get --raw' command.",
"type": "string"
}
},
"required": [
"urlPath"
],
"type": "object"
},
"configMap": {
"description": "ConfigMap is the ConfigMap reference.",
"properties": {
"name": {
"description": "Name is the ConfigMap name.",
"type": "string"
},
"namespace": {
"description": "Namespace is the ConfigMap namespace.",
"type": "string"
}
},
"required": [
"name"
],
"type": "object"
},
"name": {
"description": "Name is the variable name.",
"type": "string"
}
},
"type": "object"
}
},
"type": "array"
},
"exclude": {
"description": "ExcludeResources defines when this policy rule should not be applied. The exclude criteria can include resource information (e.g. kind, name, namespace, labels) and admission review request information like the name or role.",
"properties": {
"clusterRoles": {
"description": "ClusterRoles is the list of cluster-wide role names for the user.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"resources": {
"description": "ResourceDescription contains information about the resource being created or modified.",
"properties": {
"annotations": {
"description": "Annotations is a map of annotations (key-value pairs of type string). Annotation keys and values support the wildcard characters \"*\" (matches zero or many characters) and \"?\" (matches at least one character).",
"type": "object"
},
"kinds": {
"description": "Kinds is a list of resource kinds.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"name": {
"description": "Name is the name of the resource. The name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
"type": "string"
},
"namespaceSelector": {
"description": "NamespaceSelector is a label selector for the resource namespace. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character).Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
"properties": {
"matchExpressions": {
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
"items": {
"schema": {
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
"properties": {
"key": {
"description": "key is the label key that the selector applies to.",
"type": "string"
},
"operator": {
"description": "operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.",
"type": "string"
},
"values": {
"description": "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
}
},
"required": [
"key",
"operator"
],
"type": "object"
}
},
"type": "array"
},
"matchLabels": {
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
"type": "object"
}
},
"type": "object"
},
"namespaces": {
"description": "Namespaces is a list of namespaces names. Each name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"selector": {
"description": "Selector is a label selector. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character). Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
"properties": {
"matchExpressions": {
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
"items": {
"schema": {
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
"properties": {
"key": {
"description": "key is the label key that the selector applies to.",
"type": "string"
},
"operator": {
"description": "operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.",
"type": "string"
},
"values": {
"description": "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
}
},
"required": [
"key",
"operator"
],
"type": "object"
}
},
"type": "array"
},
"matchLabels": {
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
"type": "object"
}
},
"type": "object"
}
},
"type": "object"
},
"roles": {
"description": "Roles is the list of namespaced role names for the user.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"subjects": {
"description": "Subjects is the list of subject names like users, user groups, and service accounts.",
"items": {
"schema": {
"description": "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.",
"properties": {
"apiGroup": {
"description": "APIGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.",
"type": "string"
},
"kind": {
"description": "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.",
"type": "string"
},
"name": {
"description": "Name of the object being referenced.",
"type": "string"
},
"namespace": {
"description": "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.",
"type": "string"
}
},
"required": [
"kind",
"name"
],
"type": "object"
}
},
"type": "array"
}
},
"type": "object"
},
"generate": {
"description": "Generation is used to create new resources.",
"properties": {
"apiVersion": {
"description": "APIVersion specifies resource apiVersion.",
"type": "string"
},
"clone": {
"description": "Clone specifies the source resource used to populate each generated resource. At most one of Data or Clone can be specified. If neither are provided, the generated resource will be created with default data only.",
"properties": {
"name": {
"description": "Name specifies name of the resource.",
"type": "string"
},
"namespace": {
"description": "Namespace specifies source resource namespace.",
"type": "string"
}
},
"type": "object"
},
"data": {
"description": "Data provides the resource declaration used to populate each generated resource. At most one of Data or Clone must be specified. If neither are provided, the generated resource will be created with default data only.",
"x-kubernetes-preserve-unknown-fields": true
},
"kind": {
"description": "Kind specifies resource kind.",
"type": "string"
},
"name": {
"description": "Name specifies the resource name.",
"type": "string"
},
"namespace": {
"description": "Namespace specifies resource namespace.",
"type": "string"
},
"synchronize": {
"description": "Synchronize controls if generated resources should be kept in-sync with their source resource. If Synchronize is set to \"true\" changes to generated resources will be overwritten with resource data from Data or the resource specified in the Clone declaration. Optional. Defaults to \"false\" if not specified.",
"type": "boolean"
}
},
"type": "object"
},
"match": {
"description": "MatchResources defines when this policy rule should be applied. The match criteria can include resource information (e.g. kind, name, namespace, labels) and admission review request information like the user name or role. At least one kind is required.",
"properties": {
"clusterRoles": {
"description": "ClusterRoles is the list of cluster-wide role names for the user.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"resources": {
"description": "ResourceDescription contains information about the resource being created or modified. Requires at least one tag to be specified when under MatchResources.",
"properties": {
"annotations": {
"description": "Annotations is a map of annotations (key-value pairs of type string). Annotation keys and values support the wildcard characters \"*\" (matches zero or many characters) and \"?\" (matches at least one character).",
"type": "object"
},
"kinds": {
"description": "Kinds is a list of resource kinds.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"name": {
"description": "Name is the name of the resource. The name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
"type": "string"
},
"namespaceSelector": {
"description": "NamespaceSelector is a label selector for the resource namespace. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character).Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
"properties": {
"matchExpressions": {
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
"items": {
"schema": {
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
"properties": {
"key": {
"description": "key is the label key that the selector applies to.",
"type": "string"
},
"operator": {
"description": "operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.",
"type": "string"
},
"values": {
"description": "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
}
},
"required": [
"key",
"operator"
],
"type": "object"
}
},
"type": "array"
},
"matchLabels": {
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
"type": "object"
}
},
"type": "object"
},
"namespaces": {
"description": "Namespaces is a list of namespaces names. Each name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"selector": {
"description": "Selector is a label selector. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character). Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
"properties": {
"matchExpressions": {
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
"items": {
"schema": {
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
"properties": {
"key": {
"description": "key is the label key that the selector applies to.",
"type": "string"
},
"operator": {
"description": "operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.",
"type": "string"
},
"values": {
"description": "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
}
},
"required": [
"key",
"operator"
],
"type": "object"
}
},
"type": "array"
},
"matchLabels": {
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
"type": "object"
}
},
"type": "object"
}
},
"type": "object"
},
"roles": {
"description": "Roles is the list of namespaced role names for the user.",
"items": {
"schema": {
"type": "string"
}
},
"type": "array"
},
"subjects": {
"description": "Subjects is the list of subject names like users, user groups, and service accounts.",
"items": {
"schema": {
"description": "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.",
"properties": {
"apiGroup": {
"description": "APIGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.",
"type": "string"
},
"kind": {
"description": "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.",
"type": "string"
},
"name": {
"description": "Name of the object being referenced.",
"type": "string"
},
"namespace": {
"description": "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.",
"type": "string"
}
},
"required": [
"kind",
"name"
],
"type": "object"
}
},
"type": "array"
}
},
"type": "object"
},
"mutate": {
"description": "Mutation is used to modify matching resources.",
"properties": {
"overlay": {
"description": "Overlay specifies an overlay pattern to modify resources. DEPRECATED. Use PatchStrategicMerge instead. Scheduled for removal in release 1.5+.",
"x-kubernetes-preserve-unknown-fields": true
},
"patchStrategicMerge": {
"description": "PatchStrategicMerge is a strategic merge patch used to modify resources. See https://kubernetes.io/docs/tasks/manage-kubernetes-objects/update-api-object-kubectl-patch/ and https://kubectl.docs.kubernetes.io/references/kustomize/patchesstrategicmerge/.",
"x-kubernetes-preserve-unknown-fields": true
},
"patches": {
"description": "Patches specifies a RFC 6902 JSON Patch to modify resources. DEPRECATED. Use PatchesJSON6902 instead. Scheduled for removal in release 1.5+.",
"items": {
"schema": {
"description": "Patch is a RFC 6902 JSON Patch. See: https://tools.ietf.org/html/rfc6902",
"properties": {
"op": {
"description": "Operation specifies operations supported by JSON Patch. i.e:- add, replace and delete.",
"type": "string"
},
"path": {
"description": "Path specifies path of the resource.",
"type": "string"
},
"value": {
"description": "Value specifies the value to be applied.",
"x-kubernetes-preserve-unknown-fields": true
}
},
"type": "object"
}
},
"nullable": true,
"type": "array",
"x-kubernetes-preserve-unknown-fields": true
},
"patchesJson6902": {
"description": "PatchesJSON6902 is a list of RFC 6902 JSON Patch declarations used to modify resources. See https://tools.ietf.org/html/rfc6902 and https://kubectl.docs.kubernetes.io/references/kustomize/patchesjson6902/.",
"type": "string"
}
},
"type": "object"
},
"name": {
"description": "Name is a label to identify the rule, It must be unique within the policy.",
"maxLength": 63,
"type": "string"
},
"preconditions": {
"description": "AnyAllConditions enable variable-based conditional rule execution. This is useful for finer control of when an rule is applied. A condition can reference object data using JMESPath notation. This too can be made to happen in a logical-manner where in some situation all the conditions need to pass and in some other situation, atleast one condition is enough to pass. For the sake of backwards compatibility, it can be populated with []kyverno.Condition.",
"x-kubernetes-preserve-unknown-fields": true
},
"validate": {
"description": "Validation is used to validate matching resources.",
"properties": {
"anyPattern": {
"description": "AnyPattern specifies list of validation patterns. At least one of the patterns must be satisfied for the validation rule to succeed.",
"x-kubernetes-preserve-unknown-fields": true
},
"deny": {
"description": "Deny defines conditions to fail the validation rule.",
"properties": {
"conditions": {
"description": "specifies the set of conditions to deny in a logical manner For the sake of backwards compatibility, it can be populated with []kyverno.Condition.",
"x-kubernetes-preserve-unknown-fields": true
}
},
"type": "object"
},
"message": {
"description": "Message specifies a custom message to be displayed on failure.",
"type": "string"
},
"pattern": {
"description": "Pattern specifies an overlay-style pattern used to check resources.",
"x-kubernetes-preserve-unknown-fields": true
}
},
"type": "object"
}
},
"type": "object"
}
},
"type": "array"
},
"validationFailureAction": {
"description": "ValidationFailureAction controls if a validation policy rule failure should disallow the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. The default value is \"audit\".",
"type": "string"
}
},
"type": "object"
},
"status": {
"description": "Status contains policy runtime information.",
"properties": {
"averageExecutionTime": {
"description": "AvgExecutionTime is the average time taken to process the policy rules on a resource.",
"type": "string"
},
"resourcesBlockedCount": {
"description": "ResourcesBlockedCount is the total count of admission review requests that were blocked by this policy.",
"type": "integer"
},
"resourcesGeneratedCount": {
"description": "ResourcesGeneratedCount is the total count of resources that were generated by this policy.",
"type": "integer"
},
"resourcesMutatedCount": {
"description": "ResourcesMutatedCount is the total count of resources that were mutated by this policy.",
"type": "integer"
},
"ruleStatus": {
"description": "Rules provides per rule statistics",
"items": {
"schema": {
"description": "RuleStats provides statistics for an individual rule within a policy.",
"properties": {
"appliedCount": {
"description": "AppliedCount is the total number of times this rule was applied.",
"type": "integer"
},
"averageExecutionTime": {
"description": "ExecutionTime is the average time taken to execute this rule.",
"type": "string"
},
"failedCount": {
"description": "FailedCount is the total count of policy error results for this rule.",
"type": "integer"
},
"resourcesBlockedCount": {
"description": "ResourcesBlockedCount is the total count of admission review requests that were blocked by this rule.",
"type": "integer"
},
"resourcesGeneratedCount": {
"description": "ResourcesGeneratedCount is the total count of resources that were generated by this rule.",
"type": "integer"
},
"resourcesMutatedCount": {
"description": "ResourcesMutatedCount is the total count of resources that were mutated by this rule.",
"type": "integer"
},
"ruleName": {
"description": "Name is the rule name.",
"type": "string"
},
"violationCount": {
"description": "ViolationCount is the total count of policy failure results for this rule.",
"type": "integer"
}
},
"required": [
"ruleName"
],
"type": "object"
}
},
"type": "array"
},
"rulesAppliedCount": {
"description": "RulesAppliedCount is the total number of times this policy was applied.",
"type": "integer"
},
"rulesFailedCount": {
"description": "RulesFailedCount is the total count of policy execution errors for this policy.",
"type": "integer"
},
"violationCount": {
"description": "ViolationCount is the total count of policy failure results for this policy.",
"type": "integer"
}
},
"type": "object"
}
},
"required": [
"spec"
],
"type": "object"
}
},
"served": true,
"storage": true,
"subresources": {
"status": {}
}
}
]
}
` | pkg/kyverno/crds/policy_crd.go | 0.779993 | 0.513546 | policy_crd.go | starcoder |
package dataframe
import (
"fmt"
)
type RowIterator struct {
FloatBatching
df *DataFrame
rowOffset int
dfIndex int
subInds []int
}
// Float32Iterator is a structure to iterate over a dataframe one row at a time.
// The rows provided to the user will be slices of float32.
// Float32Iterator cannot iterate through object columns.
// The delivered rows can be safely changed with no effect on the dataframe.
type Float32Iterator struct {
RowIterator
rows [128][]float32
}
// Columns returns the name of the columns ordered like the row elements are
// ordered.
// If called on Float32Iterator or Float64Iterator, it returns the list of
// columns passed to NewFloat32Iterator and NewFloat64Iterator respectively.
func (ite *RowIterator) Columns() []string {
return ite.columns
}
// Reset recycles the iterator's pre-allocated data for another dataframe with
// the same columns.
// If check is true, it will be verified that the columns are the same.
func (ite *RowIterator) Reset(df *DataFrame, check bool) {
if check {
for _, col := range ite.bColumns {
colName := ite.columns[col]
if _, ok := df.bools[colName]; !ok {
panic(fmt.Sprintf("%s missing from bool columns", colName))
}
}
for _, col := range ite.iColumns {
colName := ite.columns[col]
if _, ok := df.ints[colName]; !ok {
panic(fmt.Sprintf("%s missing from int columns", colName))
}
}
for _, col := range ite.fColumns {
colName := ite.columns[col]
if _, ok := df.floats[colName]; !ok {
panic(fmt.Sprintf("%s missing from float columns", colName))
}
}
}
ite.rowOffset = 0
ite.dfIndex = 0
ite.df = df
}
func (ite *RowIterator) nextIndices() []int {
end := ite.dfIndex + 128
if end > len(ite.df.indices) {
end = len(ite.df.indices)
}
ite.subInds = ite.df.indices[ite.dfIndex:end]
return ite.subInds
}
// NewFloat32Iterator allocates a new row iterator to allow you to iterate
// over float, bool and int columns as floats.
// If a given column is not float, bool or int, it will be ignored.
// Row elements will be delivered in the same order as the columns passed as
// argument.
func NewFloat32Iterator(df *DataFrame, columns []string) *Float32Iterator {
ite := new(Float32Iterator)
ite.initialize(df, columns)
ite.df = df
// pre-allocation of the data
for i, _ := range ite.rows {
ite.rows[i] = make([]float32, len(ite.columns))
}
return ite
}
// NextRow returns a single row, its index in the view and its index in the
// original data. If there is no more row, it returns nil, the size of the view
// and the size of the original data.
// You can safely change the values of the row since they are copies of the
// original data. However, NextRow recycles the float slice, so you shouldn't
// store the slice.
func (ite *Float32Iterator) NextRow() ([]float32, int, int) {
if ite.dfIndex == len(ite.df.indices) {
return nil, len(ite.df.indices), ite.df.NumAllocatedRows()
}
if ite.rowOffset == 0 {
indices := ite.RowIterator.nextIndices()
// bools
for _, colIx := range ite.bColumns {
vals := ite.df.bools[ite.columns[colIx]]
for j, i := range indices {
if vals[i] {
ite.rows[j][colIx] = 1.0
} else {
ite.rows[j][colIx] = 0
}
}
}
// ints
for _, colIx := range ite.iColumns {
vals := ite.df.ints[ite.columns[colIx]]
for j, i := range indices {
ite.rows[j][colIx] = float32(vals[i])
}
}
// float64
for _, colIx := range ite.fColumns {
vals := ite.df.floats[ite.columns[colIx]]
for j, i := range indices {
ite.rows[j][colIx] = float32(vals[i])
}
}
}
row := ite.rows[ite.rowOffset]
idx := ite.subInds[ite.rowOffset]
ite.rowOffset = (ite.rowOffset + 1) % len(ite.rows)
ite.dfIndex++
return row, ite.dfIndex-1, idx
} | dataframe/row_iterators.go | 0.761361 | 0.540803 | row_iterators.go | starcoder |
package level
// BlockPuzzleState describes the state of a block puzzle.
type BlockPuzzleState struct {
width int
height int
data []byte
}
// NewBlockPuzzleState returns a new instance of a block puzzle state modifier.
// The returned instance works with the passed data slice directly.
func NewBlockPuzzleState(data []byte, height, width int) *BlockPuzzleState {
return &BlockPuzzleState{
data: data,
width: width,
height: height}
}
// CellValue returns the value of the identified cell.
func (state *BlockPuzzleState) CellValue(row, col int) int {
scratch := uint16(0)
if state.positionOk(row, col) {
byteOffset, byteShift := state.byteOffset(row, col)
bitsAvailable := 8 - byteShift
scratch = uint16(state.data[state.mappedByteIndex(byteOffset)]) >> byteShift
if bitsAvailable < 3 {
scratch |= uint16(state.data[state.mappedByteIndex(byteOffset+1)]) << bitsAvailable
}
}
return int(scratch & 7)
}
// SetCellValue sets the value of the identified cell.
func (state *BlockPuzzleState) SetCellValue(row, col int, value int) {
if state.positionOk(row, col) {
byteOffset, byteShift := state.byteOffset(row, col)
needsSecondByte := (8 - byteShift) < 3
scratch := uint16(state.data[state.mappedByteIndex(byteOffset)])
mask := uint16(0x0007) << byteShift
if needsSecondByte {
scratch |= uint16(state.data[state.mappedByteIndex(byteOffset+1)]) << 8
}
scratch = (scratch & ^mask) | (uint16(value) << byteShift)
state.data[state.mappedByteIndex(byteOffset)] = byte((scratch >> 0) & 0xFF)
if needsSecondByte {
state.data[state.mappedByteIndex(byteOffset+1)] = byte((scratch >> 8) & 0xFF)
}
}
}
func (state *BlockPuzzleState) bitOffset(row, col int) int {
return (row*state.width + col) * 3
}
func (state *BlockPuzzleState) positionOk(row, col int) bool {
bitOffset := state.bitOffset(row, col)
return (row < state.height) && (col < state.width) && (bitOffset <= (128 - 3))
}
func (state *BlockPuzzleState) byteOffset(row, col int) (byteOffset int, byteShift uint) {
bitOffset := state.bitOffset(row, col)
byteOffset = bitOffset / 8
byteShift = uint(bitOffset % 8)
return
}
func (state *BlockPuzzleState) mappedByteIndex(index int) int {
remainder := index % 4
return 15 - (index - remainder + (3 - remainder))
} | ss1/content/archive/level/BlockPuzzleState.go | 0.845879 | 0.478468 | BlockPuzzleState.go | starcoder |
package azure
type ClassicVMSize struct {
MemoryInMB int
NumberOfCores int
StorageSize int
MaxNic int
}
var CLASSIC_VM_SIZES = map[string]ClassicVMSize{
"ExtraSmall": {MemoryInMB: 786, NumberOfCores: 1, StorageSize: 20, MaxNic: 1},
"Small": {MemoryInMB: 1.75 * 1024, NumberOfCores: 1, StorageSize: 225, MaxNic: 1},
"Medium": {MemoryInMB: 3.5 * 1024, NumberOfCores: 2, StorageSize: 490, MaxNic: 1},
"Large": {MemoryInMB: 7 * 1024, NumberOfCores: 4, StorageSize: 1000, MaxNic: 2},
"ExtraLarge": {MemoryInMB: 14 * 1024, NumberOfCores: 8, StorageSize: 2040, MaxNic: 4},
"A5": {MemoryInMB: 14 * 1024, NumberOfCores: 2, StorageSize: 490, MaxNic: 1},
"A6": {MemoryInMB: 28 * 1024, NumberOfCores: 4, StorageSize: 1000, MaxNic: 2},
"A7": {MemoryInMB: 56 * 1024, NumberOfCores: 8, StorageSize: 2040, MaxNic: 4},
"A8*": {MemoryInMB: 56 * 1024, NumberOfCores: 8, StorageSize: 1817, MaxNic: 2},
"A9*": {MemoryInMB: 112 * 1024, NumberOfCores: 16, StorageSize: 1817, MaxNic: 4},
"A10": {MemoryInMB: 56 * 1024, NumberOfCores: 8, StorageSize: 1817, MaxNic: 2},
"A11": {MemoryInMB: 112 * 1024, NumberOfCores: 16, StorageSize: 1817, MaxNic: 4},
"Standard_A1_v2": {MemoryInMB: 2 * 1024, NumberOfCores: 1, StorageSize: 10, MaxNic: 1},
"Standard_A2_v2": {MemoryInMB: 4 * 1024, NumberOfCores: 2, StorageSize: 20, MaxNic: 2},
"Standard_A4_v2": {MemoryInMB: 8 * 1024, NumberOfCores: 4, StorageSize: 40, MaxNic: 4},
"Standard_A8_v2": {MemoryInMB: 16 * 1024, NumberOfCores: 8, StorageSize: 80, MaxNic: 8},
"Standard_A2m_v2": {MemoryInMB: 16 * 1024, NumberOfCores: 2, StorageSize: 20, MaxNic: 2},
"Standard_A4m_v2": {MemoryInMB: 32 * 1024, NumberOfCores: 4, StorageSize: 40, MaxNic: 4},
"Standard_A8m_v2": {MemoryInMB: 64 * 1024, NumberOfCores: 8, StorageSize: 80, MaxNic: 8},
"Standard_D1": {MemoryInMB: 3 * 1024, NumberOfCores: 1, StorageSize: 50, MaxNic: 1},
"Standard_D2": {MemoryInMB: 7 * 1024, NumberOfCores: 2, StorageSize: 100, MaxNic: 2},
"Standard_D3": {MemoryInMB: 14 * 1024, NumberOfCores: 4, StorageSize: 200, MaxNic: 4},
"Standard_D4": {MemoryInMB: 28 * 1024, NumberOfCores: 8, StorageSize: 400, MaxNic: 8},
"Standard_D11": {MemoryInMB: 14 * 1024, NumberOfCores: 2, StorageSize: 100, MaxNic: 2},
"Standard_D12": {MemoryInMB: 28 * 1024, NumberOfCores: 4, StorageSize: 200, MaxNic: 4},
"Standard_D13": {MemoryInMB: 56 * 1024, NumberOfCores: 8, StorageSize: 400, MaxNic: 8},
"Standard_D14": {MemoryInMB: 112 * 1024, NumberOfCores: 16, StorageSize: 800, MaxNic: 8},
"Standard_D1_v2": {MemoryInMB: 3 * 1024, NumberOfCores: 1, StorageSize: 50, MaxNic: 1},
"Standard_D2_v2": {MemoryInMB: 7 * 1024, NumberOfCores: 2, StorageSize: 100, MaxNic: 2},
"Standard_D3_v2": {MemoryInMB: 14 * 1024, NumberOfCores: 4, StorageSize: 200, MaxNic: 4},
"Standard_D4_v2": {MemoryInMB: 28 * 1024, NumberOfCores: 8, StorageSize: 400, MaxNic: 8},
"Standard_D5_v2": {MemoryInMB: 56 * 1024, NumberOfCores: 16, StorageSize: 800, MaxNic: 8},
"Standard_D11_v2": {MemoryInMB: 14 * 1024, NumberOfCores: 2, StorageSize: 100, MaxNic: 2},
"Standard_D12_v2": {MemoryInMB: 28 * 1024, NumberOfCores: 4, StorageSize: 200, MaxNic: 4},
"Standard_D13_v2": {MemoryInMB: 56 * 1024, NumberOfCores: 8, StorageSize: 400, MaxNic: 8},
"Standard_D14_v2": {MemoryInMB: 112 * 1024, NumberOfCores: 16, StorageSize: 800, MaxNic: 8},
"Standard_D15_v2": {MemoryInMB: 140 * 1024, NumberOfCores: 20, StorageSize: 1, MaxNic: 8},
"Standard_D2_v3": {MemoryInMB: 8 * 1024, NumberOfCores: 2, StorageSize: 50, MaxNic: 2},
"Standard_D4_v3": {MemoryInMB: 16 * 1024, NumberOfCores: 4, StorageSize: 100, MaxNic: 2},
"Standard_D8_v3": {MemoryInMB: 32 * 1024, NumberOfCores: 8, StorageSize: 200, MaxNic: 4},
"Standard_D16_v3": {MemoryInMB: 64 * 1024, NumberOfCores: 16, StorageSize: 400, MaxNic: 8},
"Standard_D32_v3": {MemoryInMB: 128 * 1024, NumberOfCores: 32, StorageSize: 800, MaxNic: 8},
"Standard_D64_v3": {MemoryInMB: 256 * 1024, NumberOfCores: 64, StorageSize: 1600, MaxNic: 8},
"Standard_E2_v3": {MemoryInMB: 16 * 1024, NumberOfCores: 2, StorageSize: 50, MaxNic: 2},
"Standard_E4_v3": {MemoryInMB: 32 * 1024, NumberOfCores: 4, StorageSize: 100, MaxNic: 2},
"Standard_E8_v3": {MemoryInMB: 64 * 1024, NumberOfCores: 8, StorageSize: 200, MaxNic: 4},
"Standard_E16_v3": {MemoryInMB: 128 * 1024, NumberOfCores: 16, StorageSize: 400, MaxNic: 8},
"Standard_E32_v3": {MemoryInMB: 256 * 1024, NumberOfCores: 32, StorageSize: 800, MaxNic: 8},
"Standard_E64_v3": {MemoryInMB: 432 * 1024, NumberOfCores: 64, StorageSize: 1600, MaxNic: 8},
"Standard_G1": {MemoryInMB: 28 * 1024, NumberOfCores: 2, StorageSize: 384, MaxNic: 1},
"Standard_G2": {MemoryInMB: 56 * 1024, NumberOfCores: 4, StorageSize: 768, MaxNic: 2},
"Standard_G3": {MemoryInMB: 112 * 1024, NumberOfCores: 8, StorageSize: 1, MaxNic: 4},
"Standard_G4": {MemoryInMB: 224 * 1024, NumberOfCores: 16, StorageSize: 3, MaxNic: 8},
"Standard_G5": {MemoryInMB: 448 * 1024, NumberOfCores: 32, StorageSize: 6, MaxNic: 8},
} | pkg/multicloud/azure/classic_instancesize.go | 0.556882 | 0.452596 | classic_instancesize.go | starcoder |
package embd
// I2CBus interface is used to interact with the I2C bus.
type I2CBus interface {
// ReadByte reads a byte from the given address.
ReadByte(addr byte) (value byte, err error)
// ReadBytes reads a slice of bytes from the given address.
ReadBytes(addr byte, num int) (value []byte, err error)
// WriteByte writes a byte to the given address.
WriteByte(addr, value byte) error
// WriteBytes writes a slice bytes to the given address.
WriteBytes(addr byte, value []byte) error
// ReadFromReg reads n (len(value)) bytes from the given address and register.
ReadFromReg(addr, reg byte, value []byte) error
// ReadByteFromReg reads a byte from the given address and register.
ReadByteFromReg(addr, reg byte) (value byte, err error)
// ReadU16FromReg reads a unsigned 16 bit integer from the given address and register.
ReadWordFromReg(addr, reg byte) (value uint16, err error)
// WriteToReg writes len(value) bytes to the given address and register.
WriteToReg(addr, reg byte, value []byte) error
// WriteByteToReg writes a byte to the given address and register.
WriteByteToReg(addr, reg, value byte) error
// WriteU16ToReg
WriteWordToReg(addr, reg byte, value uint16) error
// Close releases the resources associated with the bus.
Close() error
}
// I2CDriver interface interacts with the host descriptors to allow us
// control of I2C communication.
type I2CDriver interface {
Bus(l byte) I2CBus
// Close releases the resources associated with the driver.
Close() error
}
var i2cDriverInitialized bool
var i2cDriverInstance I2CDriver
// InitI2C initializes the I2C driver.
func InitI2C() error {
if i2cDriverInitialized {
return nil
}
desc, err := DescribeHost()
if err != nil {
return err
}
if desc.I2CDriver == nil {
return ErrFeatureNotSupported
}
i2cDriverInstance = desc.I2CDriver()
i2cDriverInitialized = true
return nil
}
// CloseI2C releases resources associated with the I2C driver.
func CloseI2C() error {
return i2cDriverInstance.Close()
}
// NewI2CBus returns a I2CBus.
func NewI2CBus(l byte) I2CBus {
if err := InitI2C(); err != nil {
panic(err)
}
return i2cDriverInstance.Bus(l)
} | i2c.go | 0.666062 | 0.473718 | i2c.go | starcoder |
package iris
import (
"crossvalidation"
"sync"
)
// Irises represents the set of all iris data.
type Irises []Datum
// Iterate allows looping over the Irises.
func (is Irises) Iterate() <-chan interface{} {
c := make(chan interface{})
go func() {
for _, i := range []Datum(is) {
c <- i
}
close(c)
}()
return c
}
// Length returns the lenth of the set of irises.
func (is Irises) Length() int {
return len(is)
}
// ElementAt returns the iris at a given position in the data set.
func (is Irises) ElementAt(i int) interface{} {
return is[i]
}
// CreateTrainingAndTestDataSets splits the Iris data set into a training and test data set.
func CreateTrainingAndTestDataSets(percentTest float32, randomSeed int64) (Irises, Irises, error) {
trnChan := make(chan interface{})
tstChan := make(chan interface{})
trnSet := make([]Datum, 0, 0)
tstSet := make([]Datum, 0, 0)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := range trnChan {
if ii, ok := i.(Datum); ok {
trnSet = append(trnSet, ii)
}
}
}()
go func() {
defer wg.Done()
for i := range tstChan {
if ii, ok := i.(Datum); ok {
tstSet = append(tstSet, ii)
}
}
}()
if err := crossvalidation.TrainTestSplit(AllData, percentTest, randomSeed, trnChan, tstChan); err != nil {
return trnSet, tstSet, err
}
wg.Wait()
return trnSet, tstSet, nil
}
// AllData contains all Iris data points.
var AllData = Irises([]Datum{
Datum{5.1, 3.5, 1.4, 0.2, Setosa},
Datum{4.9, 3.0, 1.4, 0.2, Setosa},
Datum{4.7, 3.2, 1.3, 0.2, Setosa},
Datum{4.6, 3.1, 1.5, 0.2, Setosa},
Datum{5.0, 3.6, 1.4, 0.3, Setosa},
Datum{5.4, 3.9, 1.7, 0.4, Setosa},
Datum{4.6, 3.4, 1.4, 0.3, Setosa},
Datum{5.0, 3.4, 1.5, 0.2, Setosa},
Datum{4.4, 2.9, 1.4, 0.2, Setosa},
Datum{4.9, 3.1, 1.5, 0.1, Setosa},
Datum{5.4, 3.7, 1.5, 0.2, Setosa},
Datum{4.8, 3.4, 1.6, 0.2, Setosa},
Datum{4.8, 3.0, 1.4, 0.1, Setosa},
Datum{4.3, 3.0, 1.1, 0.1, Setosa},
Datum{5.8, 4.0, 1.2, 0.2, Setosa},
Datum{5.7, 4.4, 1.5, 0.4, Setosa},
Datum{5.4, 3.9, 1.3, 0.4, Setosa},
Datum{5.1, 3.5, 1.4, 0.3, Setosa},
Datum{5.7, 3.8, 1.7, 0.3, Setosa},
Datum{5.1, 3.8, 1.5, 0.3, Setosa},
Datum{5.4, 3.4, 1.7, 0.2, Setosa},
Datum{5.1, 3.7, 1.5, 0.4, Setosa},
Datum{4.6, 3.6, 1.0, 0.2, Setosa},
Datum{5.1, 3.3, 1.7, 0.5, Setosa},
Datum{4.8, 3.4, 1.9, 0.2, Setosa},
Datum{5.0, 3.0, 1.6, 0.2, Setosa},
Datum{5.0, 3.4, 1.6, 0.4, Setosa},
Datum{5.2, 3.5, 1.5, 0.2, Setosa},
Datum{5.2, 3.4, 1.4, 0.2, Setosa},
Datum{4.7, 3.2, 1.6, 0.2, Setosa},
Datum{4.8, 3.1, 1.6, 0.2, Setosa},
Datum{5.4, 3.4, 1.5, 0.4, Setosa},
Datum{5.2, 4.1, 1.5, 0.1, Setosa},
Datum{5.5, 4.2, 1.4, 0.2, Setosa},
Datum{4.9, 3.1, 1.5, 0.2, Setosa},
Datum{5.0, 3.2, 1.2, 0.2, Setosa},
Datum{5.5, 3.5, 1.3, 0.2, Setosa},
Datum{4.9, 3.6, 1.4, 0.1, Setosa},
Datum{4.4, 3.0, 1.3, 0.2, Setosa},
Datum{5.1, 3.4, 1.5, 0.2, Setosa},
Datum{5.0, 3.5, 1.3, 0.3, Setosa},
Datum{4.5, 2.3, 1.3, 0.3, Setosa},
Datum{4.4, 3.2, 1.3, 0.2, Setosa},
Datum{5.0, 3.5, 1.6, 0.6, Setosa},
Datum{5.1, 3.8, 1.9, 0.4, Setosa},
Datum{4.8, 3.0, 1.4, 0.3, Setosa},
Datum{5.1, 3.8, 1.6, 0.2, Setosa},
Datum{4.6, 3.2, 1.4, 0.2, Setosa},
Datum{5.3, 3.7, 1.5, 0.2, Setosa},
Datum{5.0, 3.3, 1.4, 0.2, Setosa},
Datum{7.0, 3.2, 4.7, 1.4, Versicolor},
Datum{6.4, 3.2, 4.5, 1.5, Versicolor},
Datum{6.9, 3.1, 4.9, 1.5, Versicolor},
Datum{5.5, 2.3, 4.0, 1.3, Versicolor},
Datum{6.5, 2.8, 4.6, 1.5, Versicolor},
Datum{5.7, 2.8, 4.5, 1.3, Versicolor},
Datum{6.3, 3.3, 4.7, 1.6, Versicolor},
Datum{4.9, 2.4, 3.3, 1.0, Versicolor},
Datum{6.6, 2.9, 4.6, 1.3, Versicolor},
Datum{5.2, 2.7, 3.9, 1.4, Versicolor},
Datum{5.0, 2.0, 3.5, 1.0, Versicolor},
Datum{5.9, 3.0, 4.2, 1.5, Versicolor},
Datum{6.0, 2.2, 4.0, 1.0, Versicolor},
Datum{6.1, 2.9, 4.7, 1.4, Versicolor},
Datum{5.6, 2.9, 3.6, 1.3, Versicolor},
Datum{6.7, 3.1, 4.4, 1.4, Versicolor},
Datum{5.6, 3.0, 4.5, 1.5, Versicolor},
Datum{5.8, 2.7, 4.1, 1.0, Versicolor},
Datum{6.2, 2.2, 4.5, 1.5, Versicolor},
Datum{5.6, 2.5, 3.9, 1.1, Versicolor},
Datum{5.9, 3.2, 4.8, 1.8, Versicolor},
Datum{6.1, 2.8, 4.0, 1.3, Versicolor},
Datum{6.3, 2.5, 4.9, 1.5, Versicolor},
Datum{6.1, 2.8, 4.7, 1.2, Versicolor},
Datum{6.4, 2.9, 4.3, 1.3, Versicolor},
Datum{6.6, 3.0, 4.4, 1.4, Versicolor},
Datum{6.8, 2.8, 4.8, 1.4, Versicolor},
Datum{6.7, 3.0, 5.0, 1.7, Versicolor},
Datum{6.0, 2.9, 4.5, 1.5, Versicolor},
Datum{5.7, 2.6, 3.5, 1.0, Versicolor},
Datum{5.5, 2.4, 3.8, 1.1, Versicolor},
Datum{5.5, 2.4, 3.7, 1.0, Versicolor},
Datum{5.8, 2.7, 3.9, 1.2, Versicolor},
Datum{6.0, 2.7, 5.1, 1.6, Versicolor},
Datum{5.4, 3.0, 4.5, 1.5, Versicolor},
Datum{6.0, 3.4, 4.5, 1.6, Versicolor},
Datum{6.7, 3.1, 4.7, 1.5, Versicolor},
Datum{6.3, 2.3, 4.4, 1.3, Versicolor},
Datum{5.6, 3.0, 4.1, 1.3, Versicolor},
Datum{5.5, 2.5, 4.0, 1.3, Versicolor},
Datum{5.5, 2.6, 4.4, 1.2, Versicolor},
Datum{6.1, 3.0, 4.6, 1.4, Versicolor},
Datum{5.8, 2.6, 4.0, 1.2, Versicolor},
Datum{5.0, 2.3, 3.3, 1.0, Versicolor},
Datum{5.6, 2.7, 4.2, 1.3, Versicolor},
Datum{5.7, 3.0, 4.2, 1.2, Versicolor},
Datum{5.7, 2.9, 4.2, 1.3, Versicolor},
Datum{6.2, 2.9, 4.3, 1.3, Versicolor},
Datum{5.1, 2.5, 3.0, 1.1, Versicolor},
Datum{5.7, 2.8, 4.1, 1.3, Versicolor},
Datum{6.3, 3.3, 6.0, 2.5, Virginica},
Datum{5.8, 2.7, 5.1, 1.9, Virginica},
Datum{7.1, 3.0, 5.9, 2.1, Virginica},
Datum{6.3, 2.9, 5.6, 1.8, Virginica},
Datum{6.5, 3.0, 5.8, 2.2, Virginica},
Datum{7.6, 3.0, 6.6, 2.1, Virginica},
Datum{4.9, 2.5, 4.5, 1.7, Virginica},
Datum{7.3, 2.9, 6.3, 1.8, Virginica},
Datum{6.7, 2.5, 5.8, 1.8, Virginica},
Datum{7.2, 3.6, 6.1, 2.5, Virginica},
Datum{6.5, 3.2, 5.1, 2.0, Virginica},
Datum{6.4, 2.7, 5.3, 1.9, Virginica},
Datum{6.8, 3.0, 5.5, 2.1, Virginica},
Datum{5.7, 2.5, 5.0, 2.0, Virginica},
Datum{5.8, 2.8, 5.1, 2.4, Virginica},
Datum{6.4, 3.2, 5.3, 2.3, Virginica},
Datum{6.5, 3.0, 5.5, 1.8, Virginica},
Datum{7.7, 3.8, 6.7, 2.2, Virginica},
Datum{7.7, 2.6, 6.9, 2.3, Virginica},
Datum{6.0, 2.2, 5.0, 1.5, Virginica},
Datum{6.9, 3.2, 5.7, 2.3, Virginica},
Datum{5.6, 2.8, 4.9, 2.0, Virginica},
Datum{7.7, 2.8, 6.7, 2.0, Virginica},
Datum{6.3, 2.7, 4.9, 1.8, Virginica},
Datum{6.7, 3.3, 5.7, 2.1, Virginica},
Datum{7.2, 3.2, 6.0, 1.8, Virginica},
Datum{6.2, 2.8, 4.8, 1.8, Virginica},
Datum{6.1, 3.0, 4.9, 1.8, Virginica},
Datum{6.4, 2.8, 5.6, 2.1, Virginica},
Datum{7.2, 3.0, 5.8, 1.6, Virginica},
Datum{7.4, 2.8, 6.1, 1.9, Virginica},
Datum{7.9, 3.8, 6.4, 2.0, Virginica},
Datum{6.4, 2.8, 5.6, 2.2, Virginica},
Datum{6.3, 2.8, 5.1, 1.5, Virginica},
Datum{6.1, 2.6, 5.6, 1.4, Virginica},
Datum{7.7, 3.0, 6.1, 2.3, Virginica},
Datum{6.3, 3.4, 5.6, 2.4, Virginica},
Datum{6.4, 3.1, 5.5, 1.8, Virginica},
Datum{6.0, 3.0, 4.8, 1.8, Virginica},
Datum{6.9, 3.1, 5.4, 2.1, Virginica},
Datum{6.7, 3.1, 5.6, 2.4, Virginica},
Datum{6.9, 3.1, 5.1, 2.3, Virginica},
Datum{5.8, 2.7, 5.1, 1.9, Virginica},
Datum{6.8, 3.2, 5.9, 2.3, Virginica},
Datum{6.7, 3.3, 5.7, 2.5, Virginica},
Datum{6.7, 3.0, 5.2, 2.3, Virginica},
Datum{6.3, 2.5, 5.0, 1.9, Virginica},
Datum{6.5, 3.0, 5.2, 2.0, Virginica},
Datum{6.2, 3.4, 5.4, 2.3, Virginica},
Datum{5.9, 3.0, 5.1, 1.8, Virginica},
}) | src/iris/data.go | 0.749729 | 0.598459 | data.go | starcoder |
package muse
import "fmt"
// Group is a collection of timeseries keeping track of all labeled timeseries,
// All timeseries must be unique regarding their label value pairs
type Group struct {
Name string
n int // length of each timeseries in the group
index map[string][]string // mapping of the grouped labels to a slice of Series UIDs with the same group label
registry map[string]*Series // stores a mapping of the Series UID to the Series instance
}
// NewGroup creates a new Group and initializes the timeseries label registry
func NewGroup(name string) *Group {
return &Group{
Name: name,
index: make(map[string][]string),
registry: make(map[string]*Series),
}
}
// Length returns the length of all timeseries. All timeseries have the same length
func (g *Group) Length() int {
return g.n
}
// Add will register a time series with its labels into the current groups
// registry. If the timeseries with the exact same label values already exists,
// an error will be returned
func (g *Group) Add(series ...*Series) error {
for _, s := range series {
labels := s.labels.Keys()
if len(labels) == 0 {
return fmt.Errorf("Invalid Series with no labels, %v", s)
}
uid := s.UID()
if _, exists := g.registry[uid]; exists {
return fmt.Errorf("Series with label:values, %v, already exists within group, %s", uid, g.Name)
}
// set the length of timeseries for this group or check if the added timeseries
// has the same length
if len(g.registry) == 0 {
g.n = s.Length()
} else {
if s.Length() != g.n {
return fmt.Errorf("Timeseries has length %d, but current group has length %d", s.Length(), g.n)
}
}
g.registry[uid] = s
}
return nil
}
// FilterByLabelValues returns the slice of timeseries filtered by specified label
// value pairs
func (g *Group) FilterByLabelValues(labels *Labels) []*Series {
var filteredSeries []*Series
guid := labels.ID(labels.Keys())
if _, exists := g.index[guid]; exists {
filteredSeries = make([]*Series, 0, len(g.index[guid]))
for _, uid := range g.index[guid] {
filteredSeries = append(filteredSeries, g.registry[uid])
}
}
return filteredSeries
}
// indexLabelValues return a slice of all the distinct combinations of the
// input label values while ignoring labels not being specified. If no labels
// are specified then each series will be treated separately.
func (g *Group) indexLabelValues(groupByLabels []string) []*Labels {
var distinctLabelValues []*Labels
var guid string
// clear index
g.index = make(map[string][]string)
for uid, s := range g.registry {
if len(groupByLabels) != 0 {
guid = s.labels.ID(groupByLabels)
} else {
guid = uid
groupByLabels = s.Labels().Keys()
}
if _, exists := g.index[guid]; !exists {
lv := make(LabelMap)
for _, name := range groupByLabels {
if v, exists := s.labels.Get(name); exists {
lv[name] = v
}
}
distinctLabelValues = append(distinctLabelValues, NewLabels(lv))
}
g.index[guid] = append(g.index[guid], uid)
}
return distinctLabelValues
} | group.go | 0.779364 | 0.498474 | group.go | starcoder |
package underscore
import (
"reflect"
"sort"
)
type sortQuery struct {
keysRV reflect.Value
valuesRV reflect.Value
compareRV reflect.Value
}
func (this sortQuery) Len() int {
if this.keysRV.IsValid() {
return this.keysRV.Len()
}
return 0;
}
func (this sortQuery) Swap(i, j int) {
temp := this.keysRV.Index(i).Interface()
this.keysRV.Index(i).Set(
this.keysRV.Index(j),
)
this.keysRV.Index(j).Set(
reflect.ValueOf(temp),
)
temp = this.valuesRV.Index(i).Interface()
this.valuesRV.Index(i).Set(
this.valuesRV.Index(j),
)
this.valuesRV.Index(j).Set(
reflect.ValueOf(temp),
)
}
func (this sortQuery) Less(i, j int) bool {
thisRV := this.keysRV.Index(i)
thatRV := this.keysRV.Index(j)
switch thisRV.Kind() {
case reflect.Float32, reflect.Float64:
return thisRV.Float() < thatRV.Float()
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
return thisRV.Int() < thatRV.Int()
case reflect.String:
return thisRV.String() < thatRV.String()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return thisRV.Uint() < thatRV.Uint()
default:
return false
}
}
func Sort(source, selector interface{}) interface{} {
qs := sortQuery{}
each(source, selector, func (sortRV, valueRV, _ reflect.Value) bool {
if qs.Len() == 0 {
keysRT := reflect.SliceOf(sortRV.Type())
qs.keysRV = reflect.MakeSlice(keysRT, 0, 0)
valuesRT := reflect.SliceOf(valueRV.Type())
qs.valuesRV = reflect.MakeSlice(valuesRT, 0, 0)
}
qs.keysRV = reflect.Append(qs.keysRV, sortRV)
qs.valuesRV = reflect.Append(qs.valuesRV, valueRV)
return false
})
if qs.Len() > 0 {
sort.Sort(qs)
return qs.valuesRV.Interface()
}
return nil
}
func SortBy(source interface{}, property string) interface{} {
getPropertyRV := PropertyRV(property)
return Sort(source, func (value, _ interface{}) Facade {
rv, _ := getPropertyRV(value)
return Facade{ rv }
})
}
//chain
func (this *Query) Sort(selector interface{}) Queryer {
this.source = Sort(this.source, selector)
return this
}
func (this *Query) SortBy(property string) Queryer {
this.source = SortBy(this.source, property)
return this
} | vendor/github.com/ahl5esoft/golang-underscore/sort.go | 0.52074 | 0.467332 | sort.go | starcoder |
package main
var schemas = `
{
"API": {
"createDevice": {
"description": "Create one or more parking meter device. One argument, a JSON encoded event.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "Parking meter device registration / update.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"minimumusagecost": {
"description": "minimum cost for using the meter",
"type": "number"
},
"minimumusagetime": {
"description": "minimum duration of use",
"type": "integer"
},
"overtimeusagecost": {
"description": "overtime cost.",
"type": "number"
},
"overtimeusagetime": {
"description": "Overtime duration.",
"type": "integer"
},
"latitude": {
"description": "Location:latitude",
"type": "number"
},
"longitude": {
"description": "Location:longitude",
"type": "number"
},
"address": {
"description": "Abbreviated street address",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"required": [
"deviceid",
"minimumusagecost",
"minimumusagetime",
"overtimeusagecost",
"overtimeusagetime",
"latitude",
"longitude",
"address",
"available"
],
"type": "object"
},
"minItems": 1,
"type": "array"
},
"function": {
"description": "createDevice function",
"enum": [
"createDevice"
],
"type": "string"
},
"method": "invoke"
},
"type": "object"
},
"createUsage": {
"description": "Create parking meter usage record. One argument, a JSON encoded event.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "Parking meter device registration / update.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"starttime": {
"description": "start time of usage",
"type": "string"
},
"endtime": {
"description": "usage end time. Computed from start time and duration",
"type": "string"
},
"duration": {
"description": "Usage duration. Difference between start and end times. Duration is passed in and end time computed",
"type": "number"
},
"usagecost": {
"description": "Usage cost. Based on duration and rates defined for device.",
"type": "number"
},
"actualendtime": {
"description": "actual end time. Provision for overtime scenario",
"type": "string"
},
"overtimecost": {
"description": "Cost incurred for overtime use. Provision for overtime scenario",
"type": "number"
},
"totalcost": {
"description": "Total Cost incurred including overtime use. Provision for overtime scenario",
"type": "number"
}
},
"required": [
"deviceid"
],
"type": "object"
},
"maxItems": 1,
"minItems": 1,
"type": "array"
},
"function": {
"description": "createUsage function",
"enum": [
"createUsage"
],
"type": "string"
},
"method": "invoke"
},
"type": "object"
},
"updateDeviceAsAvailable": {
"description": "Flag device as available.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "Parking meter device registration / update.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"required": [
"deviceid"
],
"type": "object"
},
"maxItems": 1,
"minItems": 1,
"type": "array"
},
"function": {
"description": "updateDeviceAsAvailable function",
"enum": [
"updateDeviceAsAvailable"
],
"type": "string"
},
"method": "invoke"
},
"type": "object"
},
"init": {
"description": "Initializes the contract when started, either by deployment or by peer restart.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "event sent to init on deployment",
"properties": {
"nickname": {
"default": "SIMPLE",
"description": "The nickname of the current contract",
"type": "string"
},
"version": {
"description": "The ID of a managed device. The resource focal point for a smart contract.",
"type": "string"
}
},
"required": [
"version"
],
"type": "object"
},
"maxItems": 1,
"minItems": 1,
"type": "array"
},
"function": {
"description": "init function",
"enum": [
"init"
],
"type": "string"
},
"method": "deploy"
},
"type": "object"
},
"readDevice": {
"description": "Returns the state an device. Argument is a JSON encoded string. Device id is the only accepted property.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "An object containing only an Device Id for use as an argument to read or delete.",
"properties": {
"deviceid": {
"description": "The ID of a managed device. The resource focal point for a smart contract.",
"type": "string"
}
},
"type": "object"
},
"maxItems": 1,
"minItems": 1,
"type": "array"
},
"function": {
"description": "readDevice function",
"enum": [
"readDevice"
],
"type": "string"
},
"method": "query",
"result": {
"description": "A set of fields that constitute the complete device state.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"minimumusagecost": {
"description": "minimum cost for using the meter",
"type": "number"
},
"minimumusagetime": {
"description": "minimum duration of use",
"type": "integer"
},
"overtimeusagecost": {
"description": "overtime cost.",
"type": "number"
},
"overtimeusagetime": {
"description": "Overtime duration.",
"type": "integer"
},
"latitude": {
"description": "Location:latitude",
"type": "number"
},
"longitude": {
"description": "Location:longitude",
"type": "number"
},
"address": {
"description": "Abbreviated street address",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"type": "object"
}
},
"type": "object"
},
"readAssetSchemas": {
"description": "Returns a string generated from the schema containing APIs and Objects as specified in generate.json in the scripts folder.",
"properties": {
"args": {
"description": "accepts no arguments",
"items": {},
"maxItems": 0,
"minItems": 0,
"type": "array"
},
"function": {
"description": "readAssetSchemas function",
"enum": [
"readAssetSchemas"
],
"type": "string"
},
"method": "query",
"result": {
"description": "JSON encoded object containing selected schemas",
"type": "string"
}
},
"type": "object"
},
"readUsage": {
"description": "Returns the state an device. Argument is a JSON encoded string. Device Id is the only accepted property.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "An object containing only an Device Id for use as an argument to read or delete.",
"properties": {
"deviceid": {
"description": "The ID of a managed device. The resource focal point for a smart contract.",
"type": "string"
}
},
"type": "object"
},
"maxItems": 1,
"minItems": 1,
"type": "array"
},
"function": {
"description": "readUsage function",
"enum": [
"readUsage"
],
"type": "string"
},
"method": "query",
"result": {
"description": "A set of fields that constitute the complete device state.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"minimumusagecost": {
"description": "minimum cost for using the meter",
"type": "number"
},
"minimumusagetime": {
"description": "minimum duration of use",
"type": "integer"
},
"overtimeusagecost": {
"description": "overtime cost.",
"type": "number"
},
"overtimeusagetime": {
"description": "Overtime duration.",
"type": "integer"
},
"latitude": {
"description": "Location:latitude",
"type": "number"
},
"longitude": {
"description": "Location:longitude",
"type": "number"
},
"address": {
"description": "Abbreviated street address",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"type": "object"
}
},
"type": "object"
},
"readUsageHistory": {
"description": "Returns the history of an device. Argument is a JSON encoded string. deviceid is the only accepted property.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "An object containing only an Device Id for use as an argument to read or delete.",
"properties": {
"deviceid": {
"description": "The ID of a managed device. The resource focal point for a smart contract.",
"type": "string"
}
},
"type": "object"
},
"maxItems": 1,
"minItems": 1,
"type": "array"
},
"function": {
"description": "readUsageHistory function",
"enum": [
"readUsageHistory"
],
"type": "string"
},
"method": "query",
"result": {
"description": "A set of fields that constitute the complete device state.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"minimumusagecost": {
"description": "minimum cost for using the meter",
"type": "number"
},
"minimumusagetime": {
"description": "minimum duration of use",
"type": "integer"
},
"overtimeusagecost": {
"description": "overtime cost.",
"type": "number"
},
"overtimeusagetime": {
"description": "Overtime duration.",
"type": "integer"
},
"latitude": {
"description": "Location:latitude",
"type": "number"
},
"longitude": {
"description": "Location:longitude",
"type": "number"
},
"address": {
"description": "Abbreviated street address",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"type": "object"
}
},
"type": "object"
},
"readDeviceList": {
"description": "Returns the history of an device. Argument is a JSON encoded string. deviceid is the only accepted property.",
"properties": {
"args": {
"description": "accepts no arguments",
"items": {},
"maxItems": 0,
"minItems": 0,
"type": "array"
},
"function": {
"description": "readDeviceList function",
"enum": [
"readDeviceList"
],
"type": "string"
},
"method": "query",
"result": {
"description": "A set of fields that constitute the complete device state.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"minimumusagecost": {
"description": "minimum cost for using the meter",
"type": "number"
},
"minimumusagetime": {
"description": "minimum duration of use",
"type": "integer"
},
"overtimeusagecost": {
"description": "overtime cost.",
"type": "number"
},
"overtimeusagetime": {
"description": "Overtime duration.",
"type": "integer"
},
"latitude": {
"description": "Location:latitude",
"type": "number"
},
"longitude": {
"description": "Location:longitude",
"type": "number"
},
"address": {
"description": "Abbreviated street address",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"type": "object"
}
},
"type": "object"
},
"deleteDevice": {
"description": "Delete a parking meter device. One argument, a JSON encoded event.",
"properties": {
"args": {
"description": "args are JSON encoded strings",
"items": {
"description": "Parking meter device registration / update.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
}
},
"required": [
"deviceid"
],
"type": "object"
},
"minItems": 1,
"type": "array"
},
"function": {
"description": "deleteDevice function",
"enum": [
"deleteDevice"
],
"type": "string"
},
"method": "invoke"
},
"type": "object"
}
},
"objectModelSchemas": {
"deviceidKey": {
"description": "An object containing only an Device Id for use as an argument to read or delete.",
"properties": {
"deviceid": {
"description": "The ID of a managed device. The resource focal point for a smart contract.",
"type": "string"
}
},
"type": "object"
},
"event": {
"description": "A set of fields that constitute the writable fields in an device's state. Device Id is mandatory along with at least one writable field. In this contract pattern, a partial state is used as an event.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"minimumusagecost": {
"description": "minimum cost for using the meter",
"type": "number"
},
"minimumusagetime": {
"description": "minimum duration of use",
"type": "integer"
},
"overtimeusagecost": {
"description": "overtime cost.",
"type": "number"
},
"overtimeusagetime": {
"description": "Overtime duration.",
"type": "integer"
},
"latitude": {
"description": "Location:latitude",
"type": "number"
},
"longitude": {
"description": "Location:longitude",
"type": "number"
},
"address": {
"description": "Abbreviated street address",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"required": [
"deviceid"
],
"type": "object"
},
"initEvent": {
"description": "event sent to init on deployment",
"properties": {
"nickname": {
"default": "SIMPLE",
"description": "The nickname of the current contract",
"type": "string"
},
"version": {
"description": "The version of the contract.",
"type": "string"
}
},
"required": [
"version"
],
"type": "object"
},
"state": {
"description": "A set of fields that constitute the complete device state.",
"properties": {
"deviceid": {
"description": "The ID of a meter.",
"type": "string"
},
"minimumusagecost": {
"description": "minimum cost for using the meter",
"type": "number"
},
"minimumusagetime": {
"description": "minimum duration of use",
"type": "integer"
},
"overtimeusagecost": {
"description": "overtime cost.",
"type": "number"
},
"overtimeusagetime": {
"description": "Overtime duration.",
"type": "integer"
},
"latitude": {
"description": "Location:latitude",
"type": "number"
},
"longitude": {
"description": "Location:longitude",
"type": "number"
},
"address": {
"description": "Abbreviated street address",
"type": "string"
},
"available": {
"description": "Light in candela.",
"type": "boolean"
}
},
"type": "object"
}
}
}` | contracts/industry/parkingmeter/mbedParkingMeter.0.6/schemas.go | 0.826607 | 0.538498 | schemas.go | starcoder |
package gogo
import (
"sort"
"gonum.org/v1/gonum/graph/formats/rdf"
)
// Query represents a step in a graph query.
type Query struct {
g *Graph
terms []rdf.Term
}
// Query returns a query of the receiver starting from the given nodes.
// Queries may not be mixed between distinct graphs.
func (g *Graph) Query(from ...rdf.Term) Query {
return Query{g: g, terms: from}
}
// Out returns a query holding nodes reachable out from the receiver's
// starting nodes via statements that satisfy fn.
func (q Query) Out(fn func(s *rdf.Statement) bool) Query {
r := Query{g: q.g}
for _, s := range q.terms {
it := q.g.From(s.ID())
for it.Next() {
if ConnectedByAny(q.g.Edge(s.ID(), it.Node().ID()), fn) {
r.terms = append(r.terms, it.Node().(rdf.Term))
}
}
}
return r
}
// In returns a query holding nodes reachable in from the receiver's
// starting nodes via statements that satisfy fn.
func (q Query) In(fn func(s *rdf.Statement) bool) Query {
r := Query{g: q.g}
for _, s := range q.terms {
it := q.g.To(s.ID())
for it.Next() {
if ConnectedByAny(q.g.Edge(it.Node().ID(), s.ID()), fn) {
r.terms = append(r.terms, it.Node().(rdf.Term))
}
}
}
return r
}
// And returns a query that holds the disjunction of q and p.
func (q Query) And(p Query) Query {
if q.g != p.g {
panic("gogo: binary query operation parameters from distinct graphs")
}
sortByID(q.terms)
sortByID(p.terms)
r := Query{g: q.g}
var i, j int
for i < len(q.terms) && j < len(p.terms) {
qi := q.terms[i]
pj := p.terms[j]
switch {
case qi.ID() < pj.ID():
i++
case pj.ID() < qi.ID():
j++
default:
r.terms = append(r.terms, qi)
i++
j++
}
}
return r
}
// Or returns a query that holds the conjunction of q and p.
func (q Query) Or(p Query) Query {
if q.g != p.g {
panic("gogo: binary query operation parameters from distinct graphs")
}
sortByID(q.terms)
sortByID(p.terms)
r := Query{g: q.g}
var i, j int
for i < len(q.terms) && j < len(p.terms) {
qi := q.terms[i]
pj := p.terms[j]
switch {
case qi.ID() < pj.ID():
if len(r.terms) == 0 || r.terms[len(r.terms)-1].UID != qi.UID {
r.terms = append(r.terms, qi)
}
i++
case pj.ID() < qi.ID():
if len(r.terms) == 0 || r.terms[len(r.terms)-1].UID != pj.UID {
r.terms = append(r.terms, pj)
}
j++
default:
if len(r.terms) == 0 || r.terms[len(r.terms)-1].UID != qi.UID {
r.terms = append(r.terms, qi)
}
i++
j++
}
}
r.terms = append(r.terms, q.terms[i:]...)
r.terms = append(r.terms, p.terms[j:]...)
return r
}
// Not returns a query that holds q less p.
func (q Query) Not(p Query) Query {
if q.g != p.g {
panic("gogo: binary query operation parameters from distinct graphs")
}
sortByID(q.terms)
sortByID(p.terms)
r := Query{g: q.g}
var i, j int
for i < len(q.terms) && j < len(p.terms) {
qi := q.terms[i]
pj := p.terms[j]
switch {
case qi.ID() < pj.ID():
r.terms = append(r.terms, qi)
i++
case pj.ID() < qi.ID():
j++
default:
i++
}
}
if len(r.terms) < len(q.terms) {
r.terms = append(r.terms, q.terms[i:len(q.terms)+min(0, i-len(r.terms))]...)
}
return r
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Unique returns a copy of the receiver that contains only one instance
// of each term.
func (q Query) Unique() Query {
sortByID(q.terms)
r := Query{g: q.g}
for i, t := range q.terms {
if i == 0 || t.UID != q.terms[i-1].UID {
r.terms = append(r.terms, t)
}
}
return r
}
// Result returns the terms held by the query.
func (q Query) Result() []rdf.Term {
return q.terms
}
func sortByID(terms []rdf.Term) {
sort.Slice(terms, func(i, j int) bool { return terms[i].ID() < terms[j].ID() })
} | query.go | 0.730674 | 0.488771 | query.go | starcoder |
package goparse
var (
// Lexical error codes and their strings
lexErrors = map[string]string{
"stringne": "A string cannot be empty",
"stringesc": `A string escape can must be \\, \t, \n, \', or \"`,
"rangene": "A range cannot be empty",
}
// Lexical analyzer table, where each row is compressed into a map.
// Since a rune is actually an int32, use -1 to refer to any other character.
// If a row does not contain an entry for a given rune, and contains no -1 entry, it is a syntax error.
lexTable = []map[rune]lexActions{
// 0 - start
{
'\t': {actions: lexSkip | lexAdvance | lexEOFOK, lexType: lexEOF},
// goiter.RunePositionIter coalesces all EOL sequences into \n
'\n': {actions: lexSkip | lexAdvance | lexEOFOK, lexType: lexEOF},
' ': {actions: lexSkip | lexAdvance | lexEOFOK, lexType: lexEOF},
'/': {row: 1},
'\'': {row: 5},
'"': {row: 8},
'[': {row: 10},
},
// 1
{
'/': {actions: lexEOFOK, row: 2, lexType: lexCommentOneLine},
'*': {row: 3},
},
// 2 - comment-one-line
{
'\n': {actions: lexUnread | lexDone, lexType: lexCommentOneLine},
-1: {actions: lexEOFOK, lexType: lexCommentOneLine, row: 2},
},
// 3 - comment-multi-line
{
'*': {row: 4},
-1: {row: 3},
},
// 4
{
'*': {row: 4},
'/': {actions: lexDone, lexType: lexCommentMultiLine},
-1: {row: 3},
},
// 5 - string: "'" string-sq-chars+ "'"
{
'\'': {actions: lexError, errCode: "stringne"},
'\\': {row: 6},
-1: {row: 7},
},
// 6
{
'\\': {row: 7},
't': {row: 7},
'n': {row: 7},
'\'': {row: 7},
'"': {row: 7},
-1: {actions: lexError, errCode: "stringesc"},
},
// 7
{
'\'': {actions: lexDone, lexType: lexString},
'\\': {row: 6},
-1: {row: 7},
},
// 8 - string: '"' string-qq-chars+ '"'
{
'"': {actions: lexError, errCode: "stringne"},
'\\': {row: 9},
-1: {row: 10},
},
// 9
{
'\\': {row: 10},
't': {row: 10},
'n': {row: 10},
'\'': {row: 10},
'"': {row: 10},
},
// 10
{
'"': {actions: lexDone, lexType: lexString},
'\\': {row: 9},
-1: {row: 10},
},
// 11 - range
{
']': {actions: lexError, errCode: "rangene"},
'\\': {row: 12},
-1: {row: 13},
},
// 12
{
'\\': {row: 13},
't': {row: 13},
'n': {row: 13},
']': {row: 13},
},
// 13
{
']': {actions: lexDone, lexType: lexRange},
'\\': {row: 12},
-1: {row: 13},
},
}
) | lexer_table.go | 0.501221 | 0.49408 | lexer_table.go | starcoder |
package order
import (
"sort"
"strings"
"golang.org/x/exp/constraints"
"github.com/mariomac/gostream/item"
)
// Comparator function compares its two arguments for order. Returns a negative
// integer, zero, or a positive integer as the first argument is less than,
// equal to, or greater than the second.
type Comparator[T any] func(a, b T) int
// Natural implements the Comparator for those elements whose type
// has a natural order (numbers and strings)
func Natural[T constraints.Ordered](a, b T) int {
if a == b {
return 0
}
if a < b {
return -1
}
return +1
}
// Int implements the Comparator for signed integers. This will be usually
// faster than Natural comparator
func Int[T constraints.Integer](a, b T) int {
return int(a - b)
}
// IgnoreCase implements order.Comparator for strings, ignoring the case.
func IgnoreCase(a, b string) int {
return Natural(strings.ToLower(a), strings.ToLower(b))
}
// Inverse result of the Comparator function for inverted sorts
func Inverse[T any](cmp Comparator[T]) Comparator[T] {
return func(a, b T) int {
return -cmp(a, b)
}
}
// ByKey uses the source comparator to compare the key of two item.Pair entries
func ByKey[K comparable, V any](cmp Comparator[K]) Comparator[item.Pair[K, V]] {
return func(a, b item.Pair[K, V]) int {
return cmp(a.Key, b.Key)
}
}
// ByVal uses the source comparator to compare the value of two item.Pair entries
func ByVal[K, V comparable](cmp Comparator[V]) Comparator[item.Pair[K, V]] {
return func(a, b item.Pair[K, V]) int {
return cmp(a.Val, b.Val)
}
}
// SortSlice sorts the given slice according to the criteria in the provided comparator
func SortSlice[T any](slice []T, comparator Comparator[T]) {
sort.Sort(&sorter[T]{items: slice, comparator: comparator})
}
type sorter[T any] struct {
items []T
comparator Comparator[T]
}
func (s *sorter[T]) Len() int {
return len(s.items)
}
func (s *sorter[T]) Less(i, j int) bool {
return s.comparator(s.items[i], s.items[j]) < 0
}
func (s *sorter[T]) Swap(i, j int) {
s.items[i], s.items[j] = s.items[j], s.items[i]
} | order/order.go | 0.821796 | 0.442094 | order.go | starcoder |
package manager
type ResourceManager interface {
/**
* Creates a {@code Namespace} resource with some preset attributes.
* <p>
* A namespace wraps the OMS resources in an abstract concept that makes it appear to the users within the namespace
* that they have their own isolated instance of the global OMS resources.
*
* @param nsName the name of the new namespace.
* @return error when have no authority to create namespace.
* @return error when the given timeout elapses before the create operation completes.
* @return error when this given destination has been created in the server.
* @return error when the {@code ResourceManager} fails to create namespace due to some internal error.
*/
CreateNamespace(nsName string) error
/**
* Deletes an existing namespace.
*
* @param nsName the namespace needs to be deleted.
* @return error when have no authority to delete this namespace.
* @return error when the given timeout elapses before the delete operation completes.
* @return error when have no given destination in the server.
* @return error when the {@code ResourceManager} fails to delete the namespace due to some internal error.
*/
DeleteNamespace(nsName string) error
/**
* Switch to an existing namespace.
*
* @param targetNamespace the namespace needs to be switched.
* @return error when have no authority to delete this namespace.
* @return error when the given timeout elapses before the delete operation completes.
* @return error when have no given destination in the server.
* @return error when the {@code ResourceManager} fails to delete the namespace due to some internal error.
*/
SwitchNamespace(targetNamespace string) error
/**
* Gets the namespace list in the current {@code MessagingAccessPoint}.
*
* @return the set of all namespaces.
* @return error when have no authority to delete this namespace.
* @return error when the given timeout elapses before the list operation completes.
* @return error when the {@code ResourceManager} fails to list the namespace due to some internal error.
*/
ListNamespaces() ([]string, error);
/**
* Creates a {@code Queue} resource in the configured namespace with some preset attributes.
* <p>
* The standard OMS {@code Queue} schema must start with the {@code Namespace} prefix:
* <p>
* {@literal <namespace_name>://<queue_name>}
*
* @param queueName the name of the new queue.
* @return error when have no authority to create this queue.
* @return error when the given timeout elapses before the create operation completes.
* @return error when the given destination has been created in the server.
* @return error when the {@code ResourceManager} fails to delete the namespace due to some internal error.
*/
CreateQueue(queueName string) error
/**
* Deletes an existing queue resource.
*
* @param queueName the queue needs to be deleted.
* @return error when have no authority to delete this namespace.
* @return error when the given timeout elapses before the delete operation completes.
* @return error when have no given destination in the server.
* @return error when the {@code ResourceManager} fails to delete the namespace due to some internal error.
*/
DeleteQueue(queueName string) error
/**
* Gets the queue list in the specific namespace.
*
* @param nsName the specific namespace.
* @return the set of queues exists in current namespace.
* @return error when have no authority to delete this namespace.
* @return error when the given timeout elapses before the list operation completes.
* @return error when the {@code ResourceManager} fails to list the namespace due to some internal error.
*/
ListQueues(nsName string) ([]string, error)
/**
* In order to enable consumers to get the message in the specified mode, the filter rule follows the sql standard
* to filter out messages.
*
* @param queueName queue name.
* @param filterString SQL expression to filter out messages.
* @return error when have no authority to add this filter.
* @return error when the given timeout elapses before the add filter operation completes.
* @return error when the {@code ResourceManager} fails to add a new filter due to some internal error.
*/
Filter(queueName string, filterString string) error
/**
* Routing from sourceQueue to targetQueue. Both queues are could be received messages after creating route action.
*
* @param sourceQueue source queue, process messages received from producer and duplicate those to target queue.
* @param targetQueue receive messages from source queue.
* @return error when have no authority to add this routing.
* @return error when the given timeout elapses before the routing operation completes.
* @return error when the {@code ResourceManager} fails to add a new routing due to some internal error.
*/
Routing(sourceQueue string, targetQueue string) error
} | openmessaging/manager/resource_manager.go | 0.925124 | 0.513546 | resource_manager.go | starcoder |
package resp
import (
"fmt"
"strconv"
)
const (
crByte = byte('\r')
nlByte = byte('\n')
whitespaceByte = byte(' ')
stringStartByte = byte('+')
integerStartByte = byte(':')
bulkStringStartByte = byte('$')
arrayStartByte = byte('*')
errorStartByte = byte('-')
)
// ErrorCodes used by server to communicate with client.
// These are not the REDIS standard error codes.
const (
InvalidByteSeq = "IVBYSEQ"
)
// The basic premise is as follows. The incoming message is parsed by an appropriate
// parser. If any of the parsers panic, we recover and return RedisError serialized
// to the client. Otherwise, we execute the command using CommandExecutor
// Assert a non-empty byte stream or panic otherwise
func assertNonEmptyStream(bytes []byte) {
if len(bytes) == 0 {
panic(NewRedisError(InvalidByteSeq, "Cannot parse empty byte stream"))
}
}
// Assert start start symbol of a byte stream (start byte) matches expected start byte (symbol)
func assertStartSymbol(startByte byte, symbol byte) {
if startByte != symbol {
panic(NewRedisError(InvalidByteSeq, fmt.Sprintf("Expected start byte to be %v, instead got %v", symbol, startByte)))
}
}
// Utility function to read a byte stream until CRLF and return the number of bytes consumed
// along with read bytes. This function can technically ignore the absence of a CR.
func readUntilCRLF(bytes []byte, excludeFirstByte bool) (string, int) {
str := ""
var c byte
read := 0
i := 0
if excludeFirstByte == true && len(bytes) > 0 {
i = 1
read = 1
}
// Initialize string
for ; i < len(bytes); i++ {
c = bytes[i]
read++
if c == nlByte {
break
}
if c != crByte {
str += string(c)
}
}
return str, read
}
// Parse a simple string from bytes and return parsed string and number of bytes consumed
func parseSimpleString(bytes []byte) (String, int) {
assertNonEmptyStream(bytes)
assertStartSymbol(bytes[0], stringStartByte)
str, i := readUntilCRLF(bytes, true)
// Return value and bytes read
return NewString(str), i
}
// Parse an error message. Clients do not typically send error messages.
func parseErrorMessage(bytes []byte) (RedisError, int) {
assertNonEmptyStream(bytes)
assertStartSymbol(bytes[0], errorStartByte)
var ecode string
var message string
var c byte
str := ""
i := 1
// Initialize string
for ; i < len(bytes); i++ {
c = bytes[i]
if c == whitespaceByte {
// Check if ecode is set
if ecode == "" {
ecode = str
// Reset string
str = ""
continue
}
}
if c == nlByte {
if ecode == "" {
ecode = str
break
} else {
message = str
break
}
}
if c != crByte {
str += string(c)
}
}
// Return value and bytes read
return NewRedisError(ecode, message), i + 1
}
// Parse a sequence of bytes as per Integer specification.
func parseIntegers(bytes []byte) (Integer, int) {
assertNonEmptyStream(bytes)
assertStartSymbol(bytes[0], integerStartByte)
str, i := readUntilCRLF(bytes, true)
// Return value and bytes read
conv, err := strconv.Atoi(str)
if err != nil {
panic(fmt.Sprintf("Invalid integer sequence supplied: %s", str))
}
return NewInteger(conv), i
}
// parse a sequence of bytes representing bulk string
func parseBulkString(bytes []byte) (BulkString, int) {
assertNonEmptyStream(bytes)
assertStartSymbol(bytes[0], bulkStringStartByte)
// Convert start symbol to : and parse as integer
bytes[0] = integerStartByte
str := ""
isNullValue := false
respInt, read := parseIntegers(bytes)
read2 := 0
// This check is much faster than the length check in constructor.
// It is safer to fail here.
if respInt.GetIntegerValue() > (MaxBulkSizeLength) {
panic("Bulk string length exceeds maximum allowed size of " + MaxBulkSizeAsHumanReadableValue)
} else if respInt.GetIntegerValue() < -1 {
panic("Bulk string length must be greater than -1")
} else {
switch respInt.GetIntegerValue() {
case 0:
// Short circuit
break
case -1:
// Null string
isNullValue = true
break
default:
// Regular parse
bytes = bytes[read:]
str, read2 = readUntilCRLF(bytes, false)
if len(str) != respInt.GetIntegerValue() {
panic(fmt.Sprintf("Bulk string length %d does not match expected length of %d", len(str), respInt.GetIntegerValue()))
}
break
}
}
if isNullValue {
return NewNullBulkString(), read + read2
}
bs, err := NewBulkString(str)
if err != nil {
panic(err)
}
return bs, read + read2
}
// parseArray parses a sequence of bytes as per RESP array
// specifications. Clients typically send commands as Array
func parseArray(bytes []byte) (*Array, int) {
assertNonEmptyStream(bytes)
assertStartSymbol(bytes[0], arrayStartByte)
bytesRead := 0
// Reset to colon so we can parse integer
bytes[0] = integerStartByte
numberOfItems, n := parseIntegers(bytes)
bytesRead += n
// Create new Array
Array, err := NewArray(numberOfItems.GetIntegerValue())
if err != nil {
panic(err)
}
counter := 0
// Advance bytes
bytes = bytes[n:]
for {
if len(bytes) == 0 {
break
}
if counter >= Array.GetNumberOfItems() {
panic(fmt.Sprintf("Invalid command stream. RESP Array index %d exceeds specified capacity of %s", counter+1, numberOfItems.ToString()))
}
first := bytes[0]
var s IDataType
var r int
switch first {
case stringStartByte:
s, r = parseSimpleString(bytes)
case integerStartByte:
s, r = parseIntegers(bytes)
case bulkStringStartByte:
s, r = parseBulkString(bytes)
case errorStartByte:
s, r = parseErrorMessage(bytes)
default:
panic("Unknown start byte " + string(first))
}
// Append to chunks
Array.SetItemAtIndex(counter, s)
// Advance by r bytes
bytes = bytes[r:]
// Add to bytes read
bytesRead += r
// Increase counter
counter++
}
return Array, bytesRead
}
// Get the next array start byte starting from offset 1
func getNextArrayStartByteIndex(bytes []byte) int {
for i := 1; i < len(bytes); i++ {
if bytes[i] == arrayStartByte {
return i
}
}
return len(bytes)
}
// ParseRedisClientRequest takes in a sequence of bytes, and parses them
// as sequential Array entries. Each command in a pipeline will form
// a Array. This method catches internal panics, and returns top level
// errors as RedisError. The caller can then check if the error is EmptyRedisError
// and return appropriately
func ParseRedisClientRequest(bytes []byte) (commands []Array, totalBytes int, finalErr RedisError) {
commands = make([]Array, 0)
totalBytesRead := 0
finalErr = EmptyRedisError
// Top level panic recovery
defer func() {
if r := recover(); r != nil {
switch re := r.(type) {
case RedisError:
finalErr = re
case string:
finalErr = NewRedisError(DefaultErrorKeyword, re)
default:
fmt.Println(r)
// We don't know what caused this, so we return generic error
finalErr = NewDefaultRedisError(fmt.Sprint(r))
}
}
}()
for len(bytes) > 0 {
// For pipelines, we read until next arrayStartByte
asbIndex := getNextArrayStartByteIndex(bytes)
command, read := parseArray(bytes[0:asbIndex])
if read > 0 {
// Add command to commands list
commands = append(commands, *command)
// Reset bytest
bytes = bytes[read:]
totalBytesRead += read
} else {
break
}
}
// Execute commands on top of syncmap
return commands, totalBytesRead, finalErr
} | resp/parsers.go | 0.672654 | 0.476336 | parsers.go | starcoder |
package main
import (
"fmt"
"log"
"math"
"github.com/unixpickle/model3d/model2d"
"github.com/unixpickle/model3d/model3d"
"github.com/unixpickle/model3d/render3d"
"github.com/unixpickle/model3d/toolbox3d"
)
const (
Thickness = 0.15
PartSpacing = 0.01
EtchInset = 0.05
AxleRadius = 0.15
HolderRadius = 0.3
OrbitRadius = 0.6
CircleRadius = 0.4
EtchRadius = 0.4
)
func main() {
squeeze := &toolbox3d.AxisSqueeze{
Axis: toolbox3d.AxisZ,
Min: -(Thickness - 0.01 - EtchInset),
Max: Thickness - 0.01 - EtchInset,
Ratio: 0.1,
}
log.Println("Creating axle mesh...")
mesh := MarchTransform(CreateAxle(), squeeze)
mesh = MarchTransform(CreateAxle(), model3d.JoinedTransform{
&toolbox3d.AxisSqueeze{
Axis: toolbox3d.AxisZ,
Min: mesh.Max().Z - 0.01,
Max: mesh.Max().Z + 0.01,
Ratio: 2.0,
},
squeeze,
&toolbox3d.AxisSqueeze{
Axis: toolbox3d.AxisZ,
Min: mesh.Min().Z - 0.01,
Max: mesh.Min().Z + 0.01,
Ratio: 2.0,
},
})
log.Println("Creating body mesh...")
mesh.AddMesh(MarchTransform(CreateBody(), model3d.JoinedTransform{
&toolbox3d.AxisPinch{
Axis: toolbox3d.AxisZ,
Min: -(Thickness + 0.01),
Max: -(Thickness - 0.01),
Power: 0.25,
},
&toolbox3d.AxisPinch{
Axis: toolbox3d.AxisZ,
Min: Thickness - 0.01,
Max: Thickness + 0.01,
Power: 0.25,
},
squeeze,
}))
log.Println("Post-processing mesh...")
mesh = mesh.EliminateCoplanar(1e-5)
log.Println("Saving mesh...")
mesh.SaveGroupedSTL("spinner.stl")
log.Println("Saving rendering of mesh...")
render3d.SaveRendering("rendering.png", mesh, model3d.Coord3D{Y: 2, Z: 2}, 400, 400, nil)
}
func MarchTransform(solid model3d.Solid, t model3d.Transform) *model3d.Mesh {
return model3d.MarchingCubesConj(solid, 0.003, 8, t)
}
func CreateAxle() model3d.Solid {
return &model3d.SubtractedSolid{
Positive: model3d.JoinedSolid{
&model3d.Cylinder{
P1: model3d.Coord3D{Z: -(Thickness + PartSpacing)},
P2: model3d.Coord3D{Z: Thickness + PartSpacing},
Radius: AxleRadius - PartSpacing,
},
&model3d.Cylinder{
P1: model3d.Coord3D{Z: -(Thickness + PartSpacing)},
P2: model3d.Coord3D{Z: -(Thickness + PartSpacing) * 1.5},
Radius: HolderRadius,
},
&model3d.Cylinder{
P1: model3d.Coord3D{Z: (Thickness + PartSpacing)},
P2: model3d.Coord3D{Z: (Thickness + PartSpacing) * 1.5},
Radius: HolderRadius,
},
},
Negative: model3d.JoinedSolid{
&model3d.Sphere{
Center: model3d.Coord3D{Z: -(Thickness+PartSpacing)*1.5 - 1.0},
Radius: 1.05,
},
&model3d.Sphere{
Center: model3d.Coord3D{Z: (Thickness+PartSpacing)*1.5 + 1.0},
Radius: 1.05,
},
},
}
}
func CreateBody() model3d.Solid {
var circles model3d.JoinedSolid
for i, theta := range []float64{0, math.Pi * 2 / 3, math.Pi * 4 / 3} {
etching := NewEtchedImage(fmt.Sprintf("side_%d.png", i+1), theta)
circles = append(circles, &model3d.SubtractedSolid{
Positive: &model3d.Cylinder{
P1: model3d.Coord3D{
X: etching.X,
Y: etching.Y,
Z: -Thickness,
},
P2: model3d.Coord3D{
X: etching.X,
Y: etching.Y,
Z: Thickness,
},
Radius: CircleRadius,
},
Negative: etching,
})
}
return &model3d.SubtractedSolid{
// Add a middle circle to hold things together.
Positive: append(circles, &model3d.Cylinder{
P1: model3d.Coord3D{Z: -Thickness},
P2: model3d.Z(Thickness),
Radius: CircleRadius,
}),
// Hole for axle.
Negative: &model3d.Cylinder{
P1: model3d.Coord3D{Z: -(Thickness + 1e-5)},
P2: model3d.Coord3D{Z: Thickness + 1e-5},
Radius: AxleRadius,
},
}
}
type EtchedImage struct {
Solid model2d.Solid
X float64
Y float64
Radius float64
}
func NewEtchedImage(path string, theta float64) *EtchedImage {
bmp := model2d.MustReadBitmap(path, nil)
mesh := bmp.Mesh().Smooth(100)
collider := model2d.MeshToCollider(mesh)
solid := model2d.NewColliderSolid(collider)
return &EtchedImage{
Solid: model2d.ScaleSolid(solid, 1/float64(bmp.Width)),
X: OrbitRadius * math.Sin(theta),
Y: OrbitRadius * math.Cos(theta),
Radius: CircleRadius,
}
}
func (e *EtchedImage) Min() model3d.Coord3D {
return model3d.XYZ(e.X-e.Radius, e.Y-e.Radius, -(Thickness + 1e-5))
}
func (e *EtchedImage) Max() model3d.Coord3D {
return model3d.XYZ(e.X+e.Radius, e.Y+e.Radius, Thickness+1e-5)
}
func (e *EtchedImage) Contains(c model3d.Coord3D) bool {
if !model3d.InBounds(e, c) {
return false
}
if math.Abs(c.Z) > Thickness || math.Abs(c.Z) < Thickness-EtchInset {
return false
}
axis1 := model3d.Coord2D{X: e.X, Y: e.Y}
axis1 = axis1.Scale(1 / (axis1.Norm() * e.Radius))
axis2 := model3d.Coord2D{X: -axis1.Y, Y: axis1.X}
if c.Z < 0 {
// Flip image on under-side of spinner.
axis2 = axis2.Scale(-1)
}
p := model3d.Coord2D{X: c.X - e.X, Y: c.Y - e.Y}
x := (axis2.Dot(p) + 1) / 2
y := (axis1.Dot(p) + 1) / 2
return e.Solid.Contains(model2d.Coord{X: x, Y: y})
} | examples/toys/fidget_spinner/main.go | 0.586168 | 0.407392 | main.go | starcoder |
package dsp
import (
"fmt"
"github.com/brettbuddin/musictheory"
)
// Valuer is the wrapper interface around the Value method; which is used in obtaining the constant value
type Valuer interface {
Float64() float64
}
// Float64 is a wrapper for float64 that implements Valuer
type Float64 float64
// Float64 returns the constant value
func (v Float64) Float64() float64 { return float64(v) }
func (v Float64) String() string { return fmt.Sprintf("%.2f", v) }
// Hz represents cycles-per-second
type Hz struct {
Valuer
Raw float64
}
// Frequency returns a scalar value in Hz
func Frequency(v float64, sampleRate int) Hz {
return Hz{Raw: v, Valuer: Float64(v / float64(sampleRate))}
}
// Float64 returns the constant value
func (hz Hz) Float64() float64 {
if hz.Valuer == nil {
return 0
}
return hz.Valuer.Float64()
}
func (hz Hz) String() string { return fmt.Sprintf("%.2fHz", hz.Raw) }
// ParsePitch parses the scientific notation of a pitch
func ParsePitch(v string, sampleRate int) (Pitch, error) {
p, err := musictheory.ParsePitch(v)
if err != nil {
return Pitch{}, err
}
return newPitch(p, sampleRate, v), nil
}
// NewPitch creates a Pitch
func NewPitch(p musictheory.Pitch, sampleRate int) Pitch {
return newPitch(p, sampleRate, "")
}
func newPitch(p musictheory.Pitch, sampleRate int, rawName string) Pitch {
return Pitch{
Valuer: Frequency(p.Freq(), sampleRate),
Pitch: p,
Raw: rawName,
}
}
// Pitch is a pitch that has been expressed in scientific notation
type Pitch struct {
Valuer
Pitch musictheory.Pitch
Raw string
}
// Float64 returns the constant value
func (p Pitch) Float64() float64 {
if p.Valuer == nil {
return 0
}
return p.Valuer.Float64()
}
func (p Pitch) String() string {
if p.Raw == "" {
return p.Pitch.Name(musictheory.DescNames)
}
return p.Raw
}
// Transpose transposes the pitch by some interval
func (p Pitch) Transpose(interval musictheory.Interval, sampleRate int) Pitch {
return newPitch(p.Pitch.Transpose(interval), sampleRate, "")
}
// MS is a value representation of milliseconds
type MS struct {
Valuer
Raw float64
}
// DurationInt returns a scalar value (int) in MS
func DurationInt(v, sampleRate int) MS { return Duration(float64(v), sampleRate) }
// Duration returns a scalar value (float64) in MS
func Duration(v float64, sampleRate int) MS {
return MS{
Valuer: Float64(v * float64(sampleRate) * 0.001),
Raw: v,
}
}
// Float64 returns the constant value
func (ms MS) Float64() float64 {
if ms.Valuer == nil {
return 0
}
return ms.Valuer.Float64()
}
func (ms MS) String() string { return fmt.Sprintf("%.2fms", ms.Raw) }
// BeatsPerMin represents beats-per-minute
type BeatsPerMin struct {
Valuer
Raw float64
}
// BPM returns a scalar value in beats-per-minute
func BPM(v float64, sampleRate int) BeatsPerMin {
return BeatsPerMin{
Valuer: Float64(v / 60 / float64(sampleRate)),
Raw: v,
}
}
// Float64 returns the constant value
func (bpm BeatsPerMin) Float64() float64 {
if bpm.Valuer == nil {
return 0
}
return bpm.Valuer.Float64()
}
func (bpm BeatsPerMin) String() string { return fmt.Sprintf("%.2fBPM", bpm.Raw) } | dsp/values.go | 0.897634 | 0.580352 | values.go | starcoder |
package main
import (
"bufio"
"flag"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
)
const (
clear marker = iota
opaque marker = iota + 10 // +10 so we can use 1-9 as bomb markers
bomb
)
type marker byte
func (m marker) String() string {
switch m {
case opaque:
return "."
case bomb:
return "B"
case clear:
return " "
case 1, 2, 3, 4, 5, 6, 7, 8, 9:
return string('0' + m)
default:
return "?"
}
}
type grid [][]marker
func (g grid) line() {
fmt.Println(" " + strings.Repeat("----", len(g)))
}
func (g grid) show() {
// Header
fmt.Print(" ")
for x := range g {
fmt.Printf(" %2d ", x+1)
}
fmt.Println()
g.line()
// the matrix
for y, row := range g {
fmt.Printf(" %2d |", y+1)
for _, col := range row {
fmt.Printf(" %s |", col)
}
fmt.Println()
g.line()
}
}
func (g grid) valid(x, y int) bool {
return x >= 0 && x < len(g) && y >= 0 && y < len(g)
}
func (g grid) bombCheck(x, y int) int {
if g.valid(x, y) && (g[y][x] == bomb) {
return 1
}
return 0
}
func (g grid) nearby(x, y int) int {
// skip if the square is a bomb itself
if g.bombCheck(x, y) == 1 {
return 0
}
// clockwise evaluation makes it clear all neighbors are checked
count := 0
count += g.bombCheck(x, y-1) // top
count += g.bombCheck(x+1, y-1) // top-right
count += g.bombCheck(x+1, y) // right
count += g.bombCheck(x+1, y+1) // bottom-right
count += g.bombCheck(x, y+1) // bottom
count += g.bombCheck(x-1, y+1) // bottom-left
count += g.bombCheck(x-1, y) // left
count += g.bombCheck(x-1, y-1) // top-left
return count
}
func newGrid(size int) grid {
a := make(grid, size)
for i := range a {
a[i] = make([]marker, size)
}
return a
}
func populate(size, count int, g grid) grid {
for count > 0 {
x := rand.Intn(size)
y := rand.Intn(size)
if g[y][x] != bomb {
g[y][x] = bomb
count--
}
}
// mark counts for cells neighboring a bomb
for y := range g {
for x := range g[y] {
if count := g.nearby(x, y); count > 0 {
g[y][x] = marker(count)
}
}
}
return g
}
// make an fresh 'opaque' board
func wipe(g grid) grid {
for _, row := range g {
for x := range row {
row[x] = opaque
}
}
return g
}
// Board represents the minesweeper game
type Board struct {
Shown grid
Mines grid
Remaining int
}
// Prompt gets the next move of the game
func (b *Board) Prompt() (bool, int, int) {
scanner := bufio.NewScanner(os.Stdin)
for {
msg := " [%d] (preface with 'b' to mark bomb) cell: "
fmt.Printf(msg, b.Remaining)
scanner.Scan()
reply := strings.TrimSpace(scanner.Text())
if reply == "" {
continue
}
if strings.EqualFold(reply, "q") {
os.Exit(0)
}
f := strings.Fields(reply)
if len(f) < 2 {
fmt.Println("incomplete response!")
continue
}
marked := strings.EqualFold(f[0], "b")
if marked {
f = f[1:]
// ignore anything after second element....
if len(f) < 2 {
fmt.Println("incomplete!")
continue
}
}
x, err := strconv.Atoi(f[0])
if err != nil {
fmt.Println("invalid data:", err)
continue
}
y, err := strconv.Atoi(f[1])
if err != nil {
fmt.Println("invalid data:", err)
continue
}
// UI has 1-based arrays, but internally we use 0-based
return marked, x - 1, y - 1
}
panic("never here")
}
// Move will move through the game until the end
func (b *Board) Move() bool {
for {
fmt.Println()
b.Shown.show()
marked, x, y := b.Prompt()
if marked {
b.Shown[y][x] = bomb
b.Remaining--
continue
}
if b.Mines[y][x] == bomb {
b.Mines.show()
fmt.Println()
w := (len(b.Mines) * 4) + 4
fmt.Println(center("K A B O O M !", w))
fmt.Println()
os.Exit(1)
}
b.Sweep(x, y)
}
return false
}
// Sweep clears all empty tiles surrounding the selected cel
func (b *Board) Sweep(x, y int) {
// make sure we haven't wandered off the grid
if !b.Mines.valid(x, y) {
return
}
// already cleared?
if b.Shown[y][x] == clear {
return
}
// got a bomb count?
tile := b.Mines[y][x]
if int(tile) > 0 {
b.Shown[y][x] = tile
return
}
// clearing one tile at a time...
if tile == clear {
b.Shown[y][x] = tile
}
// recursive walk
b.Sweep(x-1, y) // left
b.Sweep(x+1, y) // right
b.Sweep(x, y-1) // up
b.Sweep(x, y+1) // down
}
// NewBoard returns a new minesweeper game
func NewBoard(size, count int) *Board {
return &Board{
Mines: populate(size, count, newGrid(size)),
Shown: wipe(newGrid(size)),
Remaining: count,
}
}
// center prints the string in the center per w
func center(s string, w int) string {
return fmt.Sprintf("%[1]*s", -w, fmt.Sprintf("%[1]*s", (w+len(s))/2, s))
}
func main() {
size := 10
count := 5
flag.IntVar(&size, "size", size, "grid size")
flag.IntVar(&count, "count", count, "number of mines")
flag.Parse()
// make sure input was valid (was passing args w/o flags and ignoring it
if len(flag.Args()) > 0 {
fmt.Println("unknown args:", flag.Args())
os.Exit(1)
}
board := NewBoard(size, count)
board.Move()
} | main.go | 0.568895 | 0.439807 | main.go | starcoder |
package sema
import "github.com/onflow/cadence/runtime/ast"
type CheckCastVisitor struct {
exprInferredType Type
targetType Type
}
var _ ast.ExpressionVisitor = &CheckCastVisitor{}
func (d *CheckCastVisitor) IsRedundantCast(expr ast.Expression, exprInferredType, targetType Type) bool {
prevInferredType := d.exprInferredType
prevTargetType := d.targetType
defer func() {
d.exprInferredType = prevInferredType
d.targetType = prevTargetType
}()
d.exprInferredType = exprInferredType
d.targetType = targetType
result := expr.AcceptExp(d)
return result.(bool)
}
func (d *CheckCastVisitor) VisitBoolExpression(_ *ast.BoolExpression) ast.Repr {
return d.isTypeRedundant(BoolType, d.targetType)
}
func (d *CheckCastVisitor) VisitNilExpression(_ *ast.NilExpression) ast.Repr {
return d.isTypeRedundant(NilType, d.targetType)
}
func (d *CheckCastVisitor) VisitIntegerExpression(_ *ast.IntegerExpression) ast.Repr {
// For integer expressions, default inferred type is `Int`.
// So, if the target type is not `Int`, then the cast is not redundant.
return d.isTypeRedundant(IntType, d.targetType)
}
func (d *CheckCastVisitor) VisitFixedPointExpression(expr *ast.FixedPointExpression) ast.Repr {
if expr.Negative {
// Default inferred type for fixed-point expressions with sign is `Fix64Type`.
return d.isTypeRedundant(Fix64Type, d.targetType)
}
// Default inferred type for fixed-point expressions without sign is `UFix64Type`.
return d.isTypeRedundant(UFix64Type, d.targetType)
}
func (d *CheckCastVisitor) VisitArrayExpression(expr *ast.ArrayExpression) ast.Repr {
// If the target type is `ConstantSizedType`, then it is not redundant.
// Because array literals are always inferred to be `VariableSizedType`,
// unless specified.
targetArrayType, ok := d.targetType.(*VariableSizedType)
if !ok {
return false
}
inferredArrayType, ok := d.exprInferredType.(ArrayType)
if !ok {
return false
}
for _, element := range expr.Values {
// If at-least one element uses the target-type to infer the expression type,
// then the casting is not redundant.
if !d.IsRedundantCast(
element,
inferredArrayType.ElementType(false),
targetArrayType.ElementType(false),
) {
return false
}
}
return true
}
func (d *CheckCastVisitor) VisitDictionaryExpression(expr *ast.DictionaryExpression) ast.Repr {
targetDictionaryType, ok := d.targetType.(*DictionaryType)
if !ok {
return false
}
inferredDictionaryType, ok := d.exprInferredType.(*DictionaryType)
if !ok {
return false
}
for _, entry := range expr.Entries {
// If at-least one key or value uses the target-type to infer the expression type,
// then the casting is not redundant.
if !d.IsRedundantCast(
entry.Key,
inferredDictionaryType.KeyType,
targetDictionaryType.KeyType,
) {
return false
}
if !d.IsRedundantCast(
entry.Value,
inferredDictionaryType.ValueType,
targetDictionaryType.ValueType,
) {
return false
}
}
return true
}
func (d *CheckCastVisitor) VisitIdentifierExpression(_ *ast.IdentifierExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitInvocationExpression(_ *ast.InvocationExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitMemberExpression(_ *ast.MemberExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitIndexExpression(_ *ast.IndexExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitConditionalExpression(conditionalExpr *ast.ConditionalExpression) ast.Repr {
return d.IsRedundantCast(conditionalExpr.Then, d.exprInferredType, d.targetType) &&
d.IsRedundantCast(conditionalExpr.Else, d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitUnaryExpression(_ *ast.UnaryExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitBinaryExpression(_ *ast.BinaryExpression) ast.Repr {
// Binary expressions are not straight-forward to check.
// Hence skip checking redundant casts for now.
return false
}
func (d *CheckCastVisitor) VisitFunctionExpression(_ *ast.FunctionExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitStringExpression(_ *ast.StringExpression) ast.Repr {
return d.isTypeRedundant(StringType, d.targetType)
}
func (d *CheckCastVisitor) VisitCastingExpression(_ *ast.CastingExpression) ast.Repr {
// This is already covered under Case-I: where expected type is same as casted type.
// So skip checking it here to avid duplicate errors.
return false
}
func (d *CheckCastVisitor) VisitCreateExpression(_ *ast.CreateExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitDestroyExpression(_ *ast.DestroyExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitReferenceExpression(_ *ast.ReferenceExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitForceExpression(_ *ast.ForceExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) VisitPathExpression(_ *ast.PathExpression) ast.Repr {
return d.isTypeRedundant(d.exprInferredType, d.targetType)
}
func (d *CheckCastVisitor) isTypeRedundant(exprType, targetType Type) bool {
// If there is no expected type (e.g: var-decl with no type annotation),
// then the simple-cast might be used as a way of marking the type of the variable.
// Therefore, it is ok for the target type to be a super-type.
// But being the exact type as expression's type is redundant.
// e.g:
// var x: Int8 = 5
// var y = x as Int8 // <-- not ok: `y` will be of type `Int8` with/without cast
// var y = x as Integer // <-- ok : `y` will be of type `Integer`
return exprType != nil &&
exprType.Equal(targetType)
} | runtime/sema/check_cast_visitor.go | 0.72526 | 0.455622 | check_cast_visitor.go | starcoder |
package gabor
import (
"math"
"github.com/emer/etable/etable"
"github.com/emer/etable/etensor"
"github.com/goki/mat32"
)
// gabor.Filter specifies a gabor filter function,
// i.e., a 2d Gaussian envelope times a sinusoidal plane wave.
// By default it produces 2 phase asymmetric edge detector filters.
type Filter struct {
On bool `desc:"is this filter active?"`
Wt float32 `viewif:"On" desc:"how much relative weight does this filter have when combined with other filters"`
Gain float32 `viewif:"On" def:"2" desc:"overall gain multiplier applied after filtering -- only relevant if not using renormalization (otherwize it just gets renormed away)"`
Size int `viewif:"On" desc:"size of the overall filter -- number of pixels wide and tall for a square matrix used to encode the filter -- filter is centered within this square -- typically an even number, min effective size ~6"`
WvLen float32 `viewif:"On" desc:"wavelength of the sine waves -- number of pixels over which a full period of the wave takes place -- typically same as Size (computation adds a 2 PI factor to translate into pixels instead of radians)"`
Spacing int `viewif:"On" desc:"how far apart to space the centers of the gabor filters -- 1 = every pixel, 2 = every other pixel, etc -- high-res should be 1 or 2, lower res can be increments therefrom"`
SigLen float32 `viewif:"On" def:"0.3" desc:"gaussian sigma for the length dimension (elongated axis perpendicular to the sine waves) -- as a normalized proportion of filter Size"`
SigWd float32 `viewif:"On" def:"0.15,0.2" desc:"gaussian sigma for the width dimension (in the direction of the sine waves) -- as a normalized proportion of filter size"`
Phase float32 `viewif:"On" def:"0,90" desc:"phase offset for the sine wave, in degrees -- 0 = asymmetric sine wave, 90 = symmetric cosine wave"`
CircleEdge bool `viewif:"On" def:"true" desc:"cut off the filter (to zero) outside a circle of diameter = Size -- makes the filter more radially symmetric"`
NAngles int `viewif:"On" def:"4" desc:"number of different angles of overall gabor filter orientation to use -- first angle is always horizontal"`
}
func (gf *Filter) Defaults() {
gf.On = true
gf.Wt = 1
gf.Gain = 2
gf.Size = 6
gf.Spacing = 2
gf.WvLen = 6
gf.SigLen = 0.3
gf.SigWd = 0.2
gf.Phase = 0
gf.CircleEdge = true
gf.NAngles = 4
}
func (gf *Filter) Update() {
}
// SetSize sets the size and WvLen to same value, and also sets spacing
// these are the main params that need to be varied for standard V1 gabors
func (gf *Filter) SetSize(sz, spc int) {
gf.Size = sz
gf.WvLen = float32(sz)
gf.Spacing = spc
}
// ToTensor renders filters into the given etable etensor.Tensor,
// setting dimensions to [angle][Y][X] where Y = X = Size
func (gf *Filter) ToTensor(tsr *etensor.Float32) {
tsr.SetShape([]int{gf.NAngles, gf.Size, gf.Size}, nil, []string{"Angles", "Y", "X"})
ctr := 0.5 * float32(gf.Size-1)
angInc := math.Pi / float32(gf.NAngles)
radius := float32(gf.Size) * 0.5
gsLen := gf.SigLen * float32(gf.Size)
gsWd := gf.SigWd * float32(gf.Size)
lenNorm := 1.0 / (2.0 * gsLen * gsLen)
wdNorm := 1.0 / (2.0 * gsWd * gsWd)
twoPiNorm := (2.0 * math.Pi) / gf.WvLen
phsRad := mat32.DegToRad(gf.Phase)
for ang := 0; ang < gf.NAngles; ang++ {
angf := -float32(ang) * angInc
posSum := float32(0)
negSum := float32(0)
for x := 0; x < gf.Size; x++ {
for y := 0; y < gf.Size; y++ {
xf := float32(x) - ctr
yf := float32(y) - ctr
dist := mat32.Hypot(xf, yf)
val := float32(0)
if !(gf.CircleEdge && (dist > radius)) {
nx := xf*mat32.Cos(angf) - yf*mat32.Sin(angf)
ny := yf*mat32.Cos(angf) + xf*mat32.Sin(angf)
gauss := mat32.Exp(-(lenNorm*(nx*nx) + wdNorm*(ny*ny)))
sin := mat32.Sin(twoPiNorm*ny + phsRad)
val = gauss * sin
if val > 0 {
posSum += val
} else if val < 0 {
negSum += -val
}
}
tsr.Set([]int{ang, y, x}, val)
}
}
// renorm each half
posNorm := float32(1) / posSum
negNorm := float32(1) / negSum
for x := 0; x < gf.Size; x++ {
for y := 0; y < gf.Size; y++ {
val := tsr.Value([]int{ang, y, x})
if val > 0 {
val *= posNorm
} else if val < 0 {
val *= negNorm
}
tsr.Set([]int{ang, y, x}, val)
}
}
}
}
// ToTable renders filters into the given etable.Table
// setting a column named Angle to the angle and
// a column named Gabor to the filter for that angle.
// This is useful for display and validation purposes.
func (gf *Filter) ToTable(tab *etable.Table) {
tab.SetFromSchema(etable.Schema{
{"Angle", etensor.FLOAT32, nil, nil},
{"Filter", etensor.FLOAT32, []int{gf.NAngles, gf.Size, gf.Size}, []string{"Angle", "Y", "X"}},
}, gf.NAngles)
gf.ToTensor(tab.Cols[1].(*etensor.Float32))
angInc := math.Pi / float32(gf.NAngles)
for ang := 0; ang < gf.NAngles; ang++ {
angf := mat32.RadToDeg(-float32(ang) * angInc)
tab.SetCellFloatIdx(0, ang, float64(-angf))
}
} | gabor/gabor.go | 0.681833 | 0.524395 | gabor.go | starcoder |
package math3D
import (
"fmt"
)
type Matrix struct {
Data [][]float64
}
func NewMatrix(row []float64) *Matrix {
ret := new(Matrix)
ret.AddRow(row)
return ret
}
func (m *Matrix) AddRow(row []float64) *Matrix {
m.Data = append(m.Data, row)
return m
}
func (m *Matrix) At(row, col int) float64 {
return m.Data[row][col]
}
func (m *Matrix) GetNbRows() int {
return len(m.Data)
}
func (m *Matrix) GetNbCols() int {
return len(m.Data[0])
}
func (m *Matrix) GetRow(i int) *Matrix {
ret := new(Matrix)
ret.AddRow(m.Data[i])
return ret
}
func (m *Matrix) GetCol(j int) *Matrix {
ret := new(Matrix)
col := make([]float64, 0)
for i := 0; i < m.GetNbRows(); i++ {
col = append(col, m.Data[i][j])
}
ret.AddRow(col)
return ret
}
func (m *Matrix) Copy() *Matrix {
ret := Matrix{}
copy(m.Data, ret.Data)
return &ret
}
func (m *Matrix) Equals(m2 *Matrix) bool {
if len(m.Data) != len(m2.Data) {
return false
}
for i := 0; i < len(m.Data); i++ {
for j := 0; j < len(m.Data[i]); j++ {
if m.Data[i][j] != m2.Data[i][j] {
return false
}
}
}
return true
}
func (m *Matrix) Transpose() *Matrix {
ret := new(Matrix)
for j := 0; j < m.GetNbCols(); j++ {
col := make([]float64, 0)
for i := 0; i < m.GetNbRows(); i++ {
col = append(col, m.At(i, j))
}
ret.AddRow(col)
}
return ret
}
func (m1 *Matrix) Product(m2 *Matrix) *Matrix {
if m1.GetNbCols() != m2.GetNbRows() {
panic(fmt.Sprintf("Unable to multiply matrices : %+v, %+v", m1, m2))
}
matProd := new(Matrix)
for i := 0; i < m1.GetNbRows(); i++ {
curRow := m1.GetRow(i)
rowProd := make([]float64, 0)
for j := 0; j < m2.GetNbCols(); j++ {
curCol := m2.GetCol(j)
val := mult(curRow.Data[0], curCol.Data[0])
rowProd = append(rowProd, val)
}
matProd.AddRow(rowProd)
}
return matProd
}
func (m *Matrix) ScalarMultiply(s float64) *Matrix {
ret := new(Matrix)
for i := 0; i < m.GetNbRows(); i++ {
row := make([]float64, 0)
for j := 0; j < m.GetNbCols(); j++ {
row = append(row, s*m.Data[i][j])
}
ret.AddRow(row)
}
return ret
}
func mult(a1, a2 []float64) float64 {
ret := 0.0
for i := 0; i < len(a1); i++ {
ret += a1[i] * a2[i]
}
return ret
}
func (m1 *Matrix) Add(m2 *Matrix) *Matrix {
if m1.GetNbCols() != m2.GetNbCols() || m1.GetNbRows() != m2.GetNbRows() {
panic(fmt.Sprintf("Unable to add matrices: %+v, %+v", m1, m2))
}
m := new(Matrix)
for i := 0; i < len(m1.Data); i++ {
row := make([]float64, 0)
for j := 0; j < len(m1.Data[i]); j++ {
row = append(row, m1.Data[i][j]+m2.Data[i][j])
}
m.AddRow(row)
}
return m
} | math3D/matrix.go | 0.685739 | 0.46035 | matrix.go | starcoder |
package graph
import (
i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization"
)
// WorkbookRangeView
type WorkbookRangeView struct {
Entity
// Represents the cell addresses
cellAddresses *Json;
// Returns the number of visible columns. Read-only.
columnCount *int32;
// Represents the formula in A1-style notation.
formulas *Json;
// Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English '=SUM(A1, 1.5)' formula would become '=SUMME(A1; 1,5)' in German.
formulasLocal *Json;
// Represents the formula in R1C1-style notation.
formulasR1C1 *Json;
// Index of the range.
index *int32;
// Represents Excel's number format code for the given cell. Read-only.
numberFormat *Json;
// Returns the number of visible rows. Read-only.
rowCount *int32;
// Represents a collection of range views associated with the range. Read-only. Read-only.
rows []WorkbookRangeView;
// Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only.
text *Json;
// Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.
values *Json;
// Represents the type of data of each cell. Read-only. The possible values are: Unknown, Empty, String, Integer, Double, Boolean, Error.
valueTypes *Json;
}
// NewWorkbookRangeView instantiates a new workbookRangeView and sets the default values.
func NewWorkbookRangeView()(*WorkbookRangeView) {
m := &WorkbookRangeView{
Entity: *NewEntity(),
}
return m
}
// GetCellAddresses gets the cellAddresses property value. Represents the cell addresses
func (m *WorkbookRangeView) GetCellAddresses()(*Json) {
if m == nil {
return nil
} else {
return m.cellAddresses
}
}
// GetColumnCount gets the columnCount property value. Returns the number of visible columns. Read-only.
func (m *WorkbookRangeView) GetColumnCount()(*int32) {
if m == nil {
return nil
} else {
return m.columnCount
}
}
// GetFormulas gets the formulas property value. Represents the formula in A1-style notation.
func (m *WorkbookRangeView) GetFormulas()(*Json) {
if m == nil {
return nil
} else {
return m.formulas
}
}
// GetFormulasLocal gets the formulasLocal property value. Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English '=SUM(A1, 1.5)' formula would become '=SUMME(A1; 1,5)' in German.
func (m *WorkbookRangeView) GetFormulasLocal()(*Json) {
if m == nil {
return nil
} else {
return m.formulasLocal
}
}
// GetFormulasR1C1 gets the formulasR1C1 property value. Represents the formula in R1C1-style notation.
func (m *WorkbookRangeView) GetFormulasR1C1()(*Json) {
if m == nil {
return nil
} else {
return m.formulasR1C1
}
}
// GetIndex gets the index property value. Index of the range.
func (m *WorkbookRangeView) GetIndex()(*int32) {
if m == nil {
return nil
} else {
return m.index
}
}
// GetNumberFormat gets the numberFormat property value. Represents Excel's number format code for the given cell. Read-only.
func (m *WorkbookRangeView) GetNumberFormat()(*Json) {
if m == nil {
return nil
} else {
return m.numberFormat
}
}
// GetRowCount gets the rowCount property value. Returns the number of visible rows. Read-only.
func (m *WorkbookRangeView) GetRowCount()(*int32) {
if m == nil {
return nil
} else {
return m.rowCount
}
}
// GetRows gets the rows property value. Represents a collection of range views associated with the range. Read-only. Read-only.
func (m *WorkbookRangeView) GetRows()([]WorkbookRangeView) {
if m == nil {
return nil
} else {
return m.rows
}
}
// GetText gets the text property value. Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only.
func (m *WorkbookRangeView) GetText()(*Json) {
if m == nil {
return nil
} else {
return m.text
}
}
// GetValues gets the values property value. Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.
func (m *WorkbookRangeView) GetValues()(*Json) {
if m == nil {
return nil
} else {
return m.values
}
}
// GetValueTypes gets the valueTypes property value. Represents the type of data of each cell. Read-only. The possible values are: Unknown, Empty, String, Integer, Double, Boolean, Error.
func (m *WorkbookRangeView) GetValueTypes()(*Json) {
if m == nil {
return nil
} else {
return m.valueTypes
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *WorkbookRangeView) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["cellAddresses"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetCellAddresses(val.(*Json))
}
return nil
}
res["columnCount"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetColumnCount(val)
}
return nil
}
res["formulas"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetFormulas(val.(*Json))
}
return nil
}
res["formulasLocal"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetFormulasLocal(val.(*Json))
}
return nil
}
res["formulasR1C1"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetFormulasR1C1(val.(*Json))
}
return nil
}
res["index"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetIndex(val)
}
return nil
}
res["numberFormat"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetNumberFormat(val.(*Json))
}
return nil
}
res["rowCount"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetRowCount(val)
}
return nil
}
res["rows"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewWorkbookRangeView() })
if err != nil {
return err
}
if val != nil {
res := make([]WorkbookRangeView, len(val))
for i, v := range val {
res[i] = *(v.(*WorkbookRangeView))
}
m.SetRows(res)
}
return nil
}
res["text"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetText(val.(*Json))
}
return nil
}
res["values"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetValues(val.(*Json))
}
return nil
}
res["valueTypes"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetValueTypes(val.(*Json))
}
return nil
}
return res
}
func (m *WorkbookRangeView) IsNil()(bool) {
return m == nil
}
// Serialize serializes information the current object
func (m *WorkbookRangeView) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteObjectValue("cellAddresses", m.GetCellAddresses())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("columnCount", m.GetColumnCount())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("formulas", m.GetFormulas())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("formulasLocal", m.GetFormulasLocal())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("formulasR1C1", m.GetFormulasR1C1())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("index", m.GetIndex())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("numberFormat", m.GetNumberFormat())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("rowCount", m.GetRowCount())
if err != nil {
return err
}
}
if m.GetRows() != nil {
cast := make([]i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable, len(m.GetRows()))
for i, v := range m.GetRows() {
temp := v
cast[i] = i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable(&temp)
}
err = writer.WriteCollectionOfObjectValues("rows", cast)
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("text", m.GetText())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("values", m.GetValues())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("valueTypes", m.GetValueTypes())
if err != nil {
return err
}
}
return nil
}
// SetCellAddresses sets the cellAddresses property value. Represents the cell addresses
func (m *WorkbookRangeView) SetCellAddresses(value *Json)() {
if m != nil {
m.cellAddresses = value
}
}
// SetColumnCount sets the columnCount property value. Returns the number of visible columns. Read-only.
func (m *WorkbookRangeView) SetColumnCount(value *int32)() {
if m != nil {
m.columnCount = value
}
}
// SetFormulas sets the formulas property value. Represents the formula in A1-style notation.
func (m *WorkbookRangeView) SetFormulas(value *Json)() {
if m != nil {
m.formulas = value
}
}
// SetFormulasLocal sets the formulasLocal property value. Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English '=SUM(A1, 1.5)' formula would become '=SUMME(A1; 1,5)' in German.
func (m *WorkbookRangeView) SetFormulasLocal(value *Json)() {
if m != nil {
m.formulasLocal = value
}
}
// SetFormulasR1C1 sets the formulasR1C1 property value. Represents the formula in R1C1-style notation.
func (m *WorkbookRangeView) SetFormulasR1C1(value *Json)() {
if m != nil {
m.formulasR1C1 = value
}
}
// SetIndex sets the index property value. Index of the range.
func (m *WorkbookRangeView) SetIndex(value *int32)() {
if m != nil {
m.index = value
}
}
// SetNumberFormat sets the numberFormat property value. Represents Excel's number format code for the given cell. Read-only.
func (m *WorkbookRangeView) SetNumberFormat(value *Json)() {
if m != nil {
m.numberFormat = value
}
}
// SetRowCount sets the rowCount property value. Returns the number of visible rows. Read-only.
func (m *WorkbookRangeView) SetRowCount(value *int32)() {
if m != nil {
m.rowCount = value
}
}
// SetRows sets the rows property value. Represents a collection of range views associated with the range. Read-only. Read-only.
func (m *WorkbookRangeView) SetRows(value []WorkbookRangeView)() {
if m != nil {
m.rows = value
}
}
// SetText sets the text property value. Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only.
func (m *WorkbookRangeView) SetText(value *Json)() {
if m != nil {
m.text = value
}
}
// SetValues sets the values property value. Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.
func (m *WorkbookRangeView) SetValues(value *Json)() {
if m != nil {
m.values = value
}
}
// SetValueTypes sets the valueTypes property value. Represents the type of data of each cell. Read-only. The possible values are: Unknown, Empty, String, Integer, Double, Boolean, Error.
func (m *WorkbookRangeView) SetValueTypes(value *Json)() {
if m != nil {
m.valueTypes = value
}
} | models/microsoft/graph/workbook_range_view.go | 0.744471 | 0.476945 | workbook_range_view.go | starcoder |
package observability
import (
"time"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
)
// Pool metrics:
// 1. Connections taken
// 2. Connections closed
// 3. Connections usetime -- how long is a connection used until it is closed, discarded or returned
// 4. Connections reused
// 4. Connections stale
// 5. Dial errors
const dimensionless = "1"
const milliseconds = "ms"
var (
// The measures to record metrics
MBytesRead = stats.Int64("redis/bytes_read", "The number of bytes read from the server", stats.UnitBytes)
MBytesWritten = stats.Int64("redis/bytes_written", "The number of bytes written out to the server", stats.UnitBytes)
MErrors = stats.Int64("redis/errors", "The number of errors encountered", dimensionless)
MWrites = stats.Int64("redis/writes", "The number of write invocations", dimensionless)
MReads = stats.Int64("redis/reads", "The number of read invocations", dimensionless)
MRoundtripLatencyMs = stats.Float64("redis/roundtrip_latency", "The latency in milliseconds of a method/operation", milliseconds)
MConnectionsClosed = stats.Int64("redis/connections_closed", "The number of connections that have been closed", dimensionless)
MConnectionsOpen = stats.Int64("redis/connections_open", "The number of open connections", dimensionless)
)
var (
// The tag keys to record alongside measures
KeyCommandName, _ = tag.NewKey("cmd")
KeyKind, _ = tag.NewKey("kind")
KeyDetail, _ = tag.NewKey("detail")
KeyState, _ = tag.NewKey("state")
)
var defaultMillisecondsDistribution = view.Distribution(
// [0ms, 0.001ms, 0.005ms, 0.01ms, 0.05ms, 0.1ms, 0.5ms, 1ms, 1.5ms, 2ms, 2.5ms, 5ms, 10ms, 25ms, 50ms, 100ms, 200ms, 400ms, 600ms, 800ms, 1s, 1.5s, 2.5s, 5s, 10s, 20s, 40s, 100s, 200s, 500s]
0, 0.000001, 0.000005, 0.00001, 0.00005, 0.0001, 0.0005, 0.001, 0.0015, 0.002, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2.5, 5, 10, 20, 40, 100, 200, 500,
)
var defaultBytesDistribution = view.Distribution(
// [0, 1KB, 2KB, 4KB, 16KB, 64KB, 256KB, 1MB, 4MB, 16MB, 64MB, 256MB, 1GB, 4GB]
0, 1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824, 4294967296,
)
var Views = []*view.View{
{
Name: "redis/client/bytes_written",
Description: "The distribution of bytes written out to the server",
Aggregation: defaultBytesDistribution,
Measure: MBytesWritten,
TagKeys: []tag.Key{KeyCommandName},
},
{
Name: "redis/client/bytes_read",
Description: "The distribution of bytes read from the server",
Aggregation: defaultBytesDistribution,
Measure: MBytesRead,
TagKeys: []tag.Key{KeyCommandName},
},
{
Name: "redis/client/roundtrip_latency",
Description: "The distribution of milliseconds of the roundtrip latencies for a Redis method invocation",
Aggregation: defaultMillisecondsDistribution,
Measure: MRoundtripLatencyMs,
TagKeys: []tag.Key{KeyCommandName},
},
{
Name: "redis/client/writes",
Description: "The number of write operations",
Aggregation: view.Count(),
Measure: MWrites,
TagKeys: []tag.Key{KeyCommandName},
},
{
Name: "redis/client/reads",
Description: "The number of read operations",
Aggregation: view.Count(),
Measure: MReads,
TagKeys: []tag.Key{KeyCommandName},
},
{
Name: "redis/client/errors",
Description: "The number of errors encountered",
Aggregation: view.Count(),
Measure: MErrors,
TagKeys: []tag.Key{KeyCommandName, KeyDetail, KeyKind},
},
{
Name: "redis/client/connections_closed",
Description: "The number of connections that have been closed, disambiguated by keys such as stale, idle, complete",
Aggregation: view.Count(),
Measure: MConnectionsClosed,
TagKeys: []tag.Key{KeyState},
},
{
Name: "redis/client/connections_open",
Description: "The number of open connections, but disambiguated by different states e.g. new, reused",
Aggregation: view.Count(),
Measure: MConnectionsOpen,
TagKeys: []tag.Key{KeyState},
},
}
func SinceInMilliseconds(startTime time.Time) float64 {
return float64(time.Since(startTime).Nanoseconds()) / 1e6
} | internal/observability/observability.go | 0.573201 | 0.50177 | observability.go | starcoder |
package btrank
import "github.com/algao1/basically"
// A SGraph is an undirected graph, representing the sentences within a document.
// The nodes represent individual sentences, and edges represent the connection
// between sentences.
type SGraph struct {
Nodes []*basically.Sentence
Edges [][]float64
}
// BiasedTextRank implements the Summarizer interface.
type BiasedTextRank struct {
Graph *SGraph
}
var _ basically.Summarizer = (*BiasedTextRank)(nil)
// Initialize initializes the underlying SGraph by inserting nodes and edges.
func (btr *BiasedTextRank) Initialize(sents []*basically.Sentence, similar basically.Similarity,
filter basically.TokenFilter, focusString *basically.Sentence, threshold float64) {
// Instantiate a new SGraph with the appropriate nodes and edges.
btr.Graph = &SGraph{Nodes: sents, Edges: make([][]float64, len(sents))}
// Updates the bias value of each node (sentence) if necessary, and
// constructs the edge slice for each node.
for idx, sent := range sents {
if focusString != nil {
btr.Graph.Nodes[idx].Bias = similar(focusString.Tokens, sent.Tokens, filter)
}
btr.Graph.Edges[idx] = make([]float64, idx+1)
}
// Constructs the edges between nodes satisfying the threshold,
// using the given similarity function, and token filter.
for i := 0; i < len(btr.Graph.Nodes); i++ {
for j := 0; j < i; j++ {
sim := similar(btr.Graph.Nodes[i].Tokens, btr.Graph.Nodes[j].Tokens, filter)
if sim > threshold {
btr.Graph.Edges[i][j] = sim
}
}
}
}
// edge returns the weight of the edge.
// Since SGraph is symmetric, edge(y, x) == edge(x, y).
func (btr *BiasedTextRank) edge(x, y int) float64 {
if y > x {
return btr.Graph.Edges[y][x]
}
return btr.Graph.Edges[x][y]
}
// outWeights calculates the weights of outgoing edges.
func (btr *BiasedTextRank) outWeights() []float64 {
n := len(btr.Graph.Nodes)
weights := make([]float64, 0, n)
for x := 0; x < n; x++ {
var sum float64
for y := 0; y < n; y++ {
sum += btr.edge(x, y)
}
weights = append(weights, sum)
}
return weights
}
// Rank applies the Biased TextRank algorithm on the SGraph for some specified iterations.
func (btr *BiasedTextRank) Rank(iters int) {
n := len(btr.Graph.Nodes)
outWeights := btr.outWeights()
for iter := 0; iter < iters; iter++ {
for x := 0; x < n; x++ {
var sum float64
for y := 0; y < n; y++ {
// Ignore node if the outWeights are too small.
if outWeights[y] < 1e-4 {
continue
}
sum += btr.edge(x, y) * (btr.Graph.Nodes[y].Score / outWeights[y])
}
btr.Graph.Nodes[x].Score = btr.Graph.Nodes[x].Bias*0.15 + 0.85*sum
}
}
} | btrank/btrank.go | 0.825625 | 0.604136 | btrank.go | starcoder |
package main
import (
"fmt"
"math"
"github.com/ByteArena/box2d"
"github.com/wdevore/RangerGo/api"
"github.com/wdevore/RangerGo/engine/maths"
"github.com/wdevore/RangerGo/engine/nodes/custom"
"github.com/wdevore/RangerGo/engine/rendering"
)
// QuadBoxComponent is a bunch of boxes.
type QuadBoxComponent struct {
anchor api.INode // The parent
b2Body *box2d.B2Body
scale float64
}
// NewQuadBoxComponent constructs a component
func NewQuadBoxComponent(name string, parent api.INode) *QuadBoxComponent {
o := new(QuadBoxComponent)
o.anchor = custom.NewAnchorNode("QuadBox", parent.World(), parent)
return o
}
// Configure component
func (q *QuadBoxComponent) Configure(scale float64, b2World *box2d.B2World) {
q.scale = scale
buildQuad(q, b2World)
}
// SetPosition sets component's location.
func (q *QuadBoxComponent) SetPosition(x, y float64) {
q.anchor.SetPosition(x, y)
q.b2Body.SetTransform(box2d.MakeB2Vec2(x, y), q.b2Body.GetAngle())
}
// Reset configures the component back to defaults
func (q *QuadBoxComponent) Reset(x, y float64) {
q.anchor.SetPosition(x, y)
q.b2Body.SetTransform(box2d.MakeB2Vec2(x, y), 0.0)
q.b2Body.SetLinearVelocity(box2d.MakeB2Vec2(0.0, 0.0))
q.b2Body.SetAngularVelocity(0.0)
q.b2Body.SetAwake(true)
}
// Update component
func (q *QuadBoxComponent) Update() {
if q.b2Body.IsActive() {
pos := q.b2Body.GetPosition()
q.anchor.SetPosition(pos.X, pos.Y)
rot := q.b2Body.GetAngle()
q.anchor.SetRotation(rot)
}
}
// SetDensity changes the density of all boxes
func (q *QuadBoxComponent) SetDensity(value float64) {
for fix := q.b2Body.GetFixtureList(); fix != nil; fix = fix.GetNext() {
fix.SetDensity(value)
}
q.b2Body.ResetMassData()
}
// SetFriction changes the friction of all boxes
func (q *QuadBoxComponent) SetFriction(value float64) {
for fix := q.b2Body.GetFixtureList(); fix != nil; fix = fix.GetNext() {
fix.SetFriction(value)
}
}
// SetRestitution changes the restitution of all boxes
func (q *QuadBoxComponent) SetRestitution(value float64) {
for fix := q.b2Body.GetFixtureList(); fix != nil; fix = fix.GetNext() {
fix.SetRestitution(value)
}
}
// ResetFixtures reset all fixtures
func (q *QuadBoxComponent) ResetFixtures(den, fric, rest float64) {
for fix := q.b2Body.GetFixtureList(); fix != nil; fix = fix.GetNext() {
fix.SetDensity(den)
fix.SetFriction(fric)
fix.SetRestitution(rest)
}
q.b2Body.ResetMassData()
}
func buildQuad(c *QuadBoxComponent, b2World *box2d.B2World) {
// A body def used to create bodies
bDef := box2d.MakeB2BodyDef()
bDef.Type = box2d.B2BodyType.B2_dynamicBody
// An instance of a body to contain Fixtures
c.b2Body = b2World.CreateBody(&bDef)
// ------------------------------------------------
// Boxes
// ------------------------------------------------
for i := 0.0; i < 4.0; i++ {
b := custom.NewRectangleNode(fmt.Sprintf("::Box%d", int(i)), c.anchor.World(), c.anchor)
b.SetPosition(math.Sin(i*maths.DegreeToRadians*90.0)*c.scale, math.Cos(i*maths.DegreeToRadians*90.0)*c.scale)
b.SetScale(2.0 * c.scale)
gb := b.(*custom.RectangleNode)
gb.SetColor(rendering.NewPaletteInt64(rendering.Orange))
c.anchor.AddChild(b)
// Every Fixture has a shape
b2Shape := box2d.MakeB2PolygonShape()
b2Shape.SetAsBoxFromCenterAndAngle(1.0*c.scale, 1.0*c.scale, box2d.B2Vec2{X: b.Position().X(), Y: b.Position().Y()}, 0.0)
fd := box2d.MakeB2FixtureDef()
fd.Shape = &b2Shape
fd.Density = 1.0
fd.Friction = i / 4.0
fd.Restitution = (4.0 - i) / 8.0
c.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body
}
} | examples/physics/basics/fixture_properties/quadbox_component.go | 0.646795 | 0.450601 | quadbox_component.go | starcoder |
package generator
import (
"fmt"
"image"
"image/jpeg"
"math"
"os"
"runtime"
"sync"
"github.com/saesh/mandelbrot/pkg/colors"
)
// Coordinate holds real number 'Re', imaginary number 'Im' and corresponding pixel index
type Coordinate struct {
Re float64
Im float64
index int
}
// Mandelbrot defines the parameters of the set to render
// Width & Height define the dimensions of the output image
// R specifies the "zoom"
// MaxIterations is upper limit of iterations for the calculation if a pixel is contained in the set or not
// X & Y define where the center of the complex plane should be from -2..2
type Mandelbrot struct {
Width int
Height int
R float64
MaxIterations int
X float64
Y float64
ImageData *image.RGBA
Colors int
}
// Render generates the Mandelbrot set with N CPU number of go routines
func (m *Mandelbrot) Render() {
m.RenderWithBufferedChannel()
}
// RenderSequentially generates the Mandelbrot set sequentially, without go routines
func (m *Mandelbrot) RenderSequentially() {
m.ImageData = image.NewRGBA(image.Rect(0, 0, m.Width, m.Height))
nPixels := m.Height * m.Width
for index := 0; index < nPixels*4; index += 4 {
m.colorize(m.toCoordinate(index))
}
}
// RenderWithUnlimitedRoutines uses one go routine per Coordinate
// All go routines read from one Coordinate channel with no buffer set
func (m *Mandelbrot) RenderWithUnlimitedRoutines() {
m.ImageData = image.NewRGBA(image.Rect(0, 0, m.Width, m.Height))
nPixels := m.Height * m.Width
done := make(chan bool, nPixels)
for index := 0; index < nPixels*4; index += 4 {
go func(c Coordinate) {
m.colorize(c)
done <- true
}(m.toCoordinate(index))
}
for i := 0; i < nPixels; i++ {
<-done
}
}
// RenderWithMaxRoutines limits the number of go routines
// All go routines read from one Coordinate channel with no buffer set
func (m *Mandelbrot) RenderWithMaxRoutines(maxRoutines int) {
m.ImageData = image.NewRGBA(image.Rect(0, 0, m.Width, m.Height))
nPixels := m.Height * m.Width
semaphore := make(chan bool, maxRoutines)
for index := 0; index < nPixels*4; index += 4 {
semaphore <- true // occupy one slot
go func(c Coordinate) {
m.colorize(c)
<-semaphore // free one slot
}(m.toCoordinate(index))
}
// fill all slots to ensure remaining routines finish
for i := 0; i < maxRoutines; i++ {
semaphore <- true
}
}
// RenderWithBufferedChannel uses a buffered channel for Coordinates
// The buffer size is tthe number of pixel devided by n CPU.
// For each CPU one go routine is started, each reading from the buffered
// Coorindate channel
func (m *Mandelbrot) RenderWithBufferedChannel() {
m.ImageData = image.NewRGBA(image.Rect(0, 0, m.Width, m.Height))
nPixels := m.Height * m.Width
coordinates := make(chan Coordinate, nPixels/4)
go func() {
for index := 0; index < nPixels*4; index += 4 {
coordinates <- m.toCoordinate(index)
}
close(coordinates)
}()
numCPU := runtime.NumCPU()
var wg sync.WaitGroup
wg.Add(numCPU)
for i := 0; i < numCPU; i++ {
go func() {
defer wg.Done()
for coordinate := range coordinates {
m.colorize(coordinate)
}
}()
}
wg.Wait()
}
// WriteJpeg encodes the Mandelbrot.ImageData to a JPEG file
// The quality for JPEG encoding must be passed as int, value between 0..100
func (m *Mandelbrot) WriteJpeg(filename string, quality int) error {
outputFile, err := os.Create(filename)
defer outputFile.Close()
if err != nil {
fmt.Println("could not create file.")
return err
}
options := jpeg.Options{Quality: quality}
jpeg.Encode(outputFile, m.ImageData, &options)
return nil
}
// toCoordinate maps an []RGBA index to a Coordinate in a complex plane
// []RGBA stores 4 numbers for each pixel (r, g, b, a) so every 4 indexes a new pixel starts
func (m *Mandelbrot) toCoordinate(index int) Coordinate {
var width = float64(m.Width)
var height = float64(m.Height)
aspectRatio := height / width
pixelIndex := int(math.Floor(float64(index) / 4))
// Create a point in 0, 0 top and left indexed pane
point := image.Point{pixelIndex % m.Width, int(math.Floor(float64(pixelIndex) / width))}
// Move pane to a complex pane, 0,0 centered and scale with factor
re := (((float64(point.X) * m.R / width) - m.R/2) + (m.X * aspectRatio)) / aspectRatio
im := (((float64(point.Y) * m.R / height) - m.R/2) * -1) + m.Y
return Coordinate{re, im, index}
}
// isMandelbrot calculates if a Cooridinate on the complex plane is within the Mandelbrot set or not
// returns bool wether the Coorindate is in the Mandelbrot set
// int iteration number when the algorithm exited
// float64 the real number calculated up to the point when the algorithm exited
// float64 the imaginary number calculated up to the point when the algorithm exited
// The returned values are used to calculate the color of the corresponding pixel
func (m *Mandelbrot) isMandelbrot(coordinate Coordinate) (bool, int, float64, float64) {
var cr = coordinate.Re
var ci = coordinate.Im
var zr = cr
var zi = ci
for iteration := 0; iteration < m.MaxIterations; iteration++ {
if zr*zr+zi*zi > 4 {
return false, iteration, zr, zi
}
newzr := (zr * zr) - (zi * zi) + cr
newzi := ((zr * zi) * 2) + ci
zr = newzr
zi = newzi
}
return true, m.MaxIterations, zr, zi
}
// colorize takes a Coordinate and uses the results from isMandelbrot to
// get a color. The color is then set in Mandelbrot.ImageData
func (m *Mandelbrot) colorize(coordinate Coordinate) {
isMandelbrot, iteration, real, imaginary := m.isMandelbrot(coordinate)
color := colors.GetColor(m.Colors, isMandelbrot, iteration, m.MaxIterations, real, imaginary)
m.ImageData.Pix[coordinate.index] = color.R
m.ImageData.Pix[coordinate.index+1] = color.G
m.ImageData.Pix[coordinate.index+2] = color.B
m.ImageData.Pix[coordinate.index+3] = color.A
} | pkg/generator/mandelbrot.go | 0.669096 | 0.45847 | mandelbrot.go | starcoder |
package mph
import "sort"
// A Table is an immutable hash table that provides constant-time lookups of key
// indices using a minimal perfect hash.
type Table struct {
keys []string
level0 []uint32 // power of 2 size
level0Mask int // len(Level0) - 1
level1 []uint32 // power of 2 size >= len(keys)
level1Mask int // len(Level1) - 1
}
// Build builds a Table from keys using the "Hash, displace, and compress"
// algorithm described in http://cmph.sourceforge.net/papers/esa09.pdf.
func Build(keys []string) *Table {
var (
level0 = make([]uint32, nextPow2(len(keys)/4))
level0Mask = len(level0) - 1
level1 = make([]uint32, nextPow2(len(keys)))
level1Mask = len(level1) - 1
sparseBuckets = make([][]int, len(level0))
zeroSeed = murmurSeed(0)
)
for i, s := range keys {
n := int(zeroSeed.hash(s)) & level0Mask
sparseBuckets[n] = append(sparseBuckets[n], i)
}
var buckets []indexBucket
for n, vals := range sparseBuckets {
if len(vals) > 0 {
buckets = append(buckets, indexBucket{n, vals})
}
}
sort.Sort(bySize(buckets))
occ := make([]bool, len(level1))
var tmpOcc []int
for _, bucket := range buckets {
var seed murmurSeed
trySeed:
tmpOcc = tmpOcc[:0]
for _, i := range bucket.vals {
n := int(seed.hash(keys[i])) & level1Mask
if occ[n] {
for _, n := range tmpOcc {
occ[n] = false
}
seed++
goto trySeed
}
occ[n] = true
tmpOcc = append(tmpOcc, n)
level1[n] = uint32(i)
}
level0[int(bucket.n)] = uint32(seed)
}
return &Table{
keys: keys,
level0: level0,
level0Mask: level0Mask,
level1: level1,
level1Mask: level1Mask,
}
}
func nextPow2(n int) int {
for i := 1; ; i *= 2 {
if i >= n {
return i
}
}
}
// Lookup searches for s in t and returns its index and whether it was found.
func (t *Table) Lookup(s string) (n uint32, ok bool) {
i0 := int(murmurSeed(0).hash(s)) & t.level0Mask
seed := t.level0[i0]
i1 := int(murmurSeed(seed).hash(s)) & t.level1Mask
n = t.level1[i1]
return n, s == t.keys[int(n)]
}
type indexBucket struct {
n int
vals []int
}
type bySize []indexBucket
func (s bySize) Len() int { return len(s) }
func (s bySize) Less(i, j int) bool { return len(s[i].vals) > len(s[j].vals) }
func (s bySize) Swap(i, j int) { s[i], s[j] = s[j], s[i] } | mph.go | 0.60964 | 0.414366 | mph.go | starcoder |
package plaid
import (
"encoding/json"
)
// TransferAuthorization TransferAuthorization contains the authorization decision for a proposed transfer
type TransferAuthorization struct {
// Plaid’s unique identifier for a transfer authorization.
Id string `json:"id"`
// The datetime representing when the authorization was created, in the format \"2006-01-02T15:04:05Z\".
Created string `json:"created"`
// A decision regarding the proposed transfer. `approved` – The proposed transfer has received the end user's consent and has been approved for processing. Plaid has also reviewed the proposed transfer and has approved it for processing. `permitted` – Plaid was unable to fetch the information required to approve or decline the proposed transfer. You may proceed with the transfer, but further review is recommended. Plaid is awaiting further instructions from the client. `declined` – Plaid reviewed the proposed transfer and declined processing. Refer to the `code` field in the `decision_rationale` object for details.
Decision string `json:"decision"`
DecisionRationale NullableTransferAuthorizationDecisionRationale `json:"decision_rationale"`
ProposedTransfer TransferAuthorizationProposedTransfer `json:"proposed_transfer"`
AdditionalProperties map[string]interface{}
}
type _TransferAuthorization TransferAuthorization
// NewTransferAuthorization instantiates a new TransferAuthorization object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewTransferAuthorization(id string, created string, decision string, decisionRationale NullableTransferAuthorizationDecisionRationale, proposedTransfer TransferAuthorizationProposedTransfer) *TransferAuthorization {
this := TransferAuthorization{}
this.Id = id
this.Created = created
this.Decision = decision
this.DecisionRationale = decisionRationale
this.ProposedTransfer = proposedTransfer
return &this
}
// NewTransferAuthorizationWithDefaults instantiates a new TransferAuthorization object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewTransferAuthorizationWithDefaults() *TransferAuthorization {
this := TransferAuthorization{}
return &this
}
// GetId returns the Id field value
func (o *TransferAuthorization) GetId() string {
if o == nil {
var ret string
return ret
}
return o.Id
}
// GetIdOk returns a tuple with the Id field value
// and a boolean to check if the value has been set.
func (o *TransferAuthorization) GetIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Id, true
}
// SetId sets field value
func (o *TransferAuthorization) SetId(v string) {
o.Id = v
}
// GetCreated returns the Created field value
func (o *TransferAuthorization) GetCreated() string {
if o == nil {
var ret string
return ret
}
return o.Created
}
// GetCreatedOk returns a tuple with the Created field value
// and a boolean to check if the value has been set.
func (o *TransferAuthorization) GetCreatedOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Created, true
}
// SetCreated sets field value
func (o *TransferAuthorization) SetCreated(v string) {
o.Created = v
}
// GetDecision returns the Decision field value
func (o *TransferAuthorization) GetDecision() string {
if o == nil {
var ret string
return ret
}
return o.Decision
}
// GetDecisionOk returns a tuple with the Decision field value
// and a boolean to check if the value has been set.
func (o *TransferAuthorization) GetDecisionOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Decision, true
}
// SetDecision sets field value
func (o *TransferAuthorization) SetDecision(v string) {
o.Decision = v
}
// GetDecisionRationale returns the DecisionRationale field value
// If the value is explicit nil, the zero value for TransferAuthorizationDecisionRationale will be returned
func (o *TransferAuthorization) GetDecisionRationale() TransferAuthorizationDecisionRationale {
if o == nil || o.DecisionRationale.Get() == nil {
var ret TransferAuthorizationDecisionRationale
return ret
}
return *o.DecisionRationale.Get()
}
// GetDecisionRationaleOk returns a tuple with the DecisionRationale field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *TransferAuthorization) GetDecisionRationaleOk() (*TransferAuthorizationDecisionRationale, bool) {
if o == nil {
return nil, false
}
return o.DecisionRationale.Get(), o.DecisionRationale.IsSet()
}
// SetDecisionRationale sets field value
func (o *TransferAuthorization) SetDecisionRationale(v TransferAuthorizationDecisionRationale) {
o.DecisionRationale.Set(&v)
}
// GetProposedTransfer returns the ProposedTransfer field value
func (o *TransferAuthorization) GetProposedTransfer() TransferAuthorizationProposedTransfer {
if o == nil {
var ret TransferAuthorizationProposedTransfer
return ret
}
return o.ProposedTransfer
}
// GetProposedTransferOk returns a tuple with the ProposedTransfer field value
// and a boolean to check if the value has been set.
func (o *TransferAuthorization) GetProposedTransferOk() (*TransferAuthorizationProposedTransfer, bool) {
if o == nil {
return nil, false
}
return &o.ProposedTransfer, true
}
// SetProposedTransfer sets field value
func (o *TransferAuthorization) SetProposedTransfer(v TransferAuthorizationProposedTransfer) {
o.ProposedTransfer = v
}
func (o TransferAuthorization) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["id"] = o.Id
}
if true {
toSerialize["created"] = o.Created
}
if true {
toSerialize["decision"] = o.Decision
}
if true {
toSerialize["decision_rationale"] = o.DecisionRationale.Get()
}
if true {
toSerialize["proposed_transfer"] = o.ProposedTransfer
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *TransferAuthorization) UnmarshalJSON(bytes []byte) (err error) {
varTransferAuthorization := _TransferAuthorization{}
if err = json.Unmarshal(bytes, &varTransferAuthorization); err == nil {
*o = TransferAuthorization(varTransferAuthorization)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "id")
delete(additionalProperties, "created")
delete(additionalProperties, "decision")
delete(additionalProperties, "decision_rationale")
delete(additionalProperties, "proposed_transfer")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableTransferAuthorization struct {
value *TransferAuthorization
isSet bool
}
func (v NullableTransferAuthorization) Get() *TransferAuthorization {
return v.value
}
func (v *NullableTransferAuthorization) Set(val *TransferAuthorization) {
v.value = val
v.isSet = true
}
func (v NullableTransferAuthorization) IsSet() bool {
return v.isSet
}
func (v *NullableTransferAuthorization) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableTransferAuthorization(val *TransferAuthorization) *NullableTransferAuthorization {
return &NullableTransferAuthorization{value: val, isSet: true}
}
func (v NullableTransferAuthorization) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableTransferAuthorization) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | plaid/model_transfer_authorization.go | 0.753376 | 0.593786 | model_transfer_authorization.go | starcoder |
package sliceutil
import (
"strconv"
"strings"
)
// Atoi initializes an array of int from a string of int separated by a character
func Atoi(content string, separator string) []int {
lines := strings.Split(content, separator)
sliceOfInts := make([]int, len(lines))
for i, instruction := range lines {
sliceOfInts[i], _ = strconv.Atoi(instruction)
}
return sliceOfInts
}
// EqualInt returns true if two slices of int are equal (same length, same values), false otherwise
func EqualInt(s1, s2 []int) bool {
if s1 == nil && s2 == nil {
return true
}
if s1 == nil || s2 == nil {
return false
}
if len(s1) != len(s2) {
return false
}
for i := range s1 {
if s1[i] != s2[i] {
return false
}
}
return true
}
// Equal2DString returns true if two 2D slices of string are equal (same length, same values), false otherwise
func Equal2DString(s1, s2 [][]string) bool {
if s1 == nil && s2 == nil {
return true
}
if s1 == nil || s2 == nil {
return false
}
if len(s1) != len(s2) {
return false
}
for i := range s1 {
if EqualString(s1[i], s2[i]) == false {
return false
}
}
return true
}
// Equal2DInt returns true if two 2D slices of int are equal (same length, same values), false otherwise
func Equal2DInt(s1, s2 [][]int) bool {
if s1 == nil && s2 == nil {
return true
}
if s1 == nil || s2 == nil {
return false
}
if len(s1) != len(s2) {
return false
}
for i := range s1 {
if EqualInt(s1[i], s2[i]) == false {
return false
}
}
return true
}
// EqualString returns true if two slices of string are equal (same length, same values), false otherwise
func EqualString(s1, s2 []string) bool {
if s1 == nil && s2 == nil {
return true
}
if s1 == nil || s2 == nil {
return false
}
if len(s1) != len(s2) {
return false
}
for i := range s1 {
if s1[i] != s2[i] {
return false
}
}
return true
}
// GetLargest returns the index of first largest value of a slice of ints
func GetLargest(values []int) int {
var largestValue int
index := -1
for i, value := range values {
if value > largestValue {
largestValue = value
index = i
}
}
return index
}
// ExtendString extends a slice by adding one item
func ExtendString(slice []string, element string) []string {
n := len(slice)
if n == cap(slice) {
// Slice is full; must grow.
// We double its size and add 1, so if the size is zero we still grow.
newSlice := make([]string, len(slice), 2*len(slice)+1)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : n+1]
slice[n] = element
return slice
}
// ReverseInt reverses an array of strings (i.e. [2, 7, 3, 1] becomes [1, 3, 7, 2])
func ReverseInt(input []int) []int {
for i := 0; i < len(input)/2; i++ {
input[i], input[len(input)-1-i] = input[len(input)-1-i], input[i]
}
return input
}
// InsertInt inserts an int in an array of int if it is not already present in the array
func InsertInt(ins int, arr []int) []int {
found := false
for _, val := range arr {
if val == ins {
found = true
break
}
}
if !found {
arr = append(arr, ins)
}
return arr
}
// HasInt returns true if the array of ints has the value find, false otherwise
func HasInt(find int, arr []int) bool {
for _, val := range arr {
if val == find {
return true
}
}
return false
}
// CircularAdd returns the next index after adding n to the current index in an array of the specified length
func CircularAdd(currentIndex int, n int, length int) int {
newIndex := 0
if length <= 0 {
return 0
}
newIndex = currentIndex + n
if newIndex >= length {
newIndex = newIndex % length
}
return newIndex
} | sliceutil/sliceutil.go | 0.827445 | 0.471892 | sliceutil.go | starcoder |
package types
import (
"bytes"
"sort"
"strings"
)
type operator uint8
const (
operatorEq operator = iota + 1
operatorGt
operatorGte
operatorLt
operatorLte
)
func (op operator) String() string {
switch op {
case operatorEq:
return "="
case operatorGt:
return ">"
case operatorGte:
return ">="
case operatorLt:
return "<"
case operatorLte:
return "<="
}
return ""
}
// IsEqual returns true if v is equal to the given value.
func IsEqual(v, other Value) (bool, error) {
return compare(operatorEq, v, other)
}
// IsNotEqual returns true if v is not equal to the given value.
func IsNotEqual(v, other Value) (bool, error) {
ok, err := IsEqual(v, other)
if err != nil {
return ok, err
}
return !ok, nil
}
// IsGreaterThan returns true if v is greather than the given value.
func IsGreaterThan(v, other Value) (bool, error) {
return compare(operatorGt, v, other)
}
// IsGreaterThanOrEqual returns true if v is greather than or equal to the given value.
func IsGreaterThanOrEqual(v, other Value) (bool, error) {
return compare(operatorGte, v, other)
}
// IsLesserThan returns true if v is lesser than the given value.
func IsLesserThan(v, other Value) (bool, error) {
return compare(operatorLt, v, other)
}
// IsLesserThanOrEqual returns true if v is lesser than or equal to the given value.
func IsLesserThanOrEqual(v, other Value) (bool, error) {
return compare(operatorLte, v, other)
}
func compare(op operator, l, r Value) (bool, error) {
switch {
// deal with nil
case l.Type() == NullValue || r.Type() == NullValue:
return compareWithNull(op, l, r), nil
// compare booleans together
case l.Type() == BooleanValue && r.Type() == BooleanValue:
return compareBooleans(op, As[bool](l), As[bool](r)), nil
// compare texts together
case l.Type() == TextValue && r.Type() == TextValue:
return compareTexts(op, As[string](l), As[string](r)), nil
// compare blobs together
case r.Type() == BlobValue && l.Type() == BlobValue:
return compareBlobs(op, As[[]byte](l), As[[]byte](r)), nil
// compare integers together
case l.Type() == IntegerValue && r.Type() == IntegerValue:
return compareIntegers(op, As[int64](l), As[int64](r)), nil
// compare numbers together
case l.Type().IsNumber() && r.Type().IsNumber():
return compareNumbers(op, l, r), nil
// compare arrays together
case l.Type() == ArrayValue && r.Type() == ArrayValue:
return compareArrays(op, As[Array](l), As[Array](r))
// compare documents together
case l.Type() == DocumentValue && r.Type() == DocumentValue:
return compareDocuments(op, As[Document](l), As[Document](r))
}
return false, nil
}
func compareWithNull(op operator, l, r Value) bool {
switch op {
case operatorEq, operatorGte, operatorLte:
return l.Type() == r.Type()
case operatorGt, operatorLt:
return false
}
return false
}
func compareBooleans(op operator, a, b bool) bool {
switch op {
case operatorEq:
return a == b
case operatorGt:
return a && !b
case operatorGte:
return a == b || a
case operatorLt:
return !a && b
case operatorLte:
return a == b || !a
}
return false
}
func compareTexts(op operator, l, r string) bool {
switch op {
case operatorEq:
return l == r
case operatorGt:
return strings.Compare(l, r) > 0
case operatorGte:
return strings.Compare(l, r) >= 0
case operatorLt:
return strings.Compare(l, r) < 0
case operatorLte:
return strings.Compare(l, r) <= 0
}
return false
}
func compareBlobs(op operator, l, r []byte) bool {
switch op {
case operatorEq:
return bytes.Equal(l, r)
case operatorGt:
return bytes.Compare(l, r) > 0
case operatorGte:
return bytes.Compare(l, r) >= 0
case operatorLt:
return bytes.Compare(l, r) < 0
case operatorLte:
return bytes.Compare(l, r) <= 0
}
return false
}
func compareIntegers(op operator, l, r int64) bool {
switch op {
case operatorEq:
return l == r
case operatorGt:
return l > r
case operatorGte:
return l >= r
case operatorLt:
return l < r
case operatorLte:
return l <= r
}
return false
}
func compareNumbers(op operator, l, r Value) bool {
l = convertNumberToDouble(l)
r = convertNumberToDouble(r)
af := As[float64](l)
bf := As[float64](r)
var ok bool
switch op {
case operatorEq:
ok = af == bf
case operatorGt:
ok = af > bf
case operatorGte:
ok = af >= bf
case operatorLt:
ok = af < bf
case operatorLte:
ok = af <= bf
}
return ok
}
func compareArrays(op operator, l Array, r Array) (bool, error) {
var i, j int
for {
lv, lerr := l.GetByIndex(i)
rv, rerr := r.GetByIndex(j)
if lerr == nil {
i++
}
if rerr == nil {
j++
}
if lerr != nil || rerr != nil {
break
}
if lv.Type() == rv.Type() || (lv.Type().IsNumber() && rv.Type().IsNumber()) {
isEq, err := compare(operatorEq, lv, rv)
if err != nil {
return false, err
}
if !isEq && op != operatorEq {
return compare(op, lv, rv)
}
if !isEq {
return false, nil
}
} else {
switch op {
case operatorEq:
return false, nil
case operatorGt, operatorGte:
return lv.Type() > rv.Type(), nil
case operatorLt, operatorLte:
return lv.Type() < rv.Type(), nil
}
}
}
switch {
case i > j:
switch op {
case operatorEq, operatorLt, operatorLte:
return false, nil
default:
return true, nil
}
case i < j:
switch op {
case operatorEq, operatorGt, operatorGte:
return false, nil
default:
return true, nil
}
default:
switch op {
case operatorEq, operatorGte, operatorLte:
return true, nil
default:
return false, nil
}
}
}
func compareDocuments(op operator, l, r Document) (bool, error) {
lf, err := Fields(l)
if err != nil {
return false, err
}
rf, err := Fields(r)
if err != nil {
return false, err
}
if len(lf) == 0 && len(rf) > 0 {
switch op {
case operatorEq:
return false, nil
case operatorGt:
return false, nil
case operatorGte:
return false, nil
case operatorLt:
return true, nil
case operatorLte:
return true, nil
}
}
if len(rf) == 0 && len(lf) > 0 {
switch op {
case operatorEq:
return false, nil
case operatorGt:
return true, nil
case operatorGte:
return true, nil
case operatorLt:
return false, nil
case operatorLte:
return false, nil
}
}
var i, j int
for i < len(lf) && j < len(rf) {
if cmp := strings.Compare(lf[i], rf[j]); cmp != 0 {
switch op {
case operatorEq:
return false, nil
case operatorGt:
return cmp > 0, nil
case operatorGte:
return cmp >= 0, nil
case operatorLt:
return cmp < 0, nil
case operatorLte:
return cmp <= 0, nil
}
}
lv, lerr := l.GetByField(lf[i])
rv, rerr := r.GetByField(rf[j])
if lerr == nil {
i++
}
if rerr == nil {
j++
}
if lerr != nil || rerr != nil {
break
}
if lv.Type() == rv.Type() || (lv.Type().IsNumber() && rv.Type().IsNumber()) {
isEq, err := compare(operatorEq, lv, rv)
if err != nil {
return false, err
}
if !isEq && op != operatorEq {
return compare(op, lv, rv)
}
if !isEq {
return false, nil
}
} else {
switch op {
case operatorEq:
return false, nil
case operatorGt, operatorGte:
return lv.Type() > rv.Type(), nil
case operatorLt, operatorLte:
return lv.Type() < rv.Type(), nil
}
}
}
switch {
case i > j:
switch op {
case operatorEq, operatorLt, operatorLte:
return false, nil
default:
return true, nil
}
case i < j:
switch op {
case operatorEq, operatorGt, operatorGte:
return false, nil
default:
return true, nil
}
default:
switch op {
case operatorEq, operatorGte, operatorLte:
return true, nil
default:
return false, nil
}
}
}
// Fields returns a list of all the fields at the root of the document
// sorted lexicographically.
func Fields(d Document) ([]string, error) {
var fields []string
err := d.Iterate(func(f string, _ Value) error {
fields = append(fields, f)
return nil
})
if err != nil {
return nil, err
}
sort.Strings(fields)
return fields, nil
} | types/compare.go | 0.733547 | 0.478955 | compare.go | starcoder |
package clip
import (
"github.com/tidwall/geojson"
"github.com/tidwall/geojson/geometry"
)
// Clip clips the contents of a geojson object and return
func Clip(
obj geojson.Object, clipper geojson.Object, opts *geometry.IndexOptions,
) (clipped geojson.Object) {
switch obj := obj.(type) {
case *geojson.Point:
return clipPoint(obj, clipper, opts)
case *geojson.Rect:
return clipRect(obj, clipper, opts)
case *geojson.LineString:
return clipLineString(obj, clipper, opts)
case *geojson.Polygon:
return clipPolygon(obj, clipper, opts)
case *geojson.Feature:
return clipFeature(obj, clipper, opts)
case geojson.Collection:
return clipCollection(obj, clipper, opts)
}
return obj
}
// clipSegment is Cohen-Sutherland Line Clipping
// https://www.cs.helsinki.fi/group/goa/viewing/leikkaus/lineClip.html
func clipSegment(seg geometry.Segment, rect geometry.Rect) (
res geometry.Segment, rejected bool,
) {
startCode := getCode(rect, seg.A)
endCode := getCode(rect, seg.B)
if (startCode | endCode) == 0 {
// trivially accept
res = seg
} else if (startCode & endCode) != 0 {
// trivially reject
rejected = true
} else if startCode != 0 {
// start is outside. get new start.
newStart := intersect(rect, startCode, seg.A, seg.B)
res, rejected =
clipSegment(geometry.Segment{A: newStart, B: seg.B}, rect)
} else {
// end is outside. get new end.
newEnd := intersect(rect, endCode, seg.A, seg.B)
res, rejected = clipSegment(geometry.Segment{A: seg.A, B: newEnd}, rect)
}
return
}
// clipRing is Sutherland-Hodgman Polygon Clipping
// https://www.cs.helsinki.fi/group/goa/viewing/leikkaus/intro2.html
func clipRing(ring []geometry.Point, bbox geometry.Rect) (
resRing []geometry.Point,
) {
if len(ring) < 4 {
// under 4 elements this is not a polygon ring!
return
}
var edge uint8
var inside, prevInside bool
var prev geometry.Point
for edge = 1; edge <= 8; edge *= 2 {
prev = ring[len(ring)-2]
prevInside = (getCode(bbox, prev) & edge) == 0
for _, p := range ring {
inside = (getCode(bbox, p) & edge) == 0
if prevInside && inside {
// Staying inside
resRing = append(resRing, p)
} else if prevInside && !inside {
// Leaving
resRing = append(resRing, intersect(bbox, edge, prev, p))
} else if !prevInside && inside {
// Entering
resRing = append(resRing, intersect(bbox, edge, prev, p))
resRing = append(resRing, p)
} else {
// Staying outside
}
prev, prevInside = p, inside
}
if len(resRing) > 0 && resRing[0] != resRing[len(resRing)-1] {
resRing = append(resRing, resRing[0])
}
ring, resRing = resRing, []geometry.Point{}
if len(ring) == 0 {
break
}
}
resRing = ring
return
}
func getCode(bbox geometry.Rect, point geometry.Point) (code uint8) {
code = 0
if point.X < bbox.Min.X {
code |= 1 // left
} else if point.X > bbox.Max.X {
code |= 2 // right
}
if point.Y < bbox.Min.Y {
code |= 4 // bottom
} else if point.Y > bbox.Max.Y {
code |= 8 // top
}
return
}
func intersect(bbox geometry.Rect, code uint8, start, end geometry.Point) (
new geometry.Point,
) {
if (code & 8) != 0 { // top
new = geometry.Point{
X: start.X + (end.X-start.X)*(bbox.Max.Y-start.Y)/(end.Y-start.Y),
Y: bbox.Max.Y,
}
} else if (code & 4) != 0 { // bottom
new = geometry.Point{
X: start.X + (end.X-start.X)*(bbox.Min.Y-start.Y)/(end.Y-start.Y),
Y: bbox.Min.Y,
}
} else if (code & 2) != 0 { //right
new = geometry.Point{
X: bbox.Max.X,
Y: start.Y + (end.Y-start.Y)*(bbox.Max.X-start.X)/(end.X-start.X),
}
} else if (code & 1) != 0 { // left
new = geometry.Point{
X: bbox.Min.X,
Y: start.Y + (end.Y-start.Y)*(bbox.Min.X-start.X)/(end.X-start.X),
}
} else { // should not call intersect with the zero code
}
return
} | internal/clip/clip.go | 0.691393 | 0.438966 | clip.go | starcoder |
package rf
import (
"fmt"
r "reflect"
)
/*
Ensures that the type has the required kind or panics with a descriptive error.
Returns the same type, allowing shorter code.
*/
func ValidateTypeKind(typ r.Type, exp r.Kind) r.Type {
act := TypeKind(typ)
if exp != act {
panic(Err{
`validating type kind`,
fmt.Errorf(`expected kind %v, got type %v of kind %v`, exp, typ, act),
})
}
return typ
}
/*
Ensures that the value has the required kind or panics with a descriptive error.
Returns the same value, allowing shorter code.
*/
func ValidateValueKind(val r.Value, exp r.Kind) r.Value {
act := val.Kind()
if exp != act {
panic(Err{
`validating value kind`,
fmt.Errorf(`expected kind %v, got value %v of kind %v`, exp, val, act),
})
}
return val
}
// Shortcut for `rf.ValidateTypeKind(typ, reflect.Func)`.
func ValidateTypeFunc(typ r.Type) r.Type { return ValidateTypeKind(typ, r.Func) }
// Shortcut for `rf.ValidateTypeKind(typ, reflect.Map)`.
func ValidateTypeMap(typ r.Type) r.Type { return ValidateTypeKind(typ, r.Map) }
// Shortcut for `rf.ValidateTypeKind(typ, reflect.Ptr)`.
func ValidateTypePtr(typ r.Type) r.Type { return ValidateTypeKind(typ, r.Ptr) }
// Shortcut for `rf.ValidateTypeKind(typ, reflect.Slice)`.
func ValidateTypeSlice(typ r.Type) r.Type { return ValidateTypeKind(typ, r.Slice) }
// Shortcut for `rf.ValidateTypeKind(typ, reflect.Struct)`.
func ValidateTypeStruct(typ r.Type) r.Type { return ValidateTypeKind(typ, r.Struct) }
// Shortcut for `rf.ValidateValueKind(val, reflect.Func)`.
func ValidateFunc(val r.Value) r.Value { return ValidateValueKind(val, r.Func) }
// Shortcut for `rf.ValidateValueKind(val, reflect.Map)`.
func ValidateMap(val r.Value) r.Value { return ValidateValueKind(val, r.Map) }
// Shortcut for `rf.ValidateValueKind(val, reflect.Slice)`.
func ValidateSlice(val r.Value) r.Value { return ValidateValueKind(val, r.Slice) }
// Shortcut for `rf.ValidateValueKind(val, reflect.Struct)`.
func ValidateStruct(val r.Value) r.Value { return ValidateValueKind(val, r.Struct) }
// Similar to `rf.ValidateValueKind(val, reflect.Ptr)`, but also ensures that
// the pointer is non-nil.
func ValidatePtr(val r.Value) r.Value {
ValidateValueKind(val, r.Ptr)
if val.IsNil() {
panic(Err{
`validating pointer`,
fmt.Errorf(`expected non-nil pointer %T, got nil`, val),
})
}
return val
}
// Shortcut for `rf.ValidateFunc(reflect.ValueOf(val))`.
func ValidFunc(val any) r.Value { return ValidateFunc(r.ValueOf(val)) }
// Shortcut for `rf.ValidateMap(reflect.ValueOf(val))`.
func ValidMap(val any) r.Value { return ValidateMap(r.ValueOf(val)) }
// Shortcut for `rf.ValidateSlice(reflect.ValueOf(val))`.
func ValidSlice(val any) r.Value { return ValidateSlice(r.ValueOf(val)) }
// Shortcut for `rf.ValidateStruct(reflect.ValueOf(val))`.
func ValidStruct(val any) r.Value { return ValidateStruct(r.ValueOf(val)) }
// Shortcut for `rf.ValidatePtr(reflect.ValueOf(val))`.
func ValidPtr(val any) r.Value { return ValidatePtr(r.ValueOf(val)) }
// Shortcut for `rf.ValidateTypeFunc(reflect.TypeOf(val))`.
func ValidTypeFunc(val any) r.Type { return ValidateTypeFunc(r.TypeOf(val)) }
// Shortcut for `rf.ValidateTypeMap(reflect.TypeOf(val))`.
func ValidTypeMap(val any) r.Type { return ValidateTypeMap(r.TypeOf(val)) }
// Shortcut for `rf.ValidateTypeSlice(reflect.TypeOf(val))`.
func ValidTypeSlice(val any) r.Type { return ValidateTypeSlice(r.TypeOf(val)) }
// Shortcut for `rf.ValidateTypeStruct(reflect.TypeOf(val))`.
func ValidTypeStruct(val any) r.Type { return ValidateTypeStruct(r.TypeOf(val)) }
// Shortcut for `rf.ValidateTypePtr(reflect.TypeOf(val))`.
func ValidTypePtr(val any) r.Type { return ValidateTypePtr(r.TypeOf(val)) }
/*
Ensures that the value is a non-nil pointer where the underlying type has the
required kind, or panics with a descriptive error. Returns the same value,
allowing shorter code. Supports pointers of any depth: `*T`, `**T`, etc. Known
limitation: only the outermost pointer is required to be non-nil. Inner
pointers may be nil.
*/
func ValidatePtrToKind(val r.Value, exp r.Kind) r.Value {
ValidatePtr(val)
// Deep deref allows pointers of any depth: `*T`, `**T`, etc.
act := TypeKind(TypeDeref(val.Type()))
if exp != act {
panic(Err{
`validating pointer`,
fmt.Errorf(`expected pointer to kind %v, got %v`, exp, val.Type()),
})
}
return val
}
/*
Shortcut for `rf.ValidatePtrToKind(reflect.ValueOf(val))`. Converts the input to
`reflect.Value`, ensures that it's a non-nil pointer where the inner type has
the required kind, and returns the resulting `reflect.Value`.
*/
func ValidPtrToKind(val any, exp r.Kind) r.Value {
return ValidatePtrToKind(r.ValueOf(val), exp)
}
/*
Ensures that the value is a slice where the element type has the required kind,
or panics with a descriptive error. Returns the same value, allowing shorter
code. Doesn't automatically dereference the input.
*/
func ValidateSliceOfKind(val r.Value, exp r.Kind) r.Value {
ValidateSlice(val)
act := TypeKind(val.Type().Elem())
if exp != act {
panic(Err{
`validating slice`,
fmt.Errorf(`expected slice of kind %v, got %v`, exp, val.Type()),
})
}
return val
}
/*
Shortcut for `rf.ValidateSliceOfKind(reflect.ValueOf(val))`. Converts the input
to `reflect.Value`, ensures that it's a slice where the element type has the
required kind, and returns the resulting `reflect.Value`.
*/
func ValidSliceOfKind(val any, exp r.Kind) r.Value {
return ValidateSliceOfKind(r.ValueOf(val), exp)
}
/*
Ensures that the value is a slice where the element type has the required type,
or panics with a descriptive error. Returns the same value, allowing shorter
code. Doesn't automatically dereference the input.
*/
func ValidateSliceOf(val r.Value, exp r.Type) r.Value {
ValidateSlice(val)
act := val.Type().Elem()
if exp != act {
panic(Err{
`validating slice`,
fmt.Errorf(`expected slice of type %v, got slice of type %v`, exp, act),
})
}
return val
}
/*
Shortcut for `rf.ValidateSliceOf(reflect.ValueOf(val))`. Converts the input to
`reflect.Value`, ensures that it's a slice with the required element type, and
returns the resulting `reflect.Value`.
*/
func ValidSliceOf(val any, exp r.Type) r.Value {
return ValidateSliceOf(r.ValueOf(val), exp)
}
/*
Takes a func type and ensures that it has the required count of input
parameters, or panics with a descriptive error.
*/
func ValidateFuncNumIn(typ r.Type, exp int) {
if exp != typ.NumIn() {
panic(Err{
`validating func type`,
fmt.Errorf(`expected func type with %v input parameters, found type %v`, exp, typ),
})
}
}
/*
Takes a func type and ensures that it has the required count of output
parameters, or panics with a descriptive error.
*/
func ValidateFuncNumOut(typ r.Type, exp int) {
if exp != typ.NumOut() {
panic(Err{
`validating func type`,
fmt.Errorf(`expected func type with %v output parameters, found type %v`, exp, typ),
})
}
}
/*
Takes a func type and ensures that its input parameters exactly match the count
and types provided to this function, or panics with a descriptive error. Among
the provided parameter types, nil serves as a wildcard that matches any type.
*/
func ValidateFuncIn(typ r.Type, params ...r.Type) {
ValidateTypeFunc(typ)
ValidateFuncNumIn(typ, len(params))
for i, param := range params {
if param != nil && param != typ.In(i) {
panic(Err{
`validating func type`,
fmt.Errorf(`expected func type with input types %v, found type %v`, params, typ),
})
}
}
}
/*
Takes a func type and ensures that its return parameters exactly match the count
and types provided to this function, or panics with a descriptive error. Among
the provided parameter types, nil serves as a wildcard that matches any type.
*/
func ValidateFuncOut(typ r.Type, params ...r.Type) {
ValidateTypeFunc(typ)
ValidateFuncNumOut(typ, len(params))
for i, param := range params {
if param != nil && param != typ.Out(i) {
panic(Err{
`validating func type`,
fmt.Errorf(`expected func type with output types %v, found type %v`, params, typ),
})
}
}
}
/*
Ensures that the given value either directly or indirectly (through any number
of arbitrarily-nested pointer types) contains a type of the provided kind, and
returns its dereferenced value. If any intermediary pointer is nil, the
returned value is invalid.
*/
func DerefWithKind(src any, kind r.Kind) r.Value {
val := r.ValueOf(src)
ValidateTypeKind(TypeDeref(ValueType(val)), kind)
return ValueDeref(val)
}
// Shortcut for `rf.DerefWithKind(val, reflect.Func)`.
func DerefFunc(val any) r.Value { return DerefWithKind(val, r.Func) }
// Shortcut for `rf.DerefWithKind(val, reflect.Map)`.
func DerefMap(val any) r.Value { return DerefWithKind(val, r.Map) }
// Shortcut for `rf.DerefWithKind(val, reflect.Slice)`.
func DerefSlice(val any) r.Value { return DerefWithKind(val, r.Slice) }
// Shortcut for `rf.DerefWithKind(val, reflect.Struct)`.
func DerefStruct(val any) r.Value { return DerefWithKind(val, r.Struct) } | rf_validate.go | 0.832169 | 0.577049 | rf_validate.go | starcoder |
package check
import "fmt"
// Int64Slice is the type of a check function for a slice of int64's. It
// takes a slice of int64's and returns an error or nil if the check passes
type Int64Slice func(v []int64) error
// Int64SliceNoDups checks that the list contains no duplicates
func Int64SliceNoDups(v []int64) error {
dupMap := make(map[int64]int)
for i, s := range v {
if dup, ok := dupMap[s]; ok {
return fmt.Errorf(
"list entries: %d and %d are duplicates, both are: %d",
dup, i, s)
}
dupMap[s] = i
}
return nil
}
// Int64SliceInt64Check returns a check function that checks that every member
// of the list matches the supplied Int64 check function
func Int64SliceInt64Check(sc Int64) Int64Slice {
return func(v []int64) error {
for i, s := range v {
if err := sc(s); err != nil {
return fmt.Errorf(
"list entry: %d (%d) does not pass the test: %s",
i, s, err)
}
}
return nil
}
}
// Int64SliceLenEQ returns a check function that checks that the length of
// the list equals the supplied value
func Int64SliceLenEQ(i int) Int64Slice {
return func(v []int64) error {
if len(v) != i {
return fmt.Errorf("the length of the list (%d) must equal %d",
len(v), i)
}
return nil
}
}
// Int64SliceLenGT returns a check function that checks that the length of
// the list is greater than the supplied value
func Int64SliceLenGT(i int) Int64Slice {
return func(v []int64) error {
if len(v) <= i {
return fmt.Errorf(
"the length of the list (%d) must be greater than %d",
len(v), i)
}
return nil
}
}
// Int64SliceLenLT returns a check function that checks that the length of
// the list is less than the supplied value
func Int64SliceLenLT(i int) Int64Slice {
return func(v []int64) error {
if len(v) >= i {
return fmt.Errorf(
"the length of the list (%d) must be less than %d",
len(v), i)
}
return nil
}
}
// Int64SliceLenBetween returns a check function that checks that the length
// of the list is between the two supplied values (inclusive)
func Int64SliceLenBetween(low, high int) Int64Slice {
if low >= high {
panic(fmt.Sprintf("Impossible checks passed to Int64SliceLenBetween: "+
"the lower limit (%d) should be less than the upper limit (%d)",
low, high))
}
return func(v []int64) error {
if len(v) < low {
return fmt.Errorf(
"the length of the list (%d) must be between %d and %d"+
" - too short",
len(v), low, high)
}
if len(v) > high {
return fmt.Errorf(
"the length of the list (%d) must be between %d and %d"+
" - too long",
len(v), low, high)
}
return nil
}
}
// Int64SliceOr returns a function that will check that the value, when
// passed to each of the check funcs in turn, passes at least one of them
func Int64SliceOr(chkFuncs ...Int64Slice) Int64Slice {
return func(i []int64) error {
compositeErr := ""
sep := "("
for _, cf := range chkFuncs {
err := cf(i)
if err == nil {
return nil
}
compositeErr += sep + err.Error()
sep = _Or
}
return fmt.Errorf("%s)", compositeErr)
}
}
// Int64SliceAnd returns a function that will check that the value, when
// passed to each of the check funcs in turn, passes all of them
func Int64SliceAnd(chkFuncs ...Int64Slice) Int64Slice {
return func(i []int64) error {
for _, cf := range chkFuncs {
err := cf(i)
if err != nil {
return err
}
}
return nil
}
}
// Int64SliceNot returns a function that will check that the value, when passed
// to the check func, does not pass it. You must also supply the error text
// to appear after the value that fails. This error text should be a string
// that describes the quality that the slice should not have. So, for
// instance, if the function being Not'ed was
// check.Int64SliceLenGT(5)
// then the errMsg parameter should be
// "a list with length greater than 5".
func Int64SliceNot(c Int64Slice, errMsg string) Int64Slice {
return func(v []int64) error {
err := c(v)
if err != nil {
return nil
}
return fmt.Errorf("%v should not be %s", v, errMsg)
}
} | check/int64slice.go | 0.678966 | 0.512327 | int64slice.go | starcoder |
package generic
func IsEmpty(value interface{}) bool {
switch val := value.(type) {
case uint:
return val == 0
case uint8:
return val == 0
case uint16:
return val == 0
case uint32:
return val == 0
case uint64:
return val == 0
case int:
return val == 0
case int8:
return val == 0
case int16:
return val == 0
case int32:
return val == 0
case int64:
return val == 0
case float32:
return val == 0
case float64:
return val == 0
case string:
return val == ""
case bool:
return val == false
case []string:
return len(val) == 0
default:
return true
}
}
func CoalesceUint(values ...uint) uint {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceUint8(values ...uint8) uint8 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceUint16(values ...uint16) uint16 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceUint32(values ...uint32) uint32 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceUint64(values ...uint64) uint64 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceInt(values ...int) int {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceInt8(values ...int8) int8 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceInt16(values ...int16) int16 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceInt32(values ...int32) int32 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceInt64(values ...int64) int64 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceFloat32(values ...float32) float32 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceFloat64(values ...float64) float64 {
for _, val := range values {
if val != 0 {
return val
}
}
return 0
}
func CoalesceString(values ...string) string {
for _, val := range values {
if val != "" {
return val
}
}
return ""
} | generic/primitives.go | 0.514644 | 0.465266 | primitives.go | starcoder |
package pythonmixing
import (
"math"
"strings"
"github.com/kiteco/kiteco/kite-go/lang/python/pythoncompletions"
"github.com/kiteco/kiteco/kite-go/lang/python/pythonkeyword"
"github.com/kiteco/kiteco/kite-golib/kitectx"
)
// CompType defines enum to represent which model the completion is from
type CompType int
func (compType CompType) size() int {
return 4
}
const (
// SinglePopularityComp describes a popularity-based single attribute completion.
SinglePopularityComp CompType = 0
// SingleGGNNAttrComp describes a model-based single attribute completion.
SingleGGNNAttrComp CompType = 1
// MultiGGNNAttrComp describes a multi-token model-based attribute completion.
MultiGGNNAttrComp CompType = 2
// CallGGNNComp describes a multi-token model-based call completion.
CallGGNNComp CompType = 3
)
// ContextualFeatures represents a subset of features that can be derived just from the source code.
type ContextualFeatures struct {
ParentType int `json:"parent_type"` // This is the astNodeType of the ast parent node.
NumVars int `json:"num_vars"`
}
func (c ContextualFeatures) vector() []float32 {
var numVars float32
vectorizedContext := make([]float32, 62)
vectorizedContext[c.ParentType-1] = 1.0
if c.NumVars > 0 {
numVars = float32(math.Log(float64(c.NumVars)))
}
vectorizedContext[61] = numVars
return vectorizedContext
}
// CompFeatures represents a subset of features that only depends on the completions returned from completion models.
type CompFeatures struct {
PopularityScore float64 `json:"popularity_score"`
SoftmaxScore float64 `json:"softmax_score"`
AttrScore float64 `json:"attr_score"`
Model CompType `json:"model"`
CompletionLength int `json:"completion_length"`
NumArgs int `json:"num_args"`
}
func (c CompFeatures) vector() []float32 {
compVector := make([]float32, 0, c.Model.size()+5)
var popularityScore float32
if c.PopularityScore > 0.0 {
popularityScore = float32(math.Log(c.PopularityScore))
}
compVector = append(compVector, popularityScore)
var softmaxScore float32
if c.SoftmaxScore > 0.0 {
softmaxScore = float32(math.Log(c.SoftmaxScore))
}
compVector = append(compVector, softmaxScore)
var attrScore float32
if c.AttrScore > 0.0 {
attrScore = float32(math.Log(c.AttrScore))
}
compVector = append(compVector, attrScore)
modelVec := make([]float32, c.Model.size())
modelVec[c.Model] = 1.0
compVector = append(compVector, modelVec...)
compVector = append(compVector, float32(c.CompletionLength), float32(c.NumArgs))
return compVector
}
// Features used for prediction
type Features struct {
Contextual ContextualFeatures `json:"contextual"`
Comp []CompFeatures `json:"comp"`
}
// NewFeatures calculated from the inputs
func NewFeatures(ctx kitectx.Context, in Inputs) (Features, error) {
var numVars int
parentType := pythonkeyword.NodeToCat(in.RAST.Parent[in.AttributeExpr])
comp := make([]CompFeatures, 0, len(in.MixInputs))
for _, m := range in.MixInputs {
c := m.Completion()
numVars = c.MixData.NumVarsInScope
cf := CompFeatures{
CompletionLength: len(c.Identifier),
}
switch m.(type) {
case pythoncompletions.PopularitySingleAttribute:
cf.Model = SinglePopularityComp
cf.PopularityScore = c.Score / 1000
case pythoncompletions.MultiTokenCall:
cf.Model = CallGGNNComp
cf.NumArgs = strings.Count(c.Identifier, ",") + 1
confidenceScore, err := in.CallProb(ctx, int64(in.AttributeExpr.Dot.Begin), c)
if err == nil {
cf.SoftmaxScore = float64(confidenceScore)
} else {
cf.SoftmaxScore = c.Score
}
case pythoncompletions.GGNNAttribute:
cf.Model = SingleGGNNAttrComp
cf.AttrScore = c.Score
}
comp = append(comp, cf)
}
contextual := ContextualFeatures{ParentType: parentType, NumVars: numVars}
return Features{
Contextual: contextual,
Comp: comp,
}, nil
}
func (f Features) feeds() map[string]interface{} {
compFeatures := make([][]float32, 0, len(f.Comp))
for _, c := range f.Comp {
compFeatures = append(compFeatures, c.vector())
}
return map[string]interface{}{
"placeholders/contextual_features": [][]float32{f.Contextual.vector()},
"placeholders/completion_features": compFeatures,
"placeholders/sample_ids": make([]int32, len(f.Comp)),
}
} | kite-exp/old-mixing-model/pythonmixing/features.go | 0.693888 | 0.513851 | features.go | starcoder |
Package speedtest is a client for the speedtest.net bandwidth measuring service.
This package is not affiliated, connected, or associated with speedtest.net in
any way. For information about speedtest.net, visit: http://www.speedtest.net/
This package is hosted on GitHub: http://www.github.com/johnsto/speedtest
This package implements only one part of speedtest.net's functionality, namely
the testing of your connection's upload and download bandwidth by way of HTTP
requests made to one of the service's many global testing servers. It does not
currently report the results back to the speedtest.net API.
Unlike speedtest.net, no attempt is made to ping servers to find the nearest
one. The 'nearest' server is selected using the geographic locations returned
by the speedtest.net API and may not always be physically correct.
A CLI is provided, which is the simplest and easiest way to measure your
connection's bandwidth.
Below is a simple example of how you might test bandwidth against the first
server reported by the service:
import "fmt"
import . "github.com/johnsto/speedtest"
import "net/http"
import "time"
func main() {
// Fetch server list
settings, _ := FetchSettings()
// Configure benchmark
benchmark := NewDownloadBenchmark(http.DefaultClient, settings.Servers[0])
// Run benchmark
rate := RunBenchmark(benchmark, 4, 16, time.Second * 10)
// Print result (bps)
fmt.Println(NiceRate(rate))
}
For a more detailed example, see speedtest-cli/cli.go
The algorithms used by this package differs from that used by the original
service. There are no guarantees about whether the approach used here is more
or less accurate, but my own measurements showed the results to be
broadly representative of line speed.
Both upload and download testing send/receive as much data as they can within
a given time period, increasing the number of concurrent requests as necessary.
Data is read/written in 16kb chunks, and the amount of data transferred is
logged into an array indexed by time, to a resolution of 100ms. Once all
transfers are complete, the array is scanned to find the second in
which cumulative data transfer was highest, and this value is combined with
the median transfer rate over the period to provide an estimated speed.
This approach is designed to produce a value close to the peak speed of the
line. In contrast, a mean average will typically underestimate due to the
overheads of the testing process.
*/
package speedtest | doc.go | 0.85022 | 0.712232 | doc.go | starcoder |
package xbits
// Many of the loops in this file are of the form
// for i := 0; i < len(z) && i < len(x) && i < len(y); i++
// i < len(z) is the real condition.
// However, checking i < len(x) && i < len(y) as well is faster than
// having the compiler do a bounds check in the body of the loop;
// remarkably it is even faster than hoisting the bounds check
// out of the loop, by doing something like
// _, _ = x[len(z)-1], y[len(z)-1]
// There are other ways to hoist the bounds check out of the loop,
// but the compiler's BCE isn't powerful enough for them (yet?).
// See the discussion in CL 164966.
import "math/bits"
func mulAddVWW(z, x []uint64, y, r uint64) (c uint64) {
c = r
// The comment near the top of this file discusses this for loop condition.
for i := 0; i < len(z) && i < len(x); i++ {
c, z[i] = mul128(x[i], y, c)
}
return
}
// The resulting carry c is either 0 or 1.
func addVV(z, x, y []uint64) (c uint64) {
// The comment near the top of this file discusses this for loop condition.
for i := 0; i < len(z) && i < len(x) && i < len(y); i++ {
zi, cc := bits.Add64(x[i], y[i], c)
z[i] = zi
c = cc
}
return
}
// The resulting carry c is either 0 or 1.
func subVV(z, x, y []uint64) (c uint64) {
// The comment near the top of this file discusses this for loop condition.
for i := 0; i < len(z) && i < len(x) && i < len(y); i++ {
zi, cc := bits.Sub(uint(x[i]), uint(y[i]), uint(c))
z[i] = uint64(zi)
c = uint64(cc)
}
return
}
// q = ( x1 << _W + x0 - r)/y. m = floor(( _B^2 - 1 ) / d - _B). Requiring x1<y.
// An approximate reciprocal with a reference to "Improved Division by Invariant Integers
// (IEEE Transactions on Computers, 11 Jun. 2010)"
func divWW(x1, x0, y, m uint64) (q, r uint64) {
s := bits.LeadingZeros64(y)
if s != 0 {
x1 = x1<<s | x0>>(64-s)
x0 <<= s
y <<= s
}
d := uint(y)
// We know that
// m = ⎣(B^2-1)/d⎦-B
// ⎣(B^2-1)/d⎦ = m+B
// (B^2-1)/d = m+B+delta1 0 <= delta1 <= (d-1)/d
// B^2/d = m+B+delta2 0 <= delta2 <= 1
// The quotient we're trying to compute is
// quotient = ⎣(x1*B+x0)/d⎦
// = ⎣(x1*B*(B^2/d)+x0*(B^2/d))/B^2⎦
// = ⎣(x1*B*(m+B+delta2)+x0*(m+B+delta2))/B^2⎦
// = ⎣(x1*m+x1*B+x0)/B + x0*m/B^2 + delta2*(x1*B+x0)/B^2⎦
// The latter two terms of this three-term sum are between 0 and 1.
// So we can compute just the first term, and we will be low by at most 2.
t1, t0 := bits.Mul(uint(m), uint(x1))
_, c := bits.Add(t0, uint(x0), 0)
t1, _ = bits.Add(t1, uint(x1), c)
// The quotient is either t1, t1+1, or t1+2.
// We'll try t1 and adjust if needed.
qq := t1
// compute remainder r=x-d*q.
dq1, dq0 := bits.Mul(d, qq)
r0, b := bits.Sub(uint(x0), dq0, 0)
r1, _ := bits.Sub(uint(x1), dq1, b)
// The remainder we just computed is bounded above by B+d:
// r = x1*B + x0 - d*q.
// = x1*B + x0 - d*⎣(x1*m+x1*B+x0)/B⎦
// = x1*B + x0 - d*((x1*m+x1*B+x0)/B-alpha) 0 <= alpha < 1
// = x1*B + x0 - x1*d/B*m - x1*d - x0*d/B + d*alpha
// = x1*B + x0 - x1*d/B*⎣(B^2-1)/d-B⎦ - x1*d - x0*d/B + d*alpha
// = x1*B + x0 - x1*d/B*⎣(B^2-1)/d-B⎦ - x1*d - x0*d/B + d*alpha
// = x1*B + x0 - x1*d/B*((B^2-1)/d-B-beta) - x1*d - x0*d/B + d*alpha 0 <= beta < 1
// = x1*B + x0 - x1*B + x1/B + x1*d + x1*d/B*beta - x1*d - x0*d/B + d*alpha
// = x0 + x1/B + x1*d/B*beta - x0*d/B + d*alpha
// = x0*(1-d/B) + x1*(1+d*beta)/B + d*alpha
// < B*(1-d/B) + d*B/B + d because x0<B (and 1-d/B>0), x1<d, 1+d*beta<=B, alpha<1
// = B - d + d + d
// = B+d
// So r1 can only be 0 or 1. If r1 is 1, then we know q was too small.
// Add 1 to q and subtract d from r. That guarantees that r is <B, so
// we no longer need to keep track of r1.
if r1 != 0 {
qq++
r0 -= d
}
// If the remainder is still too large, increment q one more time.
if r0 >= d {
qq++
r0 -= d
}
return uint64(qq), uint64(r0 >> s)
}
// greaterThan reports whether (x1<<_W + x2) > (y1<<_W + y2)
func greaterThan(x1, x2, y1, y2 uint64) bool {
return x1 > y1 || x1 == y1 && x2 > y2
}
func reciprocal(d1 uint64) uint64 {
const mask = 1<<64 - 1
u := d1 << bits.LeadingZeros64(d1)
// (_B^2-1)/U-_B = (_B*(_M-C)+_M)/U
rec, _ := bits.Div64(^u, mask, u)
return rec
} | xbits/arith.go | 0.560493 | 0.548915 | arith.go | starcoder |
package gen
import (
"math/rand"
"time"
)
/*
Times
*/
// Time is a generator for Time values.
type Time interface {
Gen() time.Time
}
// StaticTime generates a static Time.
func StaticTime(t time.Time) Time {
return TimeFunc(func() time.Time { return t })
}
// NormalTime generates a Time from a normal distribution,
// centered on the given mean and with the given standard deviation.
func NormalTime(r *rand.Rand, mean time.Time, stdDev time.Duration) Time {
dur := NormalDuration(r, 0, stdDev)
return TimeFunc(func() time.Time {
return mean.Add(dur.Gen())
})
}
// ExpTime generates a Time from a exponential distribution,
// given a desired average rate.
func ExpTime(r *rand.Rand, now time.Time, avgRate time.Duration) Time {
dur := ExpDuration(r, avgRate)
return TimeFunc(func() time.Time {
return now.Add(dur.Gen())
})
}
// UniformTime generates a Time from a uniform distribution,
// given a desired range.
func UniformTime(r *rand.Rand, from, to time.Time) Time {
dur := UniformDuration(r, 0, to.Sub(from))
return TimeFunc(func() time.Time {
return from.Add(dur.Gen())
})
}
// TimeFunc generates Time by invoking a given function.
type TimeFunc func() time.Time
// Gen generates a Time.
func (gen TimeFunc) Gen() time.Time { return gen() }
/*
Durations
*/
// Duration is a generator for Duration values.
type Duration interface {
Gen() time.Duration
}
// StaticDuration generates a static Duration.
func StaticDuration(t time.Duration) Duration {
return DurationFunc(func() time.Duration { return t })
}
// NormalDuration generates a Duration from a normal distribution,
// centered on the given mean and with the given standard deviation.
func NormalDuration(r *rand.Rand, mean, stdDev time.Duration) Duration {
desiredStdDevInSec := stdDev.Seconds()
desiredMeanInSec := mean.Seconds()
return DurationFunc(func() time.Duration {
sampleInSec := r.NormFloat64()*desiredStdDevInSec + desiredMeanInSec
return time.Duration(sampleInSec * float64(time.Second))
})
}
// ExpDuration generates a Duration from a exponential distribution,
// given a desired average rate.
func ExpDuration(r *rand.Rand, avgRate time.Duration) Duration {
avgRateInSec := avgRate.Seconds()
return DurationFunc(func() time.Duration {
sampleInSec := r.ExpFloat64() / avgRateInSec
return time.Duration(sampleInSec * float64(time.Second))
})
}
// UniformDuration generates a Duration from a uniform distribution,
// given a desired range.
func UniformDuration(r *rand.Rand, from, to time.Duration) Duration {
fromInSec := from.Seconds()
toInSec := to.Seconds()
return DurationFunc(func() time.Duration {
sampleInSec := (r.Float64() * (toInSec - fromInSec)) * fromInSec
return time.Duration(sampleInSec * float64(time.Second))
})
}
// DurationFunc generates Duration by invoking a given function.
type DurationFunc func() time.Duration
// Gen generates a Duration.
func (gen DurationFunc) Gen() time.Duration { return gen() } | pkg/gen/time.go | 0.885365 | 0.646572 | time.go | starcoder |
package blend
import (
"image"
stdcolor "image/color"
"image/draw"
)
// porter/duff compositing modes
var (
Clear draw.Drawer = clear{}
Copy draw.Drawer = copy{}
Dest draw.Drawer = dest{}
SrcOver draw.Drawer = srcOver{}
DestOver draw.Drawer = destOver{}
SrcIn draw.Drawer = srcIn{}
DestIn draw.Drawer = destIn{}
SrcOut draw.Drawer = srcOut{}
DestOut draw.Drawer = destOut{}
SrcAtop draw.Drawer = srcAtop{}
DestAtop draw.Drawer = destAtop{}
XOR draw.Drawer = xOR{}
)
// clear implements the clear porter-duff mode.
type clear struct{}
// String implemenets fmt.Stringer interface.
func (d clear) String() string {
return "Clear"
}
// Draw implements image.Drawer interface.
func (d clear) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d clear) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawClearNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d clear) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawClearRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d clear) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawClearNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d clear) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawClearRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d clear) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawClearAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d clear) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawClearAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d clear) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawClearUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d clear) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawClearUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawClearNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawClearRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawClearNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawClearRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawClearAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawClearAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawClearUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawClearUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d clear) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
var a, r, g, b, tmp uint32
_ = tmp
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// copy implements the copy porter-duff mode.
type copy struct{}
// String implemenets fmt.Stringer interface.
func (d copy) String() string {
return "Copy"
}
// Draw implements image.Drawer interface.
func (d copy) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d copy) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawCopyNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d copy) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawCopyRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d copy) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawCopyNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d copy) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawCopyRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d copy) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawCopyAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d copy) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawCopyAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d copy) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawCopyUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d copy) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawCopyUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawCopyNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawCopyRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawCopyNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawCopyRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawCopyAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawCopyAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawCopyUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawCopyUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
var r, g, b, a, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d copy) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
a = sa
r = sr
g = sg
b = sb
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// dest implements the dest porter-duff mode.
type dest struct{}
// String implemenets fmt.Stringer interface.
func (d dest) String() string {
return "Dest"
}
// Draw implements image.Drawer interface.
func (d dest) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d dest) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d dest) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d dest) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d dest) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d dest) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d dest) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d dest) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d dest) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawDestNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawDestUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d dest) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
a = da
r = dr
g = dg
b = db
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// srcOver implements the srcOver porter-duff mode.
type srcOver struct{}
// String implemenets fmt.Stringer interface.
func (d srcOver) String() string {
return "SrcOver"
}
// Draw implements image.Drawer interface.
func (d srcOver) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d srcOver) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOverNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOver) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOverRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOver) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOverNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOver) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOverRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOver) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOverAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOver) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOverAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOver) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcOverUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d srcOver) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcOverUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawSrcOverNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOverRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOverNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOverRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOverAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOverAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOverUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawSrcOverUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d srcOver) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = sa + (tmp*da)/0xffff
r = sr + (tmp*dr)/0xffff
g = sg + (tmp*dg)/0xffff
b = sb + (tmp*db)/0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// destOver implements the destOver porter-duff mode.
type destOver struct{}
// String implemenets fmt.Stringer interface.
func (d destOver) String() string {
return "DestOver"
}
// Draw implements image.Drawer interface.
func (d destOver) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d destOver) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOverNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOver) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOverRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOver) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOverNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOver) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOverRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOver) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOverAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOver) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOverAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOver) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestOverUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d destOver) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestOverUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawDestOverNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOverRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOverNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOverRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOverAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOverAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOverUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawDestOverUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d destOver) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
tmp = 0xffff - da
a = da + (tmp*sa)/0xffff
r = dr + (tmp*sr)/0xffff
g = dg + (tmp*sg)/0xffff
b = db + (tmp*sb)/0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// srcIn implements the srcIn porter-duff mode.
type srcIn struct{}
// String implemenets fmt.Stringer interface.
func (d srcIn) String() string {
return "SrcIn"
}
// Draw implements image.Drawer interface.
func (d srcIn) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d srcIn) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcInNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcIn) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcInRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcIn) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcInNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcIn) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcInRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcIn) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcInAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcIn) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcInAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcIn) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcInUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d srcIn) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcInUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawSrcInNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcInRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcInNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcInRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcInAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcInAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcInUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawSrcInUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d srcIn) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
_, _, _, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (da * sr) / 0xffff
g = (da * sg) / 0xffff
b = (da * sb) / 0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// destIn implements the destIn porter-duff mode.
type destIn struct{}
// String implemenets fmt.Stringer interface.
func (d destIn) String() string {
return "DestIn"
}
// Draw implements image.Drawer interface.
func (d destIn) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d destIn) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestInNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destIn) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestInRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destIn) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestInNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destIn) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestInRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destIn) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestInAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destIn) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestInAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destIn) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestInUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d destIn) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestInUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawDestInNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestInRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestInNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestInRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestInAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestInAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestInUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawDestInUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d destIn) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
_, _, _, sa := src.At(sx, sy).RGBA()
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
a = (da * sa) / 0xffff
r = (sa * dr) / 0xffff
g = (sa * dg) / 0xffff
b = (sa * db) / 0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// srcOut implements the srcOut porter-duff mode.
type srcOut struct{}
// String implemenets fmt.Stringer interface.
func (d srcOut) String() string {
return "SrcOut"
}
// Draw implements image.Drawer interface.
func (d srcOut) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d srcOut) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOutNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOut) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOutRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOut) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOutNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOut) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOutRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOut) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOutAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOut) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcOutAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcOut) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcOutUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d srcOut) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcOutUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawSrcOutNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOutRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOutNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOutRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOutAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOutAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcOutUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawSrcOutUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d srcOut) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
_, _, _, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
tmp = 0xffff - da
a = (tmp * sa) / 0xffff
r = (tmp * sr) / 0xffff
g = (tmp * sg) / 0xffff
b = (tmp * sb) / 0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// destOut implements the destOut porter-duff mode.
type destOut struct{}
// String implemenets fmt.Stringer interface.
func (d destOut) String() string {
return "DestOut"
}
// Draw implements image.Drawer interface.
func (d destOut) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d destOut) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOutNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOut) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOutRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOut) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOutNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOut) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOutRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOut) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOutAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOut) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestOutAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destOut) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestOutUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d destOut) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestOutUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawDestOutNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOutRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOutNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOutRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOutAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOutAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestOutUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawDestOutUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d destOut) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
_, _, _, sa := src.At(sx, sy).RGBA()
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
tmp = 0xffff - sa
a = (tmp * da) / 0xffff
r = (tmp * dr) / 0xffff
g = (tmp * dg) / 0xffff
b = (tmp * db) / 0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// srcAtop implements the srcAtop porter-duff mode.
type srcAtop struct{}
// String implemenets fmt.Stringer interface.
func (d srcAtop) String() string {
return "SrcAtop"
}
// Draw implements image.Drawer interface.
func (d srcAtop) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d srcAtop) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcAtopNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcAtop) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcAtopRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcAtop) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcAtopNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcAtop) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcAtopRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcAtop) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcAtopAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcAtop) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawSrcAtopAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d srcAtop) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcAtopUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d srcAtop) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawSrcAtopUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawSrcAtopNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcAtopRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcAtopNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcAtopRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcAtopAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcAtopAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawSrcAtopUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawSrcAtopUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d srcAtop) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
a = da
tmp = 0xffff - sa
r = (sr*da + dr*tmp) / 0xffff
g = (sg*da + dg*tmp) / 0xffff
b = (sb*da + db*tmp) / 0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// destAtop implements the destAtop porter-duff mode.
type destAtop struct{}
// String implemenets fmt.Stringer interface.
func (d destAtop) String() string {
return "DestAtop"
}
// Draw implements image.Drawer interface.
func (d destAtop) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d destAtop) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAtopNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destAtop) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAtopRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destAtop) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAtopNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destAtop) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAtopRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destAtop) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAtopAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destAtop) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawDestAtopAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d destAtop) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestAtopUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d destAtop) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawDestAtopUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawDestAtopNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAtopRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAtopNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAtopRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAtopAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAtopAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawDestAtopUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawDestAtopUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d destAtop) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
a = sa
tmp = 0xffff - da
r = (sr*tmp + dr*sa) / 0xffff
g = (sg*tmp + dg*sa) / 0xffff
b = (sb*tmp + db*sa) / 0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
}
// xOR implements the xOR porter-duff mode.
type xOR struct{}
// String implemenets fmt.Stringer interface.
func (d xOR) String() string {
return "XOR"
}
// Draw implements image.Drawer interface.
func (d xOR) Draw(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point) {
// d.drawFallback(dst, r, src, sp, nil, image.Point{})
drawMask(d, dst, r, src, sp, nil, image.Point{})
}
func (d xOR) drawNRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawXORNRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d xOR) drawRGBAToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawXORRGBAToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d xOR) drawNRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawXORNRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d xOR) drawRGBAToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare4to4(dst, src, dst.Stride, src.Stride, r, sp)
drawXORRGBAToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d xOR) drawAlphaToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawXORAlphaToNRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d xOR) drawAlphaToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Alpha, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
d0, dx0, dx1, dxDelta, dyDelta, s0, sx0, sx1, sxDelta, syDelta := prepare1to4(dst, src, dst.Stride, src.Stride, r, sp)
drawXORAlphaToRGBA.Parallel(dst.Pix, src.Pix, alpha, d0, s0, r.Dy(), sx0, sx1, sxDelta, syDelta, dx0, dx1, dxDelta, dyDelta)
}
func (d xOR) drawUniformToNRGBAUniform(dst *image.NRGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawXORUniformToNRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
func (d xOR) drawUniformToRGBAUniform(dst *image.RGBA, r image.Rectangle, src *image.Uniform, sp image.Point, mask *image.Uniform) {
alpha := uint32(0xffff)
if mask != nil {
_, _, _, alpha = mask.C.RGBA()
if alpha == 0 {
return
}
}
sr, sg, sb, sa := src.C.RGBA()
if alpha == 0x00 {
sr, sg, sb, sa = 0, 0, 0, 0
} else if alpha != 0xffff {
sr = sr * alpha / 0xffff
sg = sg * alpha / 0xffff
sb = sb * alpha / 0xffff
sa = sa * alpha / 0xffff
}
drawXORUniformToRGBA.Parallel(dst.Pix[dst.PixOffset(r.Min.X, r.Min.Y):], sr, sg, sb, sa, r.Dy(), 0, r.Dx()<<2, 4, dst.Stride)
}
var drawXORNRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawXORRGBAToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawXORNRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if sa == 0x0000 {
sr = 0
sg = 0
sb = 0
} else if sa < 0xffff {
sr = sr * sa / 0xffff
sg = sg * sa / 0xffff
sb = sb * sa / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawXORRGBAToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i+3]) * 0x0101 * alpha / 0xffff
sb := uint32(spix[i+2]) * 0x0101
sg := uint32(spix[i+1]) * 0x0101
sr := uint32(spix[i]) * 0x0101
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawXORAlphaToNRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
d0 += dyDelta
s0 += syDelta
}
}
var drawXORAlphaToRGBA drawFunc = func(dest []byte, src []byte, alpha uint32, d0, s0, y int, sx0 int, sx1 int, sxDelta int, syDelta int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
const (
sb = 0
sg = 0
sr = 0
)
for ; y > 0; y-- {
dpix := dest[d0:]
spix := src[s0:]
for i, j := sx0, dx0; i != sx1; i, j = i+sxDelta, j+dxDelta {
sa := uint32(spix[i]) * 0x0101 * alpha / 0xffff
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
d0 += dyDelta
s0 += syDelta
}
}
var drawXORUniformToNRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
if da == 0x0000 {
dr = 0
dg = 0
db = 0
} else if da < 0xffff {
dr = dr * da / 0xffff
dg = dg * da / 0xffff
db = db * da / 0xffff
}
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
if a == 0xffff {
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
} else if a == 0 {
dpix[j+2] = 0
dpix[j+1] = 0
dpix[j+0] = 0
} else {
dpix[j+2] = uint8((b * 0xffff / a) >> 8)
dpix[j+1] = uint8((g * 0xffff / a) >> 8)
dpix[j+0] = uint8((r * 0xffff / a) >> 8)
}
}
dPos += dyDelta
}
}
var drawXORUniformToRGBA drawUniformFunc = func(dest []byte, sr, sg, sb, sa uint32, y int, dx0 int, dx1 int, dxDelta int, dyDelta int) {
var dPos int
for ; y > 0; y-- {
dpix := dest[dPos:]
for j := dx0; j != dx1; j += dxDelta {
da := uint32(dpix[j+3]) * 0x0101
db := uint32(dpix[j+2]) * 0x0101
dg := uint32(dpix[j+1]) * 0x0101
dr := uint32(dpix[j]) * 0x0101
var r, g, b, a, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
dpix[j+3] = uint8(a >> 8)
dpix[j+2] = uint8(b >> 8)
dpix[j+1] = uint8(g >> 8)
dpix[j+0] = uint8(r >> 8)
}
dPos += dyDelta
}
}
func (d xOR) drawFallback(dst draw.Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point) {
x0, x1, dx := r.Min.X, r.Max.X, 1
y0, y1, dy := r.Min.Y, r.Max.Y, 1
if processBackward(dst, r, src, sp) {
x0, x1, dx = x1-1, x0-1, -1
y0, y1, dy = y1-1, y0-1, -1
}
var out stdcolor.RGBA64
sy := sp.Y + y0 - r.Min.Y
my := mp.Y + y0 - r.Min.Y
for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
sx := sp.X + x0 - r.Min.X
mx := mp.X + x0 - r.Min.X
for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
ma := uint32(0xffff)
if mask != nil {
_, _, _, ma = mask.At(mx, my).RGBA()
}
if ma == 0 {
continue
}
sr, sg, sb, sa := src.At(sx, sy).RGBA()
dr, dg, db, da := dst.At(x, y).RGBA()
var a, r, g, b, tmp uint32
_ = tmp
a = (sa*(0xffff-da) + da*(0xffff-sa)) / 0xffff
r = (sr*(0xffff-da) + dr*(0xffff-sa)) / 0xffff
g = (sg*(0xffff-da) + dg*(0xffff-sa)) / 0xffff
b = (sb*(0xffff-da) + db*(0xffff-sa)) / 0xffff
out.R = uint16(r)
out.G = uint16(g)
out.B = uint16(b)
out.A = uint16(a)
dst.Set(x, y, &out)
}
}
} | blend/zporterduffs.go | 0.662796 | 0.408926 | zporterduffs.go | starcoder |
// Package systestkeys defines trusted assertions and keys to use in tests.
package systestkeys
import (
"fmt"
"github.com/snapcore/snapd/asserts"
)
const (
TestRootPrivKey = `-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1
<KEY>
-----END PGP PRIVATE KEY BLOCK-----
`
encodedTestRootAccount = `type: account
authority-id: testrootorg
account-id: testrootorg
display-name: Testrootorg
timestamp: 2018-06-27T14:25:40+02:00
username: testrootorg
validation: verified
sign-key-sha3-384: <KEY>
`
TestRootKeyID = "<KEY>"
encodedTestRootAccountKey = `type: account-key
authority-id: testrootorg
public-key-sha3-384: hIedp1AvrWlcDI4uS_qjoFLzjKl5enu4G2FYJpgB3Pj-tUzGlTQBxMBsBmi-tnJR
account-id: testrootorg
name: test-root
since: 2016-08-11T18:30:57+02:00
body-length: 717
sign-key-sha3-384: <KEY>
`
TestStorePrivKey = `-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1
<KEY>
-----END PGP PRIVATE KEY BLOCK-----
`
TestStoreKeyID = "<KEY>"
encodedTestStoreAccountKey = `type: account-key
authority-id: testrootorg
public-key-sha3-384: XCIC_Wvj9_hiAt0b10sDon74oGr3a6xGODkMZqrj63ZzNYUD5N87-ojjPoeN7f1Y
account-id: testrootorg
name: test-store
since: 2016-08-11T18:42:22+02:00
body-length: 717
sign-key-sha3-384: <KEY>
`
)
var (
TestRootAccount asserts.Assertion
TestRootAccountKey asserts.Assertion
// here for convenience, does not need to be in the trusted set
TestStoreAccountKey asserts.Assertion
// Testing-only trusted assertions for injecting in the the system trusted set.
Trusted []asserts.Assertion
)
func init() {
acct, err := asserts.Decode([]byte(encodedTestRootAccount))
if err != nil {
panic(fmt.Sprintf("cannot decode trusted assertion: %v", err))
}
accKey, err := asserts.Decode([]byte(encodedTestRootAccountKey))
if err != nil {
panic(fmt.Sprintf("cannot decode trusted assertion: %v", err))
}
storeAccKey, err := asserts.Decode([]byte(encodedTestStoreAccountKey))
if err != nil {
panic(fmt.Sprintf("cannot decode test store assertion: %v", err))
}
TestRootAccount = acct
TestRootAccountKey = accKey
TestStoreAccountKey = storeAccKey
Trusted = []asserts.Assertion{TestRootAccount, TestRootAccountKey}
} | vendor/github.com/snapcore/snapd/asserts/systestkeys/trusted.go | 0.500732 | 0.430626 | trusted.go | starcoder |
package gates
var builtInFunctions = map[string]Function{
"bool": FunctionFunc(func(fc FunctionCall) Value {
var v Bool
if NewArgumentScanner(fc).Scan(&v) != nil {
return False
}
return v
}),
"int": FunctionFunc(func(fc FunctionCall) Value {
var v Int
if NewArgumentScanner(fc).Scan(&v) != nil {
return Int(0)
}
return v
}),
"number": FunctionFunc(func(fc FunctionCall) Value {
var v Value
if NewArgumentScanner(fc).Scan(&v) != nil {
return Int(0)
}
return v.ToNumber()
}),
"string": FunctionFunc(func(fc FunctionCall) Value {
var v String
if NewArgumentScanner(fc).Scan(&v) != nil {
return String("")
}
return v
}),
"type": FunctionFunc(func(fc FunctionCall) Value {
var v Value
if NewArgumentScanner(fc).Scan(&v) != nil {
return String("")
}
return String(Type(v))
}),
"curry": CurriedFunctionFunc(2, func(fc FunctionCall) Value {
var n int64
var f Value
if NewArgumentScanner(fc).Scan(&n, &f) != nil {
return Null
}
return Curry(f.ToFunction(), int(n))
}),
"map": CurriedFunctionFunc(2, func(fc FunctionCall) Value {
var f Callback
var base []Value
if NewArgumentScanner(fc).Scan(&f, &base) != nil {
return Null
}
result := make([]Value, len(base))
for i := 0; i < len(base); i++ {
result[i] = f(base[i], Int(i))
}
return NewArray(result)
}),
"filter": CurriedFunctionFunc(2, func(fc FunctionCall) Value {
var f Callback
var base []Value
if NewArgumentScanner(fc).Scan(&f, &base) != nil {
return Null
}
result := make([]Value, 0)
for i := 0; i < len(base); i++ {
if f(base[i], Int(i)).ToBool() {
result = append(result, base[i])
}
}
return NewArray(result)
}),
"reduce": CurriedFunctionFunc(3, func(fc FunctionCall) Value {
var f Callback
var initial Value
var base Value
if NewArgumentScanner(fc).Scan(&f, &initial, &base) != nil {
return Null
}
var baseArray []Value
if convertValue(fc.Runtime(), &baseArray, base) != nil {
return Null
}
acc := initial
for i := 0; i < len(baseArray); i++ {
acc = f(acc, baseArray[i], Int(i), base)
}
return acc
}),
"find": CurriedFunctionFunc(2, func(fc FunctionCall) Value {
var f Callback
var base []Value
if NewArgumentScanner(fc).Scan(&f, &base) != nil {
return Null
}
for i := 0; i < len(base); i++ {
if f(base[i], Int(i)).ToBool() {
return base[i]
}
}
return Null
}),
"find_index": CurriedFunctionFunc(2, func(fc FunctionCall) Value {
var f Callback
var base []Value
if NewArgumentScanner(fc).Scan(&f, &base) != nil {
return Int(-1)
}
for i := 0; i < len(base); i++ {
if f(base[i], Int(i)).ToBool() {
return Int(i)
}
}
return Int(-1)
}),
"find_last": CurriedFunctionFunc(2, func(fc FunctionCall) Value {
var f Callback
var base []Value
if NewArgumentScanner(fc).Scan(&f, &base) != nil {
return Null
}
for i := len(base) - 1; i >= 0; i-- {
if f(base[i], Int(i)).ToBool() {
return base[i]
}
}
return Null
}),
"find_last_index": CurriedFunctionFunc(2, func(fc FunctionCall) Value {
var f Callback
var base []Value
if NewArgumentScanner(fc).Scan(&f, &base) != nil {
return Int(-1)
}
for i := len(base) - 1; i >= 0; i-- {
if f(base[i], Int(i)).ToBool() {
return Int(i)
}
}
return Int(-1)
}),
"to_entries": FunctionFunc(func(fc FunctionCall) Value {
var v Value
if NewArgumentScanner(fc).Scan(&v) != nil {
return Null
}
it, ok := GetIterator(v)
if !ok {
return Null
}
entries := make([]Value, 0)
for {
value, ok := it.Next()
if !ok {
break
}
entries = append(entries, value)
}
return NewArray(entries)
}),
"from_entries": FunctionFunc(func(fc FunctionCall) Value {
var v Value
if NewArgumentScanner(fc).Scan(&v) != nil {
return Null
}
it, ok := GetIterator(v)
if !ok {
return Null
}
result := make(map[string]Value)
r := fc.Runtime()
for {
entry, ok := it.Next()
if !ok {
break
}
k := objectGet(r, entry, String("key"))
v := objectGet(r, entry, String("value"))
result[k.ToString()] = v
}
return Map(result)
}),
}
type Global struct {
m Map
}
func NewGlobal() *Global {
return &Global{
m: make(Map),
}
}
func (g *Global) Set(name string, value Value) {
g.m[name] = value
}
func (g *Global) Get(name string) Value {
return g.m[name]
}
func Curry(f Function, n int) Function {
var curriedF Function
curriedF = FunctionFunc(func(fc FunctionCall) Value {
args := fc.Args()
argc := len(args)
if argc >= n {
return fc.Runtime().Call(f, args...)
}
args = make([]Value, argc)
copy(args, fc.Args())
return Curry(FunctionFunc(func(fc FunctionCall) Value {
return fc.Runtime().Call(f, append(args, fc.Args()...)...)
}), n-argc)
})
return curriedF
}
func CurriedFunctionFunc(n int, f func(FunctionCall) Value) Function {
return Curry(FunctionFunc(f), n)
}
func (g *Global) initBuiltInFunctions() {
for name, f := range builtInFunctions {
g.Set(name, f)
}
} | global.go | 0.527073 | 0.472562 | global.go | starcoder |
package exp
import (
"errors"
"strconv"
"github.com/Miha-ha/exp/parse"
)
// The Exp interface represents a tree node. There are several implementations
// of the interface in this package, but one may define custom Exp's as long as
// they implement the Eval function.
type Exp interface {
Eval(Params) bool
}
// Params defines the interface needed by Exp in order to be able to validate
// conditions. An example implementation of this interface would be
// https://golang.org/pkg/net/url/#Values.
type Params interface {
Get(string) string
}
// Map is a simple implementation of Params using a map of strings.
type Map map[string]string
// Get returns the value pointed to by key.
func (m Map) Get(key string) string {
return m[key]
}
func Parse(s string) (Exp, error) {
t, err := parse.Parse(s)
if err != nil {
return nil, err
}
return visit(t)
}
func visit(t parse.Tree) (Exp, error) {
token := t.Value()
switch token.Type {
case parse.T_BOOLEAN:
switch token.Value {
case "true":
return True, nil
case "false":
return False, nil
}
case parse.T_LOGICAL_AND:
l, err := visit(t.Left())
if err != nil {
return nil, err
}
r, err := visit(t.Right())
if err != nil {
return nil, err
}
return And(l, r), nil
case parse.T_LOGICAL_OR:
l, err := visit(t.Left())
if err != nil {
return nil, err
}
r, err := visit(t.Right())
if err != nil {
return nil, err
}
return Or(l, r), nil
case parse.T_IS_EQUAL:
var (
k, v string
f float64
l = t.Left()
r = t.Right()
)
switch l.Value().Type {
case parse.T_IDENTIFIER:
k = l.Value().Value
case parse.T_STRING:
v = l.Value().Value
case parse.T_NUMBER:
var err error
f, err = strconv.ParseFloat(l.Value().Value, 10)
if err != nil {
return nil, err
}
}
switch r.Value().Type {
case parse.T_IDENTIFIER:
k = r.Value().Value
case parse.T_STRING:
v = r.Value().Value
case parse.T_NUMBER:
var err error
f, err = strconv.ParseFloat(r.Value().Value, 10)
if err != nil {
return nil, err
}
}
if v == "" {
return Equal(k, f), nil
}
return Match(k, v), nil
case parse.T_IS_NOT_EQUAL:
var (
k, v string
f float64
l = t.Left()
r = t.Right()
)
switch l.Value().Type {
case parse.T_IDENTIFIER:
k = l.Value().Value
case parse.T_STRING:
v = l.Value().Value
case parse.T_NUMBER:
var err error
f, err = strconv.ParseFloat(l.Value().Value, 10)
if err != nil {
return nil, err
}
}
switch r.Value().Type {
case parse.T_IDENTIFIER:
k = r.Value().Value
case parse.T_STRING:
v = r.Value().Value
case parse.T_NUMBER:
var err error
f, err = strconv.ParseFloat(r.Value().Value, 10)
if err != nil {
return nil, err
}
}
if v == "" {
return NotEqual(k, f), nil
}
return Not(Match(k, v)), nil
case parse.T_IS_GREATER:
var (
k string
v float64
l = t.Left()
r = t.Right()
)
switch l.Value().Type {
case parse.T_IDENTIFIER:
k = l.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(l.Value().Value, 10)
if err != nil {
return nil, err
}
}
switch r.Value().Type {
case parse.T_IDENTIFIER:
k = r.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(r.Value().Value, 10)
if err != nil {
return nil, err
}
}
return GreaterThan(k, v), nil
case parse.T_IS_GREATER_OR_EQUAL:
var (
k string
v float64
l = t.Left()
r = t.Right()
)
switch l.Value().Type {
case parse.T_IDENTIFIER:
k = l.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(l.Value().Value, 10)
if err != nil {
return nil, err
}
}
switch r.Value().Type {
case parse.T_IDENTIFIER:
k = r.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(r.Value().Value, 10)
if err != nil {
return nil, err
}
}
return GreaterOrEqual(k, v), nil
case parse.T_IS_SMALLER:
var (
k string
v float64
l = t.Left()
r = t.Right()
)
switch l.Value().Type {
case parse.T_IDENTIFIER:
k = l.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(l.Value().Value, 10)
if err != nil {
return nil, err
}
}
switch r.Value().Type {
case parse.T_IDENTIFIER:
k = r.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(r.Value().Value, 10)
if err != nil {
return nil, err
}
}
return LessThan(k, v), nil
case parse.T_IS_SMALLER_OR_EQUAL:
var (
k string
v float64
l = t.Left()
r = t.Right()
)
switch l.Value().Type {
case parse.T_IDENTIFIER:
k = l.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(l.Value().Value, 10)
if err != nil {
return nil, err
}
}
switch r.Value().Type {
case parse.T_IDENTIFIER:
k = r.Value().Value
case parse.T_NUMBER:
var err error
v, err = strconv.ParseFloat(r.Value().Value, 10)
if err != nil {
return nil, err
}
}
return LessOrEqual(k, v), nil
}
return nil, errors.New("invalid expression")
}
// And
type expAnd struct{ elems []Exp }
func (a expAnd) Eval(p Params) bool {
for _, elem := range a.elems {
if !elem.Eval(p) {
return false
}
}
return true
}
func (a expAnd) String() string {
return sprintf("(%s)", join(a.elems, "∧"))
}
// And evaluates to true if all t's are true.
func And(t ...Exp) Exp {
return expAnd{t}
}
// Or
type expOr struct{ elems []Exp }
func (o expOr) Eval(p Params) bool {
for _, elem := range o.elems {
if elem.Eval(p) {
return true
}
}
return false
}
func (o expOr) String() string {
return sprintf("(%s)", join(o.elems, "∨"))
}
// Or evaluates to true if any t's are true.
func Or(t ...Exp) Exp {
return expOr{t}
}
// Not
type expNot struct{ elem Exp }
func (n expNot) Eval(p Params) bool {
return !n.elem.Eval(p)
}
func (n expNot) String() string {
return sprintf("¬%s", n.elem)
}
// Not evaluates to the opposite of t.
func Not(t Exp) Exp {
return expNot{t}
} | exp.go | 0.717408 | 0.465266 | exp.go | starcoder |
package include
import "strings"
// Exampledagbasic created with astro dev init
var Exampledagbasic = strings.TrimSpace(`
import json
from datetime import datetime, timedelta
from airflow.decorators import dag, task # DAG and task decorators for interfacing with the TaskFlow API
@dag(
# This defines how often your DAG will run, or the schedule by which your DAG runs. In this case, this DAG
# will run daily
schedule_interval="@daily",
# This DAG is set to run for the first time on January 1, 2021. Best practice is to use a static
# start_date. Subsequent DAG runs are instantiated based on scheduler_interval
start_date=datetime(2021, 1, 1),
# When catchup=False, your DAG will only run for the latest schedule_interval. In this case, this means
# that tasks will not be run between January 1, 2021 and 30 mins ago. When turned on, this DAG's first
# run will be for the next 30 mins, per the schedule_interval
catchup=False,
default_args={
"retries": 2, # If a task fails, it will retry 2 times.
},
tags=['example']) # If set, this tag is shown in the DAG view of the Airflow UI
def example_dag_basic():
"""
### Basic ETL Dag
This is a simple ETL data pipeline example that demonstrates the use of
the TaskFlow API using three simple tasks for extract, transform, and load.
For more information on Airflow's TaskFlow API, reference documentation here:
https://airflow.apache.org/docs/apache-airflow/stable/tutorial_taskflow_api.html
"""
@task()
def extract():
"""
#### Extract task
A simple "extract" task to get data ready for the rest of the
pipeline. In this case, getting data is simulated by reading from a
hardcoded JSON string.
"""
data_string = '{"1001": 301.27, "1002": 433.21, "1003": 502.22}'
order_data_dict = json.loads(data_string)
return order_data_dict
@task(multiple_outputs=True) # multiple_outputs=True unrolls dictionaries into separate XCom values
def transform(order_data_dict: dict):
"""
#### Transform task
A simple "transform" task which takes in the collection of order data and
computes the total order value.
"""
total_order_value = 0
for value in order_data_dict.values():
total_order_value += value
return {"total_order_value": total_order_value}
@task()
def load(total_order_value: float):
"""
#### Load task
A simple "load" task that takes in the result of the "transform" task and prints it out,
instead of saving it to end user review
"""
print(f"Total order value is: {total_order_value:.2f}")
order_data = extract()
order_summary = transform(order_data)
load(order_summary["total_order_value"])
example_dag_basic = example_dag_basic()
`) | airflow/include/basicexampledag.go | 0.622574 | 0.623234 | basicexampledag.go | starcoder |
package wonsz
import "unicode"
// camelCaseToDashedLowered converts text from
// camelCase naming convention (begin new words with capital letter except first word)
// to kebab-case naming convention (separate words with dashes).
func camelCaseToDashedLowered(text string) string {
return camelCaseToSeparatorsLowered(text, '-')
}
// camelCaseToUnderscoredLowered converts text from
// camelCase naming convention (begin new words with capital letter except first word)
// to snake_case naming convention (separate words with underscores).
func camelCaseToUnderscoredLowered(text string) string {
return camelCaseToSeparatorsLowered(text, '_')
}
// camelCaseToSeparatorsLowered converts text from
// camelCase naming convention (begin new words with capital letter except first word)
// to lowercase text with words separated by specified separator.
func camelCaseToSeparatorsLowered(text string, separator rune) string {
separators := getDesiredSeparatorPositions(text)
newLen := len(text) + len(separators)
converted := make([]rune, newLen)
insertedSeparators := 0
for i, letter := range text {
idx := i + insertedSeparators
if _, ok := separators[i]; ok {
converted[idx] = separator
insertedSeparators++
idx++
}
lowered := unicode.ToLower(letter)
converted[idx] = lowered
}
return string(converted)
}
// getDesiredSeparatorPositions takes as a parameter text in
// camelCase naming convention (begin new words with capital letter except first word)
// and returns a places where two words should be separated (as map keys).
// If word contains a several capital letters in a row, separation will occur before last capital letter.
// Numbers will also be separated. It skips runes other than letters & numbers.
func getDesiredSeparatorPositions(text string) map[int]struct{} {
separators := map[int]struct{}{}
upperSequence := false
numberSequence := false
for i, j := 0, 1; j < len(text); i, j = i+1, j+1 {
letter := rune(text[i])
nextLetter := rune(text[j])
if !unicode.IsLetter(letter) && !unicode.IsNumber(letter) {
continue
}
if unicode.IsUpper(letter) && unicode.IsUpper(nextLetter) {
upperSequence = true
continue
}
if unicode.IsNumber(letter) && unicode.IsNumber(nextLetter) {
numberSequence = true
continue
}
if unicode.IsUpper(nextLetter) || unicode.IsNumber(nextLetter) {
separators[j] = struct{}{}
} else if upperSequence {
separators[i] = struct{}{}
upperSequence = false
} else if numberSequence {
separators[j] = struct{}{}
numberSequence = false
}
}
return separators
} | names_conversion.go | 0.708414 | 0.400632 | names_conversion.go | starcoder |
package scene
import (
"github.com/eriklupander/rt/internal/pkg/config"
"github.com/eriklupander/rt/internal/pkg/mat"
"math"
)
func DoF() *Scene {
camera := mat.NewCamera(config.Cfg.Width, config.Cfg.Height, math.Pi/3)
viewTransform := mat.ViewTransform(mat.NewPoint(-1, 0.5, -3), mat.NewPoint(0, 0.5, 0), mat.NewVector(0, 1, 0))
camera.Transform = viewTransform
camera.Inverse = mat.Inverse(viewTransform)
camera.Aperture = 0.05
camera.FocalLength = 2.0
cube := mat.NewCube()
cm := mat.NewMaterial(mat.NewColor(1.5, 1.5, 1.5), 1, 0, 0, 100)
cube.SetMaterial(cm)
cube.SetTransform(mat.Translate(-5, 2, -6))
cube.SetTransform(mat.Scale(1, 1, 0.1))
cube.CastShadow = false
plane := mat.NewPlane()
pm := mat.NewMaterial(mat.NewColor(1, 1, 1), 0.025, 0.67, 0, 200)
plane.SetMaterial(pm)
sphere1 := mat.NewSphere()
sm1 := mat.NewMaterial(mat.NewColor(1, 0, 0), 0.1, 0.6, 0, 200)
sm1.Reflectivity = 0.3
sphere1.SetMaterial(sm1)
sphere1.SetTransform(mat.Translate(0.25, 0.5, -0.5))
sphere1.SetTransform(mat.Scale(0.5, 0.5, 0.5))
sphere2 := mat.NewSphere()
sm2 := mat.NewMaterial(mat.NewColor(0.5, 0.5, 1), 0.1, 0.6, 0, 200)
sm2.Reflectivity = 0.3
sphere2.SetMaterial(sm2)
sphere2.SetTransform(mat.Translate(.25, 0.33, -1.5))
sphere2.SetTransform(mat.Scale(0.33, 0.33, 0.33))
sphere3 := mat.NewSphere()
sm3 := mat.NewMaterial(mat.NewColor(0.25, 1, 0.25), 0.1, 0.6, 0, 200)
sm3.Reflectivity = 0.3
sphere3.SetMaterial(sm3)
sphere3.SetTransform(mat.Translate(-0.5, 0.5, 1))
sphere3.SetTransform(mat.Scale(0.5, 0.5, 0.5))
sphere4 := mat.NewSphere()
sm4 := mat.NewMaterial(mat.NewColor(0.9, 0.9, 0.96), 0.1, 0.6, 0, 200)
sm4.Reflectivity = 0.3
sphere4.SetMaterial(sm4)
sphere4.SetTransform(mat.Translate(-1.5, 0.5, 4))
sphere4.SetTransform(mat.Scale(0.5, 0.5, 0.5))
return &Scene{
Camera: camera,
AreaLights: []mat.AreaLight{mat.NewAreaLight(
mat.NewPoint(-5, 2, -6),
mat.NewVector(2, 0, 0), config.Cfg.SoftShadowSamples,
mat.NewVector(0, 2, 0), config.Cfg.SoftShadowSamples,
mat.NewColor(1.5, 1.5, 1.5))},
Objects: []mat.Shape{
cube, plane, sphere1, sphere2, sphere3, sphere4,
},
}
} | scene/dof.go | 0.526586 | 0.508422 | dof.go | starcoder |
package example
import (
"fmt"
"sort"
"strconv"
"time"
)
type test struct {
ID string
Description string
}
func countLoop() {
// General for loop comprised of the init statement (optional), condition expression and post statement (optional). This counts 10 times.
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Printf("Output from the loop: %d\n\n", sum)
}
func infiniteLoop() {
//An infinite for loop but to ensure it exits we break out if the second is divisible by 5
for {
fmt.Printf("The time is: %d\n", time.Now().Second())
if time.Now().Second()%5 == 0 {
fmt.Println("The second is divisible by 5 exiting loop and function.")
return
}
time.Sleep(1 * time.Second)
}
}
func arrayLoop() {
// Configures the test data
var testData []*test
for i := 0; i < 10; i++ {
// Note: Append is a variadic function
testData = append(testData, &test{
ID: strconv.Itoa(i),
Description: "Test data for id " + strconv.Itoa(i),
})
}
// Loop over all items of an array of pointers to a custom struct and provides the key and the value for each.
fmt.Println("Output:")
for index, value := range testData {
fmt.Printf("index=%d value=%s\n", index, value)
}
fmt.Printf("\n\n")
}
func mapLoop() {
// Configures the test data
testData := make(map[string]*test)
for i := 0; i < 10; i++ {
testData["keys"+strconv.Itoa(i)] = &test{
ID: strconv.Itoa(i),
Description: "Test data for id " + strconv.Itoa(i),
}
}
// Loops over a map of keys (strings) and provides the value (custom struct) for each.
fmt.Println("Unsorted output:")
for key, value := range testData {
fmt.Printf("key=%s value=%s\n", key, value)
}
// As ranging through a map returns keys in an unsorted manner we will need another mechanism to sort the keys.
fmt.Println("\nNow implementing sorted keys...\nSorted output:")
// Configures an ordered list of keys via an array which can be iterated over to get the details from the map.
var keys []string
for k := range testData {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("key=%s value=%s\n", k, testData[k])
}
}
func init() {
examples := runs{
{"Normal count loop", countLoop},
{"Infinite Loop", infiniteLoop},
{"Arrays", arrayLoop},
{"Map i.e. Hash Table", mapLoop},
}
GetMyExamples().Add("loops", examples.runExamples)
} | chase/internal/pkg/example/loops.go | 0.582254 | 0.42668 | loops.go | starcoder |
package sketchy
import (
"github.com/tdewolff/canvas"
)
type KDTree struct {
point *IndexPoint
region Rect
left *KDTree
right *KDTree
}
func NewKDTree(r Rect) *KDTree {
return &KDTree{
point: nil,
region: r,
left: nil,
right: nil,
}
}
func NewKDTreeWithPoint(p IndexPoint, r Rect) *KDTree {
return &KDTree{
point: &p,
region: r,
left: nil,
right: nil,
}
}
func (k *KDTree) IsLeaf() bool {
return k.left == nil && k.right == nil
}
func (k *KDTree) Insert(p IndexPoint) {
k.insert(p, 0)
}
func (k *KDTree) Search(p IndexPoint) *IndexPoint {
var result *IndexPoint
if !k.region.ContainsPoint(p.Point) {
return nil
}
if k.point == nil {
return nil
}
if k.point.Point.IsEqual(p.Point) {
return k.point
}
if k.left != nil {
result = k.left.Search(p)
if result != nil {
return result
}
}
if k.right != nil {
result = k.right.Search(p)
if result != nil {
return result
}
}
return nil
}
func (k *KDTree) UpdateIndex(p IndexPoint, index int) *IndexPoint {
var result *IndexPoint
if !k.region.ContainsPoint(p.Point) {
return nil
}
if k.point == nil {
return nil
}
if k.point.Point.IsEqual(p.Point) {
k.point.Index = index
return k.point
}
if k.left != nil {
result = k.left.UpdateIndex(p, index)
if result != nil {
return result
}
}
if k.right != nil {
result = k.right.UpdateIndex(p, index)
if result != nil {
return result
}
}
return nil
}
func (k *KDTree) Query(r Rect) []Point {
var results []Point
if k.point != nil && r.ContainsPoint(k.point.Point) {
results = append(results, k.point.Point)
}
if k.left != nil {
if r.Contains(k.left.region) {
results = append(results, k.left.reportSubtree()...)
} else {
if r.Overlaps(k.left.region) {
query := k.left.Query(r)
if len(query) > 0 {
results = append(results, query...)
}
}
}
}
if k.right != nil {
if r.Contains(k.right.region) {
results = append(results, k.right.reportSubtree()...)
} else {
if r.Overlaps(k.right.region) {
query := k.right.Query(r)
if len(query) > 0 {
results = append(results, query...)
}
}
}
}
return results
}
func (k *KDTree) NearestNeighbors(point IndexPoint, s int) []IndexPoint {
var result []IndexPoint
if s <= 0 {
return result
}
ph := NewMaxPointHeap()
k.pushOnHeap(point, ph, s)
points := ph.ReportReversed()
for _, p := range points {
result = append(result, p.ToIndexPoint())
}
return result
}
func (k *KDTree) Clear() {
k.point = nil
k.left = nil
k.right = nil
}
func (k *KDTree) Size() int {
count := 1
if k.left != nil {
count += k.left.Size()
}
if k.right != nil {
count += k.right.Size()
}
return count
}
func (k *KDTree) Draw(ctx *canvas.Context) {
k.draw(ctx, 0, 0)
}
func (k *KDTree) DrawWithPoints(s float64, ctx *canvas.Context) {
k.draw(ctx, 0, s)
}
func (k *KDTree) insert(p IndexPoint, d int) {
if k.point == nil {
k.point = &p
return
}
if d%2 == 0 { // compare x value
if p.X < k.point.X {
if k.left == nil {
rect := Rect{
X: k.region.X,
Y: k.region.Y,
W: k.point.X - k.region.X,
H: k.region.H,
}
k.left = NewKDTreeWithPoint(p, rect)
} else {
k.left.insert(p, d+1)
}
} else {
if k.right == nil {
rect := Rect{
X: k.point.X,
Y: k.region.Y,
W: k.region.W - (k.point.X - k.region.X),
H: k.region.H,
}
k.right = NewKDTreeWithPoint(p, rect)
} else {
k.right.insert(p, d+1)
}
}
} else { // compare y value
if p.Y < k.point.Y {
if k.left == nil {
rect := Rect{
X: k.region.X,
Y: k.region.Y,
W: k.region.W,
H: k.point.Y - k.region.Y,
}
k.left = NewKDTreeWithPoint(p, rect)
} else {
k.left.insert(p, d+1)
}
} else {
if k.right == nil {
rect := Rect{
X: k.region.X,
Y: k.point.Y,
W: k.region.W,
H: k.region.H - (k.point.Y - k.region.Y),
}
k.right = NewKDTreeWithPoint(p, rect)
} else {
k.right.insert(p, d+1)
}
}
}
}
func (k *KDTree) reportSubtree() []Point {
var results []Point
results = append(results, k.point.Point)
if k.left != nil {
results = append(results, k.left.reportSubtree()...)
}
if k.right != nil {
results = append(results, k.right.reportSubtree()...)
}
return results
}
func (k *KDTree) draw(ctx *canvas.Context, depth int, pointSize float64) {
if k.point == nil {
return
}
if depth%2 == 0 {
ctx.MoveTo(k.point.X, k.region.Y)
ctx.LineTo(k.point.X, k.region.Y+k.region.H)
ctx.Stroke()
} else {
ctx.MoveTo(k.region.X, k.point.Y)
ctx.LineTo(k.region.X+k.region.W, k.point.Y)
ctx.Stroke()
}
if pointSize > 0 {
ctx.DrawPath(k.point.X, k.point.Y, canvas.Circle(pointSize))
}
if k.left != nil {
k.left.draw(ctx, depth+1, pointSize)
}
if k.right != nil {
k.right.draw(ctx, depth+1, pointSize)
}
}
func (k *KDTree) pushOnHeap(target IndexPoint, h *PointHeap, s int) {
if k.point != nil {
if k.point.Index != target.Index {
metric := SquaredDistance(target.Point, k.point.Point)
mp := MetricPoint{
Metric: metric,
Index: k.point.Index,
Point: k.point.Point,
}
if h.Len() < s {
h.Push(mp)
} else {
if metric < h.Peek().Metric {
_ = h.Pop()
h.Push(mp)
}
}
}
}
if k.left != nil {
k.left.pushOnHeap(target, h, s)
}
if k.right != nil {
k.right.pushOnHeap(target, h, s)
}
} | kdtree.go | 0.727685 | 0.427755 | kdtree.go | starcoder |
package api
import (
"encoding/json"
"time"
)
// CellLocation struct for CellLocation
type CellLocation struct {
// Average signal strength from all observations for the cell network. This is an integer value, in dBm.
AvgStrength *int32 `json:"avg_strength,omitempty"`
// Timestamp of the time when this record was first created.
Created *time.Time `json:"created,omitempty"`
// Whether or not this cell is a position estimate based on observations subject to change in the future (`0`) or an exact location entered from a knowledgeable source (`1`).
Exact *int32 `json:"exact,omitempty"`
// Latitude
Lat *float64 `json:"lat,omitempty"`
// Longitude
Lon *float64 `json:"lon,omitempty"`
// Estimate of radio range, in meters. This is an estimate on how large each cell area is, as a radius around the estimated position and is based on the observations or a knowledgeable source.
Range *int32 `json:"range,omitempty"`
// Total number of observations used to calculate the estimated position, range and avg_strength.
Samples *int32 `json:"samples,omitempty"`
// Timestamp of the time when this record was most recently modified.
Updated *time.Time `json:"updated,omitempty"`
}
// NewCellLocation instantiates a new CellLocation object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewCellLocation() *CellLocation {
this := CellLocation{}
return &this
}
// NewCellLocationWithDefaults instantiates a new CellLocation object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewCellLocationWithDefaults() *CellLocation {
this := CellLocation{}
return &this
}
// GetAvgStrength returns the AvgStrength field value if set, zero value otherwise.
func (o *CellLocation) GetAvgStrength() int32 {
if o == nil || o.AvgStrength == nil {
var ret int32
return ret
}
return *o.AvgStrength
}
// GetAvgStrengthOk returns a tuple with the AvgStrength field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetAvgStrengthOk() (*int32, bool) {
if o == nil || o.AvgStrength == nil {
return nil, false
}
return o.AvgStrength, true
}
// HasAvgStrength returns a boolean if a field has been set.
func (o *CellLocation) HasAvgStrength() bool {
if o != nil && o.AvgStrength != nil {
return true
}
return false
}
// SetAvgStrength gets a reference to the given int32 and assigns it to the AvgStrength field.
func (o *CellLocation) SetAvgStrength(v int32) {
o.AvgStrength = &v
}
// GetCreated returns the Created field value if set, zero value otherwise.
func (o *CellLocation) GetCreated() time.Time {
if o == nil || o.Created == nil {
var ret time.Time
return ret
}
return *o.Created
}
// GetCreatedOk returns a tuple with the Created field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetCreatedOk() (*time.Time, bool) {
if o == nil || o.Created == nil {
return nil, false
}
return o.Created, true
}
// HasCreated returns a boolean if a field has been set.
func (o *CellLocation) HasCreated() bool {
if o != nil && o.Created != nil {
return true
}
return false
}
// SetCreated gets a reference to the given time.Time and assigns it to the Created field.
func (o *CellLocation) SetCreated(v time.Time) {
o.Created = &v
}
// GetExact returns the Exact field value if set, zero value otherwise.
func (o *CellLocation) GetExact() int32 {
if o == nil || o.Exact == nil {
var ret int32
return ret
}
return *o.Exact
}
// GetExactOk returns a tuple with the Exact field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetExactOk() (*int32, bool) {
if o == nil || o.Exact == nil {
return nil, false
}
return o.Exact, true
}
// HasExact returns a boolean if a field has been set.
func (o *CellLocation) HasExact() bool {
if o != nil && o.Exact != nil {
return true
}
return false
}
// SetExact gets a reference to the given int32 and assigns it to the Exact field.
func (o *CellLocation) SetExact(v int32) {
o.Exact = &v
}
// GetLat returns the Lat field value if set, zero value otherwise.
func (o *CellLocation) GetLat() float64 {
if o == nil || o.Lat == nil {
var ret float64
return ret
}
return *o.Lat
}
// GetLatOk returns a tuple with the Lat field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetLatOk() (*float64, bool) {
if o == nil || o.Lat == nil {
return nil, false
}
return o.Lat, true
}
// HasLat returns a boolean if a field has been set.
func (o *CellLocation) HasLat() bool {
if o != nil && o.Lat != nil {
return true
}
return false
}
// SetLat gets a reference to the given float64 and assigns it to the Lat field.
func (o *CellLocation) SetLat(v float64) {
o.Lat = &v
}
// GetLon returns the Lon field value if set, zero value otherwise.
func (o *CellLocation) GetLon() float64 {
if o == nil || o.Lon == nil {
var ret float64
return ret
}
return *o.Lon
}
// GetLonOk returns a tuple with the Lon field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetLonOk() (*float64, bool) {
if o == nil || o.Lon == nil {
return nil, false
}
return o.Lon, true
}
// HasLon returns a boolean if a field has been set.
func (o *CellLocation) HasLon() bool {
if o != nil && o.Lon != nil {
return true
}
return false
}
// SetLon gets a reference to the given float64 and assigns it to the Lon field.
func (o *CellLocation) SetLon(v float64) {
o.Lon = &v
}
// GetRange returns the Range field value if set, zero value otherwise.
func (o *CellLocation) GetRange() int32 {
if o == nil || o.Range == nil {
var ret int32
return ret
}
return *o.Range
}
// GetRangeOk returns a tuple with the Range field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetRangeOk() (*int32, bool) {
if o == nil || o.Range == nil {
return nil, false
}
return o.Range, true
}
// HasRange returns a boolean if a field has been set.
func (o *CellLocation) HasRange() bool {
if o != nil && o.Range != nil {
return true
}
return false
}
// SetRange gets a reference to the given int32 and assigns it to the Range field.
func (o *CellLocation) SetRange(v int32) {
o.Range = &v
}
// GetSamples returns the Samples field value if set, zero value otherwise.
func (o *CellLocation) GetSamples() int32 {
if o == nil || o.Samples == nil {
var ret int32
return ret
}
return *o.Samples
}
// GetSamplesOk returns a tuple with the Samples field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetSamplesOk() (*int32, bool) {
if o == nil || o.Samples == nil {
return nil, false
}
return o.Samples, true
}
// HasSamples returns a boolean if a field has been set.
func (o *CellLocation) HasSamples() bool {
if o != nil && o.Samples != nil {
return true
}
return false
}
// SetSamples gets a reference to the given int32 and assigns it to the Samples field.
func (o *CellLocation) SetSamples(v int32) {
o.Samples = &v
}
// GetUpdated returns the Updated field value if set, zero value otherwise.
func (o *CellLocation) GetUpdated() time.Time {
if o == nil || o.Updated == nil {
var ret time.Time
return ret
}
return *o.Updated
}
// GetUpdatedOk returns a tuple with the Updated field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *CellLocation) GetUpdatedOk() (*time.Time, bool) {
if o == nil || o.Updated == nil {
return nil, false
}
return o.Updated, true
}
// HasUpdated returns a boolean if a field has been set.
func (o *CellLocation) HasUpdated() bool {
if o != nil && o.Updated != nil {
return true
}
return false
}
// SetUpdated gets a reference to the given time.Time and assigns it to the Updated field.
func (o *CellLocation) SetUpdated(v time.Time) {
o.Updated = &v
}
func (o CellLocation) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.AvgStrength != nil {
toSerialize["avg_strength"] = o.AvgStrength
}
if o.Created != nil {
toSerialize["created"] = o.Created
}
if o.Exact != nil {
toSerialize["exact"] = o.Exact
}
if o.Lat != nil {
toSerialize["lat"] = o.Lat
}
if o.Lon != nil {
toSerialize["lon"] = o.Lon
}
if o.Range != nil {
toSerialize["range"] = o.Range
}
if o.Samples != nil {
toSerialize["samples"] = o.Samples
}
if o.Updated != nil {
toSerialize["updated"] = o.Updated
}
return json.Marshal(toSerialize)
}
type NullableCellLocation struct {
value *CellLocation
isSet bool
}
func (v NullableCellLocation) Get() *CellLocation {
return v.value
}
func (v *NullableCellLocation) Set(val *CellLocation) {
v.value = val
v.isSet = true
}
func (v NullableCellLocation) IsSet() bool {
return v.isSet
}
func (v *NullableCellLocation) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableCellLocation(val *CellLocation) *NullableCellLocation {
return &NullableCellLocation{value: val, isSet: true}
}
func (v NullableCellLocation) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableCellLocation) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | openapi/api/model_cell_location.go | 0.855157 | 0.448607 | model_cell_location.go | starcoder |
package spatial
import (
"log"
"github.com/pmezard/gogeos/geos"
)
func (p Polygon) clipToBBox(b BBox) []Geom {
gpoly := p.geos()
if gpoly == nil {
return nil
}
var bboxLine = make([]geos.Coord, 0, 4)
for _, pt := range NewLinesFromSegments(BBoxBorders(b.SW, b.NE))[0] {
bboxLine = append(bboxLine, geos.NewCoord(pt.X, pt.Y))
}
bboxPoly := geos.Must(geos.NewPolygon(bboxLine))
res, err := bboxPoly.Intersection(gpoly)
if err != nil {
// Sometimes there is a minor topology problem, a zero buffer helps often.
gpolyBuffed, err := gpoly.Buffer(0)
if err != nil {
panic(err)
}
res, err = bboxPoly.Intersection(gpolyBuffed)
if err != nil {
panic(err)
}
}
var resGeoms []Geom
for _, poly := range geosToPolygons(res) {
resGeoms = append(resGeoms, MustNewGeom(poly))
}
return resGeoms
}
func (p Polygon) geos() *geos.Geometry {
var rings = make([][]geos.Coord, 0, len(p))
for _, ring := range p {
var rg = make([]geos.Coord, 0, len(ring))
for _, pt := range ring {
rg = append(rg, geos.NewCoord(pt.X, pt.Y))
}
rg = append(rg, rg[0])
rings = append(rings, rg)
}
var gpoly *geos.Geometry
if len(rings) == 0 {
return nil
}
if len(rings) > 1 {
return geos.Must(geos.NewPolygon(rings[0], rings[1:]...))
}
gpoly, err := geos.NewPolygon(rings[0])
if err != nil {
log.Printf("invalid polygon: %v", err)
return nil
}
return gpoly
}
func geosToPolygons(g *geos.Geometry) []Polygon {
ty, _ := g.Type()
if ty == geos.POLYGON {
return []Polygon{geosToPolygon(g)}
}
nmax, err := g.NGeometry()
if err != nil {
panic(err)
}
var polys = make([]Polygon, 0, nmax)
for n := 0; n < nmax; n++ {
polys = append(polys, geosToPolygon(geos.Must(g.Geometry(n))))
}
return polys
}
func geosToPolygon(g *geos.Geometry) Polygon {
sh, err := g.Shell()
if err != nil {
return Polygon{}
}
crds, err := sh.Coords()
if err != nil {
panic(err)
}
if len(crds) == 0 { // we got an empty polygon
return Polygon{}
}
var (
p = make(Polygon, 0, 8)
ring = make([]Point, 0, len(crds))
)
for _, crd := range crds {
ring = append(ring, Point{crd.X, crd.Y})
}
p = append(p, ring[:len(ring)-1])
holes, _ := g.Holes()
for _, hole := range holes {
crds, err = hole.Coords()
if err != nil {
panic(err)
}
ring = make([]Point, 0, len(crds))
for _, crd := range crds {
ring = append(ring, Point{crd.X, crd.Y})
}
p = append(p, ring[:len(ring)-1])
}
return p
} | lib/spatial/clip_geos.go | 0.571886 | 0.400925 | clip_geos.go | starcoder |
package apimodel
import (
"errors"
"fmt"
"github.com/alexandre-normand/glukit/app/util"
"time"
)
const (
CALIBRATION_READ_TAG = "CalibrationRead"
)
// CalibrationRead represents a CGM read (not to be confused with a MeterRead which is a calibration value from an external
// meter
type CalibrationRead struct {
Time Time `json:"time" datastore:"time,noindex"`
Unit GlucoseUnit `json:"unit" datastore:"unit,noindex"`
Value float32 `json:"value" datastore:"value,noindex"`
}
// This holds an array of reads for a whole day
type DayOfCalibrationReads struct {
Reads []CalibrationRead `datastore:"calibrations,noindex"`
StartTime time.Time `datastore:"startTime"`
EndTime time.Time `datastore:"endTime"`
}
// GetTime gets the time of a Timestamp value
func (element CalibrationRead) GetTime() time.Time {
return element.Time.GetTime()
}
func NewDayOfCalibrationReads(reads []CalibrationRead) DayOfCalibrationReads {
return DayOfCalibrationReads{reads, reads[0].GetTime().Truncate(DAY_OF_DATA_DURATION), reads[len(reads)-1].GetTime()}
}
type CalibrationReadSlice []CalibrationRead
func (slice CalibrationReadSlice) Len() int {
return len(slice)
}
func (slice CalibrationReadSlice) Less(i, j int) bool {
return slice[i].Time.Timestamp < slice[j].Time.Timestamp
}
func (slice CalibrationReadSlice) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
func (slice CalibrationReadSlice) Get(i int) float64 {
return float64(slice[i].Value)
}
func (slice CalibrationReadSlice) GetEpochTime(i int) (epochTime int64) {
return slice[i].Time.Timestamp / 1000
}
// GetNormalizedValue gets the normalized value to the requested unit
func (element CalibrationRead) GetNormalizedValue(unit GlucoseUnit) (float32, error) {
if unit == element.Unit {
return element.Value, nil
}
if element.Unit == UNKNOWN_GLUCOSE_MEASUREMENT_UNIT {
return element.Value, nil
}
// This switch can focus on only conversion cases because the obvious
// cases have been sorted out already
switch unit {
case MMOL_PER_L:
return element.Value * 0.0555, nil
case MG_PER_DL:
return element.Value * 18.0182, nil
default:
return -1., errors.New(fmt.Sprintf("Bad unit requested, [%s] is not one of [%s, %s]", unit, MG_PER_DL, MMOL_PER_L))
}
}
// ToDataPointSlice converts a CalibrationReadSlice into a generic DataPoint array
func (slice CalibrationReadSlice) ToDataPointSlice() (dataPoints []DataPoint) {
dataPoints = make([]DataPoint, len(slice))
for i := range slice {
localTime, err := slice[i].Time.Format()
if err != nil {
util.Propagate(err)
}
// It's pretty terrible if this happens and we crash the app but this is a coding error and I want to know early
mgPerDlValue, err := slice[i].GetNormalizedValue(MG_PER_DL)
if err != nil {
util.Propagate(err)
}
dataPoint := DataPoint{localTime, slice.GetEpochTime(i), mgPerDlValue, float32(slice[i].Value), CALIBRATION_READ_TAG, MG_PER_DL}
dataPoints[i] = dataPoint
}
return dataPoints
}
var UNDEFINED_CALIBRATION_READ = CalibrationRead{Time{0, "UTC"}, "NONE", -1.} | app/apimodel/calibration.go | 0.801548 | 0.522872 | calibration.go | starcoder |
package bandrng
import (
"math"
)
// safeAdd performs the addition operation on two uint64 integers, but panics if overflow.
func safeAdd(a, b uint64) uint64 {
if math.MaxUint64-a < b {
panic("bandrng::safeAdd: overflow addition")
}
return a + b
}
// ChooseOne randomly picks an index between 0 and len(weights)-1 inclusively. Each index has
// the probability of getting selected based on its weight.
func ChooseOne(rng *Rng, weights []uint64) int {
sum := uint64(0)
for _, weight := range weights {
sum = safeAdd(sum, weight)
}
luckyNumber := rng.NextUint64() % sum
currentSum := uint64(0)
for idx, weight := range weights {
currentSum += weight
if currentSum > luckyNumber {
return idx
}
}
// We should never reach here since the sum of weights is greater than the lucky number.
panic("bandrng::ChooseOne: reaching the unreachable")
}
// ChooseSome randomly picks non-duplicate "cnt" indexes between 0 and len(weights)-1 inclusively.
// The function calls ChooseOne to get an index based on the given weights. When an index is
// chosen, it gets removed from the pool. The process gets repeated until "cnt" indexes are chosen.
func ChooseSome(rng *Rng, weights []uint64, cnt int) []int {
chosenIndexes := make([]int, cnt)
availableWeights := make([]uint64, len(weights))
availableIndexes := make([]int, len(weights))
for idx, weight := range weights {
availableWeights[idx] = weight
availableIndexes[idx] = idx
}
for round := 0; round < cnt; round++ {
chosen := ChooseOne(rng, availableWeights)
chosenIndexes[round] = availableIndexes[chosen]
availableWeights = append(availableWeights[:chosen], availableWeights[chosen+1:]...)
availableIndexes = append(availableIndexes[:chosen], availableIndexes[chosen+1:]...)
}
return chosenIndexes
}
// ChooseSomeMaxWeight performs ChooseSome "tries" times and returns the sampling with the
// highest weight sum among all tries.
func ChooseSomeMaxWeight(rng *Rng, weights []uint64, cnt int, tries int) []int {
var maxWeightSum uint64 = 0
var maxWeightResult []int = nil
for each := 0; each < tries; each++ {
candidate := ChooseSome(rng, weights, cnt)
candidateWeightSum := uint64(0)
for _, idx := range candidate {
candidateWeightSum += weights[idx]
}
if candidateWeightSum > maxWeightSum {
maxWeightSum = candidateWeightSum
maxWeightResult = candidate
}
}
return maxWeightResult
} | chain/pkg/bandrng/sampling.go | 0.747524 | 0.485966 | sampling.go | starcoder |
package machinestate
import (
"fmt"
"strings"
)
// State defines the Machines state
type State int
const (
// Unknown is a state that needs to be resolved manually
Unknown State = iota
// NotInitialzed defines a state where the machine instance does not exists
// and was not built once. It's waits to be initialized
NotInitialized
// Building is in progress of creating the machine A successfull Booting
// state results in a Running state.
Building
// Starting defines the state where the machine is booting. A succesfull
// Starting state results in a Running state.
Starting
// Running defines the state where the machine is running.
Running
// Stopping is in progress of stopping the machine. A succesfull Stopping
// state results in a Stopped state.
Stopping
// Stopped defines the state where the machine is stopped and turned of.
Stopped
// Rebooting defines the state where the machine is rebooting. A succesfull
// Rebooting state results in a Running state.
Rebooting
// Terminating defines the state where the machine is being terminated. A
// succesfull Terminating state results in a Terminated state.
Terminating
// Terminated defines the state where the machine is destroyed. It
// physically doesn't exist anymore.
Terminated
// Snapshotting defines the state where the machine is in a snapshotting
// process.
Snapshotting
// Pending defines the state where the machine is in a work-in-progress
// state. A pending state might be a state between two stable states of a
// machine such as Stopped and Starting where we resized a disk. A Machine
// could be in a pending state when an ongoign maintanance is in progress.
Pending
)
var States = map[string]State{
"NotInitialized": NotInitialized,
"Building": Building,
"Starting": Starting,
"Running": Running,
"Stopping": Stopping,
"Stopped": Stopped,
"Rebooting": Rebooting,
"Terminating": Terminating,
"Terminated": Terminated,
"Snapshotting": Snapshotting,
"Pending": Pending,
"Unknown": Unknown,
}
// MarshalJSON implements the json.Marshaler interface. The state is a quoted
// string.
func (s State) MarshalJSON() ([]byte, error) {
return []byte(`"` + s.String() + `"`), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface. The state is
// expected to be a quoted string and available/exist in the States map.
func (s *State) UnmarshalJSON(d []byte) error {
// comes as `"PENDING"`, will convert to `PENDING`
unquoted := strings.Replace(string(d), "\"", "", -1)
var ok bool
*s, ok = States[unquoted]
if !ok {
return fmt.Errorf("unknown value: %s", string(d))
}
return nil
}
// In checks if the state is available in the given state.
func (s State) In(states ...State) bool {
for _, state := range states {
if state == s {
return true
}
}
return false
}
// InProgress checks whether the given state is one of the states that defines
// a ongoing process, such as building, starting, stopping, etc...
func (s State) InProgress() bool {
if s.In(Building, Starting, Stopping, Terminating, Rebooting, Pending) {
return true
}
return false
}
// ValidMethods returns a list of valid methods which can be applied to the
// state that is not in progress. A method changes a machine states from one to
// another. For example a "Stopped" state will be changed to the final state
// "Running" when a "start" method is applied. However the final state can also
// be "Terminated" when a "destroy" method is applied. Thefore "start" and
// "destroy" both are valid methods for the state "Stopped" (so is "resize"
// too).
func (s State) ValidMethods() []string {
// Nothing is valid for a state that is marked as "InProgress".
if s.InProgress() {
return nil
}
switch s {
case NotInitialized:
return []string{"build", "destroy"}
case Running:
return []string{
"stop",
"resize",
"destroy",
"restart",
"reinit",
"createSnapshot",
"deleteSnapshot",
}
case Stopped:
return []string{
"start",
"resize",
"destroy",
"reinit",
"createSnapshot",
"deleteSnapshot",
}
case Terminated:
return []string{"build"}
default:
return nil
}
}
func (s State) String() string {
switch s {
case NotInitialized:
return "NotInitialized"
case Building:
return "Building"
case Starting:
return "Starting"
case Running:
return "Running"
case Stopping:
return "Stopping"
case Stopped:
return "Stopped"
case Rebooting:
return "Rebooting"
case Terminating:
return "Terminating"
case Terminated:
return "Terminated"
case Snapshotting:
return "Snapshotting"
case Pending:
return "Pending"
case Unknown:
fallthrough
default:
return "Unknown"
}
} | go/src/koding/kites/kloud/machinestate/machinestate.go | 0.629775 | 0.541773 | machinestate.go | starcoder |
package holiday
import (
"encoding/json"
"log"
"time"
"github.com/marcelblijleven/holiday/easter"
)
type holiday struct {
Name string `json:"name"`
Date time.Time `json:"date"`
Official bool `json:"official"`
}
func newHoliday(name string, date time.Time, official bool) holiday {
return holiday{name, date, official}
}
// GetHolidays returns the mayor holidays in the given year
func GetHolidays(year int) ([]byte, error) {
var holidays []holiday
day := time.Hour * 24
// First, determine the date of Easter
easterDate := easter.GetEasterDateForYear(year)
// Using the date of Easter, we can calculate the dynamic holidays
goodFriday := newHoliday("Good Friday", easterDate.Add(day*-2), false)
easter := newHoliday("Easter", easterDate, true)
easterMonday := newHoliday("Easter Monday", easterDate.Add(day), true)
ascensionDay := newHoliday("Ascension Day", easterDate.Add(day*39), true)
pentecost := newHoliday("Pentecost", ascensionDay.Date.Add(day*10), true)
pentecostMonday := newHoliday("Pentecost Monday", pentecost.Date.Add(day), true)
holidays = append(
holidays,
goodFriday,
easter,
easterMonday,
ascensionDay,
pentecost,
pentecostMonday,
)
// Now add the fixed holidays
newYear := newHoliday("New Year", time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC), true)
kingsDay := newHoliday("Kingsday", time.Date(year, 4, 27, 0, 0, 0, 0, time.UTC), true)
if kingsDay.Date.Weekday() == 0 {
// If Kingsday falls on a Sunday, move it to one day earlier
kingsDay.Date.Add(day * -1)
}
liberationDay := newHoliday("Liberation Day", time.Date(year, 5, 5, 0, 0, 0, 0, time.UTC), false)
if (year-2020)%5 == 0 {
// Once every five years, you get a day off on Liberation Day
liberationDay.Official = true
}
christmas := newHoliday("Christmas", time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC), true)
boxingDay := newHoliday("Boxing Day", time.Date(year, 12, 26, 0, 0, 0, 0, time.UTC), true)
holidays = append(
holidays,
newYear,
kingsDay,
liberationDay,
christmas,
boxingDay,
)
marshalled, err := json.MarshalIndent(holidays, "", "\t")
if err != nil {
log.Fatal(err)
return nil, err
}
return marshalled, nil
} | holiday.go | 0.679604 | 0.411702 | holiday.go | starcoder |
package gf2p16
import "github.com/akalin/gopar/gf2"
// T is an element of GF(2^16).
type T uint16
// Plus returns the sum of t and u as elements of GF(2^16), which is
// just the bitwise xor of the two.
func (t T) Plus(u T) T {
return t ^ u
}
// Minus returns the difference of t and u as elements of GF(2^16),
// which is just the bitwise xor of the two.
func (t T) Minus(u T) T {
return t ^ u
}
const order = 1 << 16
var logTable [order - 1]uint16
var expTable [order - 1]T
type mulTableEntry struct {
s0, s8 [1 << 8]T
}
var mulTable [1 << 16]mulTableEntry
func init() {
// TODO: Generate tables at compile time.
// m is the irreducible polynomial of degree 16 used to model
// GF(2^16). m was chosen to match the PAR2 spec.
const m gf2.Poly64 = 0x1100b
// g is a generator of GF(2^16).
const g T = 3
x := T(1)
for p := 0; p < order-1; p++ {
if x == 1 && p != 0 {
panic("repeated power (1)")
} else if x != 1 && logTable[x-1] != 0 {
panic("repeated power")
}
if expTable[p] != 0 {
panic("repeated exponent")
}
logTable[x-1] = uint16(p)
expTable[p] = x
_, r := gf2.Poly64(x).Times(gf2.Poly64(g)).Div(m)
x = T(r)
}
// Since we've filled in logTable and expTable, we can use
// T.Times below.
for i := 0; i < len(mulTable); i++ {
for j := 0; j < len(mulTable[i].s0); j++ {
mulTable[i].s0[j] = T(i).Times(T(j))
mulTable[i].s8[j] = T(i).Times(T(j << 8))
}
}
platformInit()
}
// Times returns the product of t and u as elements of GF(2^16).
func (t T) Times(u T) T {
if t == 0 || u == 0 {
return 0
}
logT := int(logTable[t-1])
logU := int(logTable[u-1])
return expTable[(logT+logU)%(order-1)]
}
// Inverse returns the multiplicative inverse of t, if t != 0. It
// panics if t == 0.
func (t T) Inverse() T {
if t == 0 {
panic("zero has no inverse")
}
logT := int(logTable[t-1])
return expTable[(-logT+(order-1))%(order-1)]
}
// Div returns the product of t and u^{-1} as elements of GF(2^16), if
// u != 0. It panics if u == 0.
func (t T) Div(u T) T {
if u == 0 {
panic("division by zero")
}
if t == 0 {
return 0
}
logT := int(logTable[t-1])
logU := int(logTable[u-1])
return expTable[(logT-logU+(order-1))%(order-1)]
}
// Pow returns the t^p as an element of GF(2^16). T(0).Pow(0) returns 1.
func (t T) Pow(p uint32) T {
if t == 0 {
if p == 0 {
return 1
}
return 0
}
logT := uint64(logTable[t-1])
return expTable[(logT*uint64(p))%(order-1)]
} | gf2p16/t.go | 0.597138 | 0.549882 | t.go | starcoder |
package matcher
import (
"github.com/cube2222/octosql/physical"
)
// NodeMatcher is used to match nodes on various predicates.
type NodeMatcher interface {
// Match tries to match a node filling the match. Returns true on success.
Match(match *Match, node physical.Node) bool
}
// AnyNodeMatcher matches any node.
type AnyNodeMatcher struct {
Name string
}
func (m *AnyNodeMatcher) Match(match *Match, node physical.Node) bool {
if len(m.Name) > 0 {
match.Nodes[m.Name] = node
}
return true
}
type MapMatcher struct {
Name string
Expressions NamedExpressionListMatcher
Keep PrimitiveMatcher
Source NodeMatcher
}
func (m *MapMatcher) Match(match *Match, node physical.Node) bool {
mapNode, ok := node.(*physical.Map)
if !ok {
return false
}
if m.Expressions != nil {
matched := m.Expressions.Match(match, mapNode.Expressions)
if !matched {
return false
}
}
if m.Keep != nil {
matched := m.Keep.Match(match, mapNode.Keep)
if !matched {
return false
}
}
if m.Source != nil {
matched := m.Source.Match(match, mapNode.Source)
if !matched {
return false
}
}
if len(m.Name) > 0 {
match.Nodes[m.Name] = node
}
return true
}
// RequalifierMatcher matches a requalifier with the given attributed matches.
type RequalifierMatcher struct {
Name string
Qualifier StringMatcher
Source NodeMatcher
}
func (m *RequalifierMatcher) Match(match *Match, node physical.Node) bool {
requalifier, ok := node.(*physical.Requalifier)
if !ok {
return false
}
if m.Qualifier != nil {
matched := m.Qualifier.Match(match, requalifier.Qualifier)
if !matched {
return false
}
}
if m.Source != nil {
matched := m.Source.Match(match, requalifier.Source)
if !matched {
return false
}
}
if len(m.Name) > 0 {
match.Nodes[m.Name] = node
}
return true
}
// FilterMatcher matches a filter with the given attribute matches.
type FilterMatcher struct {
Name string
Formula FormulaMatcher
Source NodeMatcher
}
func (m *FilterMatcher) Match(match *Match, node physical.Node) bool {
filter, ok := node.(*physical.Filter)
if !ok {
return false
}
if m.Formula != nil {
matched := m.Formula.Match(match, filter.Formula)
if !matched {
return false
}
}
if m.Source != nil {
matched := m.Source.Match(match, filter.Source)
if !matched {
return false
}
}
if len(m.Name) > 0 {
match.Nodes[m.Name] = node
}
return true
}
// DataSourceBuilderMatcher matches a data source builder with the given attribute matches.
type DataSourceBuilderMatcher struct {
Name string
Formula FormulaMatcher
Alias StringMatcher
}
func (m *DataSourceBuilderMatcher) Match(match *Match, node physical.Node) bool {
dsb, ok := node.(*physical.DataSourceBuilder)
if !ok {
return false
}
if m.Formula != nil {
matched := m.Formula.Match(match, dsb.Filter)
if !matched {
return false
}
}
if m.Alias != nil {
matched := m.Alias.Match(match, dsb.Alias)
if !matched {
return false
}
}
if len(m.Name) > 0 {
match.Nodes[m.Name] = node
}
return true
} | physical/matcher/node.go | 0.664867 | 0.432483 | node.go | starcoder |
package check
import (
"errors"
"fmt"
"reflect"
"time"
)
func equal(x, y interface{}) bool {
return reflect.DeepEqual(x, y)
}
func isEmpty(x interface{}) bool {
if x == nil {
return true
}
v := reflect.ValueOf(x)
switch v.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Interface, reflect.Ptr:
return isEmpty(v.Elem().Interface())
}
return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface())
}
func toInt64(x interface{}) (int64, error) {
if x == nil {
return 0, errors.New("cannot convert nil to type int64")
}
v := reflect.ValueOf(x)
kind := v.Kind()
switch kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), nil
}
return 0, fmt.Errorf("cannot convert `%v` to type int64", kind)
}
func toUint64(x interface{}) (uint64, error) {
if x == nil {
return 0, errors.New("cannot convert nil to type uint64")
}
v := reflect.ValueOf(x)
kind := v.Kind()
switch kind {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint(), nil
}
return 0, fmt.Errorf("cannot convert `%v` to type uint64", kind)
}
func toFloat64(x interface{}) (float64, error) {
if x == nil {
return 0, errors.New("cannot convert nil to type float64")
}
v := reflect.ValueOf(x)
kind := v.Kind()
switch kind {
case reflect.Float32, reflect.Float64:
return v.Float(), nil
}
return 0, fmt.Errorf("cannot convert `%v` to type float64", kind)
}
func toString(x interface{}) (string, error) {
if x == nil {
return "", errors.New("cannot convert nil to type string")
}
v := reflect.ValueOf(x)
kind := v.Kind()
if kind == reflect.String {
return v.String(), nil
}
return "", fmt.Errorf("cannot convert `%v` to type string", kind)
}
func toTime(x interface{}) (time.Time, error) {
if x == nil {
return time.Time{}, errors.New("cannot convert nil to type time.Time")
}
v, ok := x.(time.Time)
if !ok {
return time.Time{}, fmt.Errorf("cannot convert `%v` to time.Time", reflect.TypeOf(x))
}
return v, nil
} | reflect.go | 0.727879 | 0.477067 | reflect.go | starcoder |
package log
import (
"fmt"
"os"
"github.com/fatih/color"
)
// Infof print an info with a colored prefix.
// Errorln formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Infof(format string, a ...interface{}) (n int, err error) {
return fmt.Printf(fmt.Sprintf("%s", format), a...)
}
// Infoln formats using a colored prefix prior to its operands and writes to
// standard output. Spaces are always added between operands and a newline is
// appended.
func Infoln(a ...interface{}) {
for _, b := range a {
fmt.Fprint(os.Stdout, b)
}
fmt.Fprint(os.Stdout, "\n")
}
// Warningf print an info with a colored prefix.
// Errorln formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Warningf(format string, a ...interface{}) (n int, err error) {
return fmt.Printf(
fmt.Sprintf("%v %s", color.YellowString("Warning:"), format),
a...,
)
}
// Warningln formats using a colored prefix prior to its operands and writes to
// standard output. Spaces are always added between operands and a newline is
// appended.
func Warningln(a ...interface{}) {
fmt.Fprint(os.Stderr, color.YellowString("Warning:"), " ")
for _, b := range a {
fmt.Fprint(os.Stderr, b)
}
fmt.Fprint(os.Stderr, "\n")
}
// Errorf print an error with a colored prefix.
// Errorln formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Errorf(format string, a ...interface{}) (n int, err error) {
fmt.Println(fmt.Sprintf("%v %s", color.RedString("Error:"), format))
return fmt.Fprintf(
os.Stderr,
fmt.Sprintf("%v %s", color.RedString("Error:"), format),
a...,
)
}
// Errorln formats using a colored prefix prior to its operands and writes to
// standard error. Spaces are always added between operands and a newline is
// appended.
func Errorln(a ...interface{}) {
fmt.Fprint(os.Stderr, color.RedString("Error:"), " ")
for _, b := range a {
fmt.Fprint(os.Stderr, b)
}
fmt.Fprint(os.Stderr, "\n")
} | backend/log/log.go | 0.64512 | 0.420243 | log.go | starcoder |
package proxy
import (
"context"
"errors"
"fmt"
"github.com/milvus-io/milvus/internal/log"
"github.com/milvus-io/milvus/internal/proto/commonpb"
"github.com/milvus-io/milvus/internal/proto/milvuspb"
"github.com/milvus-io/milvus/internal/proto/schemapb"
"github.com/milvus-io/milvus/internal/util/distance"
"github.com/milvus-io/milvus/internal/util/funcutil"
"github.com/milvus-io/milvus/internal/util/typeutil"
"go.uber.org/zap"
)
type calcDistanceTask struct {
traceID string
queryFunc func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error)
}
func (t *calcDistanceTask) arrangeVectorsByIntID(inputIds []int64, sequence map[int64]int, retrievedVectors *schemapb.VectorField) (*schemapb.VectorField, error) {
if retrievedVectors.GetFloatVector() != nil {
floatArr := retrievedVectors.GetFloatVector().GetData()
element := retrievedVectors.GetDim()
result := make([]float32, 0, int64(len(inputIds))*element)
for _, id := range inputIds {
index, ok := sequence[id]
if !ok {
log.Error("id not found in CalcDistance", zap.Int64("id", id))
return nil, errors.New("failed to fetch vectors by id: " + fmt.Sprintln(id))
}
result = append(result, floatArr[int64(index)*element:int64(index+1)*element]...)
}
return &schemapb.VectorField{
Dim: element,
Data: &schemapb.VectorField_FloatVector{
FloatVector: &schemapb.FloatArray{
Data: result,
},
},
}, nil
}
if retrievedVectors.GetBinaryVector() != nil {
binaryArr := retrievedVectors.GetBinaryVector()
singleBitLen := distance.SingleBitLen(retrievedVectors.GetDim())
numBytes := singleBitLen / 8
result := make([]byte, 0, int64(len(inputIds))*numBytes)
for _, id := range inputIds {
index, ok := sequence[id]
if !ok {
log.Error("id not found in CalcDistance", zap.Int64("id", id))
return nil, errors.New("failed to fetch vectors by id: " + fmt.Sprintln(id))
}
result = append(result, binaryArr[int64(index)*numBytes:int64(index+1)*numBytes]...)
}
return &schemapb.VectorField{
Dim: retrievedVectors.GetDim(),
Data: &schemapb.VectorField_BinaryVector{
BinaryVector: result,
},
}, nil
}
return nil, errors.New("unsupported vector type")
}
func (t *calcDistanceTask) arrangeVectorsByStrID(inputIds []string, sequence map[string]int, retrievedVectors *schemapb.VectorField) (*schemapb.VectorField, error) {
if retrievedVectors.GetFloatVector() != nil {
floatArr := retrievedVectors.GetFloatVector().GetData()
element := retrievedVectors.GetDim()
result := make([]float32, 0, int64(len(inputIds))*element)
for _, id := range inputIds {
index, ok := sequence[id]
if !ok {
log.Error("id not found in CalcDistance", zap.String("id", id))
return nil, errors.New("failed to fetch vectors by id: " + fmt.Sprintln(id))
}
result = append(result, floatArr[int64(index)*element:int64(index+1)*element]...)
}
return &schemapb.VectorField{
Dim: element,
Data: &schemapb.VectorField_FloatVector{
FloatVector: &schemapb.FloatArray{
Data: result,
},
},
}, nil
}
if retrievedVectors.GetBinaryVector() != nil {
binaryArr := retrievedVectors.GetBinaryVector()
singleBitLen := distance.SingleBitLen(retrievedVectors.GetDim())
numBytes := singleBitLen / 8
result := make([]byte, 0, int64(len(inputIds))*numBytes)
for _, id := range inputIds {
index, ok := sequence[id]
if !ok {
log.Error("id not found in CalcDistance", zap.String("id", id))
return nil, errors.New("failed to fetch vectors by id: " + fmt.Sprintln(id))
}
result = append(result, binaryArr[int64(index)*numBytes:int64(index+1)*numBytes]...)
}
return &schemapb.VectorField{
Dim: retrievedVectors.GetDim(),
Data: &schemapb.VectorField_BinaryVector{
BinaryVector: result,
},
}, nil
}
return nil, errors.New("unsupported vector type")
}
func (t *calcDistanceTask) Execute(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
param, _ := funcutil.GetAttrByKeyFromRepeatedKV("metric", request.GetParams())
metric, err := distance.ValidateMetricType(param)
if err != nil {
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
// the vectors retrieved are random order, we need re-arrange the vectors by the order of input ids
arrangeFunc := func(ids *milvuspb.VectorIDs, retrievedFields []*schemapb.FieldData) (*schemapb.VectorField, error) {
var retrievedIds *schemapb.ScalarField
var retrievedVectors *schemapb.VectorField
isStringID := true
for _, fieldData := range retrievedFields {
if fieldData.FieldName == ids.FieldName {
retrievedVectors = fieldData.GetVectors()
}
if fieldData.Type == schemapb.DataType_Int64 ||
fieldData.Type == schemapb.DataType_VarChar ||
fieldData.Type == schemapb.DataType_String {
retrievedIds = fieldData.GetScalars()
if fieldData.Type == schemapb.DataType_Int64 {
isStringID = false
}
}
}
if retrievedIds == nil || retrievedVectors == nil {
return nil, errors.New("failed to fetch vectors")
}
if isStringID {
dict := make(map[string]int)
for index, id := range retrievedIds.GetStringData().GetData() {
dict[id] = index
}
inputIds := ids.IdArray.GetStrId().GetData()
return t.arrangeVectorsByStrID(inputIds, dict, retrievedVectors)
}
dict := make(map[int64]int)
for index, id := range retrievedIds.GetLongData().GetData() {
dict[id] = index
}
inputIds := ids.IdArray.GetIntId().GetData()
return t.arrangeVectorsByIntID(inputIds, dict, retrievedVectors)
}
log.Debug("CalcDistance received",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole),
zap.String("metric", metric))
vectorsLeft := request.GetOpLeft().GetDataArray()
opLeft := request.GetOpLeft().GetIdArray()
if opLeft != nil {
log.Debug("OpLeft IdArray not empty, Get vectors by id",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
result, err := t.queryFunc(opLeft)
if err != nil {
log.Debug("Failed to get left vectors by id",
zap.Error(err),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
log.Debug("OpLeft IdArray not empty, Get vectors by id done",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
vectorsLeft, err = arrangeFunc(opLeft, result.FieldsData)
if err != nil {
log.Debug("Failed to re-arrange left vectors",
zap.Error(err),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
log.Debug("Re-arrange left vectors done",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
}
if vectorsLeft == nil {
msg := "Left vectors array is empty"
log.Debug(msg,
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: msg,
},
}, nil
}
vectorsRight := request.GetOpRight().GetDataArray()
opRight := request.GetOpRight().GetIdArray()
if opRight != nil {
log.Debug("OpRight IdArray not empty, Get vectors by id",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
result, err := t.queryFunc(opRight)
if err != nil {
log.Debug("Failed to get right vectors by id",
zap.Error(err),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
log.Debug("OpRight IdArray not empty, Get vectors by id done",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
vectorsRight, err = arrangeFunc(opRight, result.FieldsData)
if err != nil {
log.Debug("Failed to re-arrange right vectors",
zap.Error(err),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
log.Debug("Re-arrange right vectors done",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
}
if vectorsRight == nil {
msg := "Right vectors array is empty"
log.Debug(msg,
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: msg,
},
}, nil
}
if vectorsLeft.GetDim() != vectorsRight.GetDim() {
msg := "Vectors dimension is not equal"
log.Debug(msg,
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: msg,
},
}, nil
}
if vectorsLeft.GetFloatVector() != nil && vectorsRight.GetFloatVector() != nil {
distances, err := distance.CalcFloatDistance(vectorsLeft.GetDim(), vectorsLeft.GetFloatVector().GetData(), vectorsRight.GetFloatVector().GetData(), metric)
if err != nil {
log.Debug("Failed to CalcFloatDistance",
zap.Error(err),
zap.Int64("leftDim", vectorsLeft.GetDim()),
zap.Int("leftLen", len(vectorsLeft.GetFloatVector().GetData())),
zap.Int64("rightDim", vectorsRight.GetDim()),
zap.Int("rightLen", len(vectorsRight.GetFloatVector().GetData())),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
log.Debug("CalcFloatDistance done",
zap.Error(err),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{ErrorCode: commonpb.ErrorCode_Success, Reason: ""},
Array: &milvuspb.CalcDistanceResults_FloatDist{
FloatDist: &schemapb.FloatArray{
Data: distances,
},
},
}, nil
}
if vectorsLeft.GetBinaryVector() != nil && vectorsRight.GetBinaryVector() != nil {
hamming, err := distance.CalcHammingDistance(vectorsLeft.GetDim(), vectorsLeft.GetBinaryVector(), vectorsRight.GetBinaryVector())
if err != nil {
log.Debug("Failed to CalcHammingDistance",
zap.Error(err),
zap.Int64("leftDim", vectorsLeft.GetDim()),
zap.Int("leftLen", len(vectorsLeft.GetBinaryVector())),
zap.Int64("rightDim", vectorsRight.GetDim()),
zap.Int("rightLen", len(vectorsRight.GetBinaryVector())),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
if metric == distance.HAMMING {
log.Debug("CalcHammingDistance done",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{ErrorCode: commonpb.ErrorCode_Success, Reason: ""},
Array: &milvuspb.CalcDistanceResults_IntDist{
IntDist: &schemapb.IntArray{
Data: hamming,
},
},
}, nil
}
if metric == distance.TANIMOTO {
tanimoto, err := distance.CalcTanimotoCoefficient(vectorsLeft.GetDim(), hamming)
if err != nil {
log.Debug("Failed to CalcTanimotoCoefficient",
zap.Error(err),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
}
log.Debug("CalcTanimotoCoefficient done",
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{ErrorCode: commonpb.ErrorCode_Success, Reason: ""},
Array: &milvuspb.CalcDistanceResults_FloatDist{
FloatDist: &schemapb.FloatArray{
Data: tanimoto,
},
},
}, nil
}
}
err = errors.New("unexpected error")
if (vectorsLeft.GetBinaryVector() != nil && vectorsRight.GetFloatVector() != nil) || (vectorsLeft.GetFloatVector() != nil && vectorsRight.GetBinaryVector() != nil) {
err = errors.New("cannot calculate distance between binary vectors and float vectors")
}
log.Debug("Failed to CalcDistance",
zap.Error(err),
zap.String("traceID", t.traceID),
zap.String("role", typeutil.ProxyRole))
return &milvuspb.CalcDistanceResults{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: err.Error(),
},
}, nil
} | internal/proxy/task_calc_distance.go | 0.602179 | 0.423518 | task_calc_distance.go | starcoder |
package store
import (
"fmt"
)
// Chunks tracks a sequence of persisted chunk files.
type Chunks struct {
PathPrefix, FileSuffix string
// ChunkSizeBytes is the size of each chunk file.
ChunkSizeBytes int
// Chunks is a sequence of append-only chunk files. An example
// usage is to hold the underlying key/val bytes for a
// hashmap. The 0'th chunk is a special, in-memory-only chunk
// without an actual backing file.
Chunks []*MMapRef
// LastChunkLen is the logical length of the last chunk, which is
// the chunk that is still being appended to when there are new,
// incoming data items.
LastChunkLen int
// Recycled is a stack of chunks that are ready to reuse.
Recycled []*MMapRef
}
// ---------------------------------------------
func (cs *Chunks) BytesTruncate(size uint64) error {
prevChunkLens := cs.PrevChunkLens()
if size > uint64(prevChunkLens+cs.ChunkSizeBytes) {
return nil
}
if uint64(prevChunkLens) <= size {
// The truncate is within the last chunk.
cs.LastChunkLen = int(size) - prevChunkLens
if len(cs.Chunks) == 1 {
// Special case the 0'th in-memory chunk.
cs.Chunks[0].Buf = cs.Chunks[0].Buf[:cs.LastChunkLen]
}
return nil
}
if size != 0 {
return fmt.Errorf("chunk: BytesTruncate unsupported size")
}
if len(cs.Chunks) > 0 {
// The truncate is to 0, so recycle all file-based chunks.
for i := len(cs.Chunks) - 1; i >= 1; i-- {
cs.Recycled = append(cs.Recycled, cs.Chunks[i])
cs.Chunks[i] = nil
}
cs.Chunks = cs.Chunks[:1] // Keep 0'th in-memory-only chunk.
// Special case the 0'th in-memory chunk.
cs.Chunks[0].Buf = cs.Chunks[0].Buf[:0]
}
cs.LastChunkLen = 0
return nil
}
// ---------------------------------------------
func (cs *Chunks) BytesAppend(b []byte) (
offsetOut, sizeOut uint64, err error) {
if len(b) > cs.ChunkSizeBytes {
return 0, 0, fmt.Errorf(
"chunk: BytesAppend len(b) > ChunkSizeBytes")
}
if len(b) <= 0 {
return 0, 0, nil
}
if len(cs.Chunks) <= 0 || cs.LastChunkLen+len(b) > cs.ChunkSizeBytes {
err = cs.AddChunk()
if err != nil {
return 0, 0, err
}
}
lastChunk := cs.Chunks[len(cs.Chunks)-1]
lastChunkLen := cs.LastChunkLen
cs.LastChunkLen = lastChunkLen + len(b)
// Special case in-memory only chunk which uses append().
if lastChunk.File == nil {
lastChunk.Buf = append(lastChunk.Buf, b...)
} else {
copy(lastChunk.Buf[lastChunkLen:cs.LastChunkLen], b)
}
return uint64(cs.PrevChunkLens() + lastChunkLen), uint64(len(b)), nil
}
// ---------------------------------------------
// BytesRead returns a slice of data from the chunks.
func (cs *Chunks) BytesRead(offset, size uint64) (
[]byte, error) {
if size > uint64(cs.ChunkSizeBytes) {
return nil, fmt.Errorf(
"chunk: BytesRead size > ChunkSizeBytes")
}
chunkIdx := int(offset / uint64(cs.ChunkSizeBytes))
if chunkIdx >= len(cs.Chunks) {
return nil, fmt.Errorf(
"chunk: BytesRead offset greater than chunks")
}
chunkOffset := offset % uint64(cs.ChunkSizeBytes)
return cs.Chunks[chunkIdx].Buf[chunkOffset : chunkOffset+size], nil
}
// ---------------------------------------------
// Close releases resources used by the chunk files.
func (cs *Chunks) Close() error {
for _, chunk := range cs.Chunks {
chunk.Close()
chunk.Remove()
}
cs.Chunks = nil
cs.LastChunkLen = 0
for _, chunk := range cs.Recycled {
chunk.Close()
chunk.Remove()
}
cs.Recycled = nil
return nil
}
// ---------------------------------------------
// AddChunk appends a new chunk file to the chunks, or reuses a
// previously recycled chunk file.
func (cs *Chunks) AddChunk() (err error) {
var chunk *MMapRef
if len(cs.Recycled) <= 0 {
var chunkPath string
var chunkSizeBytes int
if len(cs.Chunks) > 0 {
chunkPath = fmt.Sprintf("%s_chunk_%09d%s",
cs.PathPrefix, len(cs.Chunks), cs.FileSuffix)
chunkSizeBytes = cs.ChunkSizeBytes
}
chunk, err = CreateFileAsMMapRef(chunkPath, chunkSizeBytes)
if err != nil {
return err
}
} else {
chunk = cs.Recycled[len(cs.Recycled)-1]
cs.Recycled[len(cs.Recycled)-1] = nil
cs.Recycled = cs.Recycled[:len(cs.Recycled)-1]
}
cs.Chunks = append(cs.Chunks, chunk)
cs.LastChunkLen = 0
return nil
}
// ---------------------------------------------
// PrevChunkLens returns the sum of the chunk lengths for all but the
// last chunk.
func (cs *Chunks) PrevChunkLens() int {
if len(cs.Chunks) > 1 {
return (len(cs.Chunks) - 1) * cs.ChunkSizeBytes
}
return 0
} | store/chunk.go | 0.673943 | 0.438064 | chunk.go | starcoder |
package unityai
type NavMeshObstacleShape int32
const (
kObstacleShapeCapsule NavMeshObstacleShape = iota
kObstacleShapeBox
)
type NavMeshCarveShape struct {
shape NavMeshObstacleShape // NavMeshObstacleShape
center Vector3f
extents Vector3f
xAxis Vector3f
yAxis Vector3f
zAxis Vector3f
bounds MinMaxAABB
}
func (this *NavMeshCarveShape) GetBounds() MinMaxAABB {
return this.bounds
}
type CarveData struct {
m_SurfaceID int32
m_TileIndex int32
m_Position Vector3f
m_Rotation Quaternionf
m_Shapes []NavMeshCarveShape
}
type Shapes []NavMeshCarveShape
func (this Shapes) Len() int {
return len(this)
}
func (this Shapes) Less(i, j int) bool {
lhs := this[i]
rhs := this[j]
if lhs.center.x < rhs.center.x {
return true
}
if rhs.center.x < lhs.center.x {
return false
}
// rhs.x == lhs.x
if lhs.center.z < rhs.center.z {
return true
}
if rhs.center.z < lhs.center.z {
return false
}
// rhs.x == lhs.x && rhs.z == lhs.z
if lhs.center.y < rhs.center.y {
return true
}
if rhs.center.y < lhs.center.y {
return false
}
// all same - favour the biggest
return SqrMagnitude(lhs.extents) > SqrMagnitude(rhs.extents)
}
func (this Shapes) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}
func NewCarveData(surfaceID int32, tileIndex int32) *CarveData {
return &CarveData{
m_SurfaceID: surfaceID,
m_TileIndex: tileIndex,
}
}
func (this *CarveData) AddShape(shape NavMeshCarveShape) {
this.m_Shapes = append(this.m_Shapes, shape)
}
func (this *CarveData) Empty() bool {
return len(this.m_Shapes) == 0
}
type NavMeshObstacle struct {
m_VersionStamp int32
m_Shape NavMeshObstacleShape
m_Extents Vector3f
m_Scale Vector3f
m_Center Vector3f
m_Position Vector3f
m_Rotation Quaternionf
}
func NewNavMeshObstacle(shape NavMeshObstacleShape, position, scale Vector3f, rotation Quaternionf) *NavMeshObstacle {
obs := &NavMeshObstacle{
m_VersionStamp: 0,
m_Shape: shape,
m_Extents: NewVector3f(0.5, 0.5, 0.5),
m_Center: NewVector3f(0, 0, 0),
m_Scale: scale,
m_Rotation: rotation,
m_Position: position,
}
return obs
}
func (this *NavMeshObstacle) SetSize(size Vector3f) {
this.SetExtents(size.Mulf(0.5))
}
func (this *NavMeshObstacle) SetCenter(center Vector3f) {
this.m_Center = center
}
func (this *NavMeshObstacle) GetVersionStamp() int32 {
return this.m_VersionStamp
}
func (this *NavMeshObstacle) GetCarveShape(shape *NavMeshCarveShape) {
shape.shape = this.m_Shape
shape.extents = this.GetWorldExtents()
this.GetWorldCenterAndAxes(&shape.center, &shape.xAxis, &shape.yAxis, &shape.zAxis)
var worldExtents Vector3f
if this.m_Shape == kObstacleShapeCapsule {
CalcCapsuleWorldExtents(&worldExtents, shape.extents, shape.xAxis, shape.yAxis, shape.zAxis)
} else {
CalcBoxWorldExtents(&worldExtents, shape.extents, shape.xAxis, shape.yAxis, shape.zAxis)
}
shape.bounds = NewMinMaxAABB(shape.center.Sub(worldExtents), shape.center.Add(worldExtents))
}
func (this *NavMeshObstacle) GetWorldExtents() Vector3f {
var matrix Matrix4x4f
matrix.SetTRS(this.m_Position, this.m_Rotation, this.m_Scale)
absScale := matrix.GetLossyScale()
if this.m_Shape == kObstacleShapeCapsule {
scaledRadius := this.m_Extents.x * FloatMax(absScale.x, absScale.z)
scaledHeight := this.m_Extents.y * absScale.y
return NewVector3f(scaledRadius, scaledHeight, scaledRadius)
} else {
return ScaleVector3f(this.m_Extents, absScale)
}
}
func (this *NavMeshObstacle) GetWorldCenterAndAxes(center, xAxis, yAxis, zAxis *Vector3f) {
//const Transform& transform = GetComponent<Transform>();
//center = transform.TransformPoint(m_Center);
//Quaternionf rotation = transform.GetRotation();
var matrix Matrix4x4f
matrix.SetTRS(this.m_Position, this.m_Rotation, this.m_Scale)
*center = matrix.MultiplyPoint3(this.m_Center)
var rotationMatrix Matrix3x3f
QuaternionToMatrix3(this.m_Rotation, &rotationMatrix)
*xAxis = rotationMatrix.GetAxisX()
*yAxis = rotationMatrix.GetAxisY()
*zAxis = rotationMatrix.GetAxisZ()
}
func (this *NavMeshObstacle) SetExtents(mulf Vector3f) {
this.m_Extents = mulf
}
func EnsurePositive(value float32) float32 {
return FloatMax(0.00001, value)
}
func (this *NavMeshObstacle) SetHeight(value float32) {
positiveHeight := EnsurePositive(value)
newExtents := NewVector3f(this.m_Extents.x, positiveHeight*0.5, this.m_Extents.z)
this.SetExtents(newExtents)
}
func (this *NavMeshObstacle) SetRadius(value float32) {
positiveRadius := EnsurePositive(value)
newExtents := NewVector3f(positiveRadius, this.m_Extents.y, positiveRadius)
this.SetExtents(newExtents)
} | nav_mesh_carve_types.go | 0.841923 | 0.494995 | nav_mesh_carve_types.go | starcoder |
package docs
import "github.com/swaggo/swag"
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{escape .Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/": {
"delete": {
"description": "deletes an image by user ID and checksum",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Image"
],
"summary": "delete an image by user ID and checksum",
"parameters": [
{
"type": "string",
"description": "userID",
"name": "userID",
"in": "query",
"required": true
},
{
"type": "string",
"description": "checksum",
"name": "checksum",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/models.Image"
}
}
}
}
},
"/load": {
"post": {
"description": "create a image with specified parameter, image will be downloaded via source url",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Image"
],
"summary": "create a image from external system",
"parameters": [
{
"description": "body for upload a image",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/dtos.ImageRequest"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/models.Image"
}
}
}
}
},
"/query": {
"get": {
"description": "Upload a image with specified parameter",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Image"
],
"summary": "query image by external ID",
"parameters": [
{
"type": "string",
"description": "externalID",
"name": "externalID",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/models.Image"
}
}
}
}
},
"/upload": {
"post": {
"description": "Upload a image with specified parameter",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Image"
],
"summary": "upload a image",
"parameters": [
{
"description": "body for upload a image",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/dtos.ImageRequestWithinFile"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/models.Image"
}
}
}
}
}
},
"definitions": {
"dtos.ImageRequest": {
"type": "object",
"required": [
"algorithm",
"checksum",
"externalComponent",
"externalID",
"fileName",
"name",
"sourceUrl",
"userID"
],
"properties": {
"algorithm": {
"type": "string",
"enum": [
"md5",
"sha256"
]
},
"checksum": {
"type": "string"
},
"desc": {
"type": "string"
},
"externalComponent": {
"type": "string"
},
"externalID": {
"type": "string"
},
"fileName": {
"type": "string"
},
"name": {
"type": "string"
},
"publish": {
"type": "boolean"
},
"sourceUrl": {
"type": "string"
},
"userID": {
"type": "integer"
}
}
},
"dtos.ImageRequestWithinFile": {
"type": "object",
"required": [
"algorithm",
"externalComponent",
"externalID",
"fileName",
"name",
"userID"
],
"properties": {
"algorithm": {
"type": "string",
"enum": [
"md5",
"sha256"
]
},
"desc": {
"type": "string"
},
"externalComponent": {
"type": "string"
},
"externalID": {
"type": "string"
},
"fileName": {
"type": "string"
},
"name": {
"type": "string"
},
"publish": {
"type": "boolean"
},
"userID": {
"type": "integer"
}
}
},
"models.Image": {
"type": "object",
"properties": {
"algorithm": {
"type": "string"
},
"checksum": {
"type": "string"
},
"checksumPath": {
"type": "string"
},
"createTime": {
"type": "string"
},
"deleted": {
"type": "boolean"
},
"desc": {
"type": "string"
},
"externalComponent": {
"type": "string"
},
"externalID": {
"type": "string"
},
"fileName": {
"type": "string"
},
"id": {
"type": "integer"
},
"imagePath": {
"type": "string"
},
"name": {
"type": "string"
},
"publish": {
"type": "boolean"
},
"sourceUrl": {
"type": "string"
},
"status": {
"type": "string"
},
"statusDetail": {
"type": "string"
},
"updateTime": {
"type": "string"
},
"userId": {
"type": "integer"
}
}
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "",
Host: "",
BasePath: "",
Schemes: []string{},
Title: "",
Description: "",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
} | docs/docs.go | 0.545286 | 0.410166 | docs.go | starcoder |
// Package naming provides methods to parse and build compound names for variables types,
// functions, classes or other structures in source code.
package naming
import (
"strings"
"unicode"
)
const (
kebab = '-'
snake = '_'
space = ' '
blank = ""
)
// Fields splits the string s around each instance of one or more consecutive white space characters,
// underscore or hyphen. Its also break title words.
// It returns a slice of substrings of s or an empty slice if s contains only white space, underscore or hyphen.
func Fields(s string) []string {
if len(s) == 0 {
return nil
}
var (
buf = strings.Builder{}
cut = unicode.IsUpper
del = func(r rune) bool {
return r == kebab || r == snake || unicode.IsSpace(r) || unicode.IsPunct(r)
}
d, wd, c, wc bool
)
for _, r := range s {
d, c = del(r), cut(r)
if (c && !wc) || (d && !wd) {
_, _ = buf.WriteRune(space)
}
if !d {
_, _ = buf.WriteRune(r)
}
wd, wc = d, c
}
return strings.Fields(buf.String())
}
// CamelCase applies the Fields method on s and returns a string with all the words capitalized after the first one.
func CamelCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
if k > 0 {
return strings.Title(v)
}
return strings.ToLower(v)
}), blank)
}
// ConstantCase applies the Fields method on s and returns a string with all the words capitalized and
// joined with an underscore.
func ConstantCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
return strings.ToTitle(v)
}), string(snake))
}
// FlatCase applies the Fields method on s and concatenates any words to return only one in lowercase.
func FlatCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
return strings.ToLower(v)
}), blank)
}
// KebabCase applies the Fields method on s and returns a string with a hyphen between each word
// and all of them are lowercase.
func KebabCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
return strings.ToLower(v)
}), string(kebab))
}
// PascalCase applies the Fields method on s and returns a string with all the words capitalized.
func PascalCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
return strings.Title(v)
}), blank)
}
// SnakeCase applies the Fields method on s and returns a string with an underscore between each word
// and all of them are lowercase.
func SnakeCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
return strings.ToLower(v)
}), string(snake))
}
// TrainCase applies the Fields method on s and returns a string with all the words capitalized
// and separated with a hyphen.
func TrainCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
return strings.Title(v)
}), string(kebab))
}
// UpperFlatCase applies the Fields method on s and concatenates any words to return only one in uppercase.
func UpperFlatCase(s string) string {
return strings.Join(mapping(Fields(s), func(k int, v string) string {
return strings.ToTitle(v)
}), blank)
}
func mapping(a []string, f func(k int, v string) string) []string {
if len(a) == 0 {
return nil
}
for k, v := range a {
a[k] = f(k, v)
}
return a
} | naming.go | 0.744378 | 0.476458 | naming.go | starcoder |
package program
import (
"fmt"
"strings"
)
type stdFunction struct {
cFunc string
includeHeader string
functionBody string
dependPackages []string
dependFuncStd []string
}
func init() {
source := `
//---
// fmax returns the larger of its arguments: either x or y.
// c function : double fmax(double , double )
// dep pkg :
// dep func :
func fmax(x, y float64) float64 {
if x < y {
return y
}
return x
}
//---
// fmaxl returns the larger of its arguments: either x or y.
// c function : long double fmaxl(long double , long double )
// dep pkg :
// dep func :
func fmaxl(x, y float64) float64 {
if x < y {
return y
}
return x
}
//---
// cbrt compute cube root
// c function : float cbrtf(float)
// dep pkg : math
// dep func :
func cbrtf(x float32) float32 {
return float32(math.Cbrt(float64(x)))
}
//---
// BoolToInt converts boolean value to an int, which is a common operation in C.
// 0 and 1 represent false and true respectively.
// c function : int BoolToInt(int)
// dep pkg :
// dep func :
func BoolToInt(x bool) int32 {
if x {
return 1
}
return 0
}
//---
// fma returns x*y+z.
// c function : double fma(double, double, double)
// dep pkg :
// dep func :
func fma(x, y, z float64) float64 {
return x*y + z
}
//---
// fmal returns x*y+z.
// c function : long double fmal(long double, long double, long double)
// dep pkg :
// dep func :
func fmal(x, y, z float64) float64 {
return x*y + z
}
//---
// fmaf returns x*y+z.
// c function : float fmaf(float, float, float)
// dep pkg :
// dep func :
func fmaf(x, y, z float32) float32 {
return x*y + z
}
//---
// realloc is function from stdlib.h.
// c function : void * realloc(void* , size_t )
// dep pkg : reflect
// dep func : memcpy
func realloc(ptr interface{}, size uint32) interface{} {
if ptr == nil {
return make([]byte, size)
}
elemType := reflect.TypeOf(ptr).Elem()
ptrNew := reflect.MakeSlice(reflect.SliceOf(elemType), int(size), int(size)).Interface()
// copy elements
memcpy(ptrNew, ptr, size)
return ptrNew
}
//---
// memcpy is function from string.h.
// c function : void * memcpy( void * , const void * , size_t )
// dep pkg : reflect
// dep func :
func memcpy(dst, src interface{}, size uint32) interface{} {
switch reflect.TypeOf(src).Kind() {
case reflect.Slice:
s := reflect.ValueOf(src)
d := reflect.ValueOf(dst)
if s.Len() == 0 {
return dst
}
if s.Len() > 0 {
size /= uint32(int(s.Index(0).Type().Size()))
}
var val reflect.Value
for i := 0; i < int(size); i++ {
if i < s.Len() {
val = s.Index(i)
}
d.Index(i).Set(val)
}
}
return dst
}
//---
// __assert_fail from assert.h
// c function : bool __assert_fail(const char*, const char*, unsigned int, const char*)
// dep pkg : fmt os github.com/Konstantin8105/c4go/noarch
// dep func :
func __assert_fail(
expression, filePath []byte,
lineNumber uint32,
functionName []byte,
) bool {
fmt.Fprintf(
os.Stderr,
"a.out: %s:%d: %s: Assertion %s%s' failed.\n",
noarch.CStringToString(filePath),
lineNumber,
noarch.CStringToString(functionName),
string(byte(96)),
noarch.CStringToString(expression),
)
os.Exit(134)
return true
}
//---
// tolower from ctype.h
// c function : int tolower(int)
// dep pkg : unicode
// dep func :
func tolower (_c int32) int32 {
return int32(unicode.ToLower(rune(_c)))
}
//---
// toupper from ctype.h
// c function : int toupper(int)
// dep pkg : unicode
// dep func :
func toupper(_c int32) int32 {
return int32(unicode.ToUpper(rune(_c)))
}
//---
// __isnanf from math.h
// c function : int __isnanf(float)
// dep pkg : math
// dep func : BoolToInt
func __isnanf(x float32) int32 {
return BoolToInt(math.IsNaN(float64(x)))
}
//---
// __isinff from math.h
// c function : int __isinff(float)
// dep pkg : math
// dep func : BoolToInt
func __isinff(x float32) int32 {
return BoolToInt(math.IsInf(float64(x), 0))
}
//---
// __nanf from math.h
// c function : double __nanf(const char *)
// dep pkg : math
// dep func :
func __nanf(_ []byte) float64 {
return math.NaN()
}
//---
// __inff from math.h
// c function : float __inff()
// dep pkg : math
// dep func :
func __inff() float32 {
return float32(math.Inf(0))
}
//---
// __isinf from math.h
// c function : int __isinf(double)
// dep pkg : math
// dep func : BoolToInt
func __isinf(x float64) int32 {
return BoolToInt(math.IsInf(x, 0))
}
//---
// __isinfl from math.h
// c function : int __isinfl(long double)
// dep pkg : math
// dep func : BoolToInt
func __isinfl(x float64) int32 {
return BoolToInt(math.IsInf(x, 0))
}
//---
// __signbit from math.h
// c function : int __signbit(double)
// dep pkg : math
// dep func : BoolToInt
func __signbit(x float64) int32 {
return BoolToInt(math.Signbit(x))
}
//---
// __signbitd from math.h
// c function : int __signbitd(double)
// dep pkg : math
// dep func : BoolToInt
func __signbitd(x float64) int32 {
return BoolToInt(math.Signbit(x))
}
//---
// __signbitl from math.h
// c function : int __signbitl(long double)
// dep pkg : math
// dep func : BoolToInt
func __signbitl(x float64) int32 {
return BoolToInt(math.Signbit(x))
}
//---
// __signbitf ...
// c function : int __signbitf(float)
// dep pkg : math
// dep func : BoolToInt
func __signbitf(x float32) int32 {
return BoolToInt(math.Signbit(float64(x)))
}
//---
// __isnanl from math.h
// c function : int __isnanl(long double)
// dep pkg : math
// dep func : BoolToInt
func __isnanl(x float64) int32 {
return BoolToInt(math.IsNaN(x))
}
//---
// __isnan from math.h
// c function : int __isnan(double)
// dep pkg : math
// dep func : BoolToInt
func __isnan(x float64) int32 {
return BoolToInt(math.IsNaN(x))
}
//---
// sinhf from math.h
// c function : float sinhf(float)
// dep pkg : math
// dep func :
// sinhf compute hyperbolic sine
func sinhf(a float32) float32 {
return float32(math.Sinh(float64(a)))
}
//---
// coshf from math.h
// c function : float coshf(float)
// dep pkg : math
// dep func :
// coshf compute hyperbolic cose
func coshf(a float32) float32 {
return float32(math.Cosh(float64(a)))
}
//---
// tanhf from math.h
// c function : float tanhf(float)
// dep pkg : math
// dep func :
// tanhf compute hyperbolic tan
func tanhf(a float32) float32 {
return float32(math.Tanh(float64(a)))
}
//---
// hypotf from math.h
// c function : float hypotf(float)
// dep pkg : math
// dep func :
// hypotf compute the square root of the sum of the squares of x and y
func hypotf(x, y float32) float32 {
return float32(math.Hypot(float64(x), float64(y)))
}
//---
// copysignf from math.h
// c function : float copysignf(float, float)
// dep pkg : math
// dep func :
// copysignf copies sign of y to absolute value of x
func copysignf(x float32, y float32) float32 {
return float32(math.Copysign(float64(x), float64(y)))
}
//---
// expf from math.h
// c function : float expf(float )
// dep pkg : math
// dep func :
// expf : finds e^x
func expf(x float32) float32 {
return float32(math.Exp(float64(x)))
}
//---
// erff from math.h
// c function : float erff(float )
// dep pkg : math
// dep func :
// erff : finds error function value of x
func erff(x float32) float32 {
return float32(math.Erf(float64(x)))
}
//---
// erfcf from math.h
// c function : float erfcf(float )
// dep pkg : math
// dep func :
// erfcf : finds error function value of x
func erfcf(x float32) float32 {
return float32(math.Erfc(float64(x)))
}
//---
// lround from math.h
// c function : long int lround(double )
// dep pkg :
// dep func : lroundl
func lround(x float32) int32 {
return lroundl(float64(x))
}
//---
// lroundf from math.h
// c function : long int lroundf(float )
// dep pkg :
// dep func : lroundl
func lroundf(x float32) int32 {
return lroundl(float64(x))
}
//---
// lroundl from math.h
// c function : long int lroundl(long double )
// dep pkg : math
// dep func :
func lroundl(x float64) int32 {
return int32(math.Round(x))
}
//---
// fmin from math.h
// c function : double fmin(double , double )
// dep pkg :
// dep func :
// fmin returns the smaller of its arguments: either x or y.
func fmin(x, y float64) float64 {
if x < y {
return x
}
return y
}
//---
// fminl from math.h
// c function : double fminl(long double , long double )
// dep pkg :
// dep func :
// fmin returns the smaller of its arguments: either x or y.
func fminl(x, y float64) float64 {
if x < y {
return x
}
return y
}
//---
// fminf from math.h
// c function : float fminf(float , float )
// dep pkg :
// dep func :
// fminf returns the smaller of its arguments: either x or y.
func fminf(x, y float32) float32 {
if x < y {
return x
}
return y
}
//---
// fmaxf from math.h
// c function : float fmaxf(float , float )
// dep pkg :
// dep func :
// fmaxf returns the larger of its arguments: either x or y.
func fmaxf(x, y float32) float32 {
if x < y {
return y
}
return x
}
//---
// fdiml from math.h
// c function : long double fdiml(long double,long double)
// dep pkg :
// dep func :
// fdiml returns the positive difference between x and y.
func fdiml(x, y float64) float64 {
if x > y {
return x - y
}
return 0
}
//---
// fdim from math.h
// c function : double fdim(double, double)
// dep pkg :
// dep func :
// fdim returns the positive difference between x and y.
func fdim(x, y float64) float64 {
if x > y {
return x - y
}
return 0
}
//---
// fdimf from math.h
// c function : float fdimf(float, float)
// dep pkg :
// dep func :
// fdimf returns the positive difference between x and y.
func fdimf(x, y float32) float32 {
if x > y {
return x - y
}
return 0
}
//---
// log2f from math.h
// c function : float log2f(float)
// dep pkg : math
// dep func :
// log2f returns the binary (base-2) logarithm of x.
func log2f(x float32) float32 {
return float32(math.Log2(float64(x)))
}
//---
// log1pf from math.h
// c function : float log1pf(float)
// dep pkg : math
// dep func :
// log1pf compute ln(1+arg)
func log1pf(arg float32) float32 {
return float32(math.Log1p(float64(arg)))
}
//---
// llround from math.h
// c function : long long int llround(double )
// dep pkg :
// dep func : llroundl
func llround(x float32) int64 {
return llroundl(float64(x))
}
//---
// llroundf from math.h
// c function : long long int llroundf(float )
// dep pkg :
// dep func : llroundl
func llroundf(x float32) int64 {
return llroundl(float64(x))
}
//---
// llroundl from math.h
// c function : long long int llroundl(long double )
// dep pkg : math
// dep func :
func llroundl(x float64) int64 {
return int64(math.Round(x))
}
//---
// expm1f from math.h
// c function : float expm1f(float)
// dep pkg : math
// dep func :
// expm1f returns e raised to the power x minus one: e^x-1
func expm1f(x float32) float32 {
return float32(math.Expm1(float64(x)))
}
//---
// exp2f from math.h
// c function : float exp2f(float)
// dep pkg : math
// dep func :
// exp2f Returns the base-2 exponential function of x, which is 2 raised
// to the power x: 2^x
func exp2f(x float32) float32 {
return float32(math.Exp2(float64(x)))
}
//---
// __ctype_b_loc from ctype.h
// c function : const unsigned short int** __ctype_b_loc()
// dep pkg : unicode
// dep func :
func __ctype_b_loc() [][]uint16 {
var characterTable []uint16
for i := 0; i < 255; i++ {
var c uint16
// Each of the bitwise expressions below were copied from the enum
// values, like _ISupper, etc.
if unicode.IsUpper(rune(i)) {
c |= ((1 << (0)) << 8)
}
if unicode.IsLower(rune(i)) {
c |= ((1 << (1)) << 8)
}
if unicode.IsLetter(rune(i)) {
c |= ((1 << (2)) << 8)
}
if unicode.IsDigit(rune(i)) {
c |= ((1 << (3)) << 8)
}
if unicode.IsDigit(rune(i)) ||
(i >= 'a' && i <= 'f') ||
(i >= 'A' && i <= 'F') {
// IsXDigit. This is the same implementation as the Mac version.
// There may be a better way to do this.
c |= ((1 << (4)) << 8)
}
if unicode.IsSpace(rune(i)) {
c |= ((1 << (5)) << 8)
}
if unicode.IsPrint(rune(i)) {
c |= ((1 << (6)) << 8)
}
// The IsSpace check is required because Go treats spaces as graphic
// characters, which C does not.
if unicode.IsGraphic(rune(i)) && !unicode.IsSpace(rune(i)) {
c |= ((1 << (7)) << 8)
}
// http://www.cplusplus.com/reference/cctype/isblank/
// The standard "C" locale considers blank characters the tab
// character ('\t') and the space character (' ').
if i == int('\t') || i == int(' ') {
c |= ((1 << (8)) >> 8)
}
if unicode.IsControl(rune(i)) {
c |= ((1 << (9)) >> 8)
}
if unicode.IsPunct(rune(i)) {
c |= ((1 << (10)) >> 8)
}
if unicode.IsLetter(rune(i)) || unicode.IsDigit(rune(i)) {
c |= ((1 << (11)) >> 8)
}
// Yes, I know this is a hideously slow way to do it but I just want to
// test if this works right now.
characterTable = append(characterTable, c)
}
return [][]uint16{characterTable}
}
`
// split source by parts
var (
splitter = "//---"
cFunc = "c function :"
depPkg = "dep pkg :"
depFunc = "dep func :"
)
cs := strings.Split(source, splitter)
// Examples:
// __signbitf ...
// __inline_signbitf ...
// __builtin_signbitf ...
to := []string{"__inline_", "__builtin_"}
for i, size := 0, len(cs); i < size; i++ {
if !strings.Contains(cs[i], "__") {
continue
}
for j := range to {
part := strings.Replace(cs[i], "__", to[j], -1)
cs = append(cs, part)
}
}
for _, c := range cs {
if strings.TrimSpace(c) == "" {
continue
}
var s stdFunction
s.functionBody = c
lines := strings.Split(c, "\n")
var foundCfunc, foundDepPkg, foundDepFunc bool
for _, line := range lines {
if index := strings.Index(line, cFunc); index > 0 {
line = line[index+len(cFunc):]
s.cFunc = strings.TrimSpace(line)
if line == "" {
panic(fmt.Errorf("no function name : %v", lines))
}
foundCfunc = true
}
if index := strings.Index(line, depPkg); index > 0 {
line = line[index+len(depPkg):]
pkgs := strings.Split(line, " ")
for _, pkg := range pkgs {
if pkg == "" || strings.TrimSpace(pkg) == "" {
continue
}
s.dependPackages = append(s.dependPackages, pkg)
}
foundDepPkg = true
}
if index := strings.Index(line, depFunc); index > 0 {
line = line[index+len(depFunc):]
funcs := strings.Split(line, " ")
for _, f := range funcs {
if f == "" || strings.TrimSpace(f) == "" {
continue
}
s.dependFuncStd = append(s.dependFuncStd, f)
}
foundDepFunc = true
}
}
if !foundCfunc || !foundDepPkg || !foundDepFunc {
panic(c)
}
std = append(std, s)
}
}
var std []stdFunction | program/cstd.go | 0.511961 | 0.408513 | cstd.go | starcoder |
package minass
import (
"fmt"
"io"
"reflect"
"runtime"
"strings"
"time"
)
// assertion contains the basic properties common to value and functional
// assertions.
type assertion struct {
t testingT
invert bool
prefix string
}
// testingT describes the behavior we require from the default testing library.
type testingT interface {
Helper()
Errorf(format string, args ...interface{})
}
var runtimeCaller = runtime.Caller
// newAssertion initalizes the common proprties.
func newAssertion(t testingT) *assertion {
t.Helper()
_, caller, line, _ := runtimeCaller(2)
return &assertion{
prefix: fmt.Sprintf("[%s:%d]", caller, line),
t: t,
}
}
// func (a *assertion) errorf(format string, args ...interface{}) {
// a.t.Helper()
// a.t.Errorf(a.prefix+format, args...)
// }
// Invert sets the invert value to true.
func (a *assertion) Invert() *assertion {
a.invert = true
return a
}
// message creates a message with the given test details and parts of the
// initial assertion.
func (a *assertion) message(vals ...interface{}) *message {
var testmsg string
var testargs []interface{}
if len(vals) > 0 {
if msg, ok := vals[0].(string); ok {
testmsg = msg
} else {
panic("first parameter after expected value must be a string")
}
testargs = vals[1:]
}
return &message{
t: a.t,
testMessage: testmsg,
testArgs: testargs,
assertionPrefix: a.prefix,
}
}
// ValueAssertion stores the value and the common assertion for testing.
type ValueAssertion struct {
*assertion
val interface{}
}
// Assert creates a new assertion about the value v.
func Assert(t testingT, v interface{}) *ValueAssertion {
t.Helper()
return &ValueAssertion{
assertion: newAssertion(t),
val: v,
}
}
// Not inverts the assertion so that expected result is now the opposite.
func (a *ValueAssertion) Not() *ValueAssertion {
a.Invert()
return a
}
func reflectIsPointer(v interface{}) bool {
return reflect.ValueOf(v).Kind() == reflect.Ptr
}
func reflectIsNil(v interface{}) bool {
return reflect.ValueOf(v).IsNil()
}
func reflectElem(v interface{}) interface{} {
return reflect.ValueOf(v).Elem().Interface()
}
// Nil confirms the value is nil. A string or string format and parameters may
// be provided to print a message on failure.
func (a *ValueAssertion) Nil(msgs ...interface{}) (ret bool) {
a.t.Helper()
msg := a.message(msgs...)
if !reflectIsPointer(a.val) {
msg.errorf("value provided is not a pointer but is %T", a.val)
return false
}
isNil := reflectIsNil(a.val)
if !a.invert && !isNil {
msg.multiLineErrorf("expected nil; got:\n%+v", reflectElem(a.val))
return false
}
if a.invert && isNil {
msg.errorf("value is nil; expected not nil")
return false
}
return true
}
// True prints an error if the value is not a boolean or is false. A string or
// string format and parameters may be provided to print a message on failure.
func (a *ValueAssertion) True(msgs ...interface{}) (ret bool) {
msg := a.message(msgs...)
b, ok := a.val.(bool)
if !ok {
msg.errorf("value is not boolean; is %T", a.val)
return false
}
if !a.invert && !b {
msg.errorf("value is false; expected true")
return false
}
if a.invert && b {
msg.errorf("value is true; expected false")
return false
}
return true
}
// False prints an error if the value is not a boolean or is true. A string or
// string format and parameters may be provided to print a message on failure.
func (a *ValueAssertion) False(msgs ...interface{}) bool {
return a.Not().True(msgs...)
}
// Equal is a DSL method that calls Equals.
func (a *ValueAssertion) Equal(exp interface{}, msgs ...interface{}) bool {
return a.Equals(exp, msgs...)
}
// Equals compares the initial value to exp using reflect.DeepEqual. A string or
// string format and parameters may be provided to print a message on failure.
func (a *ValueAssertion) Equals(exp interface{}, msgs ...interface{}) (ret bool) {
a.t.Helper()
msg := a.message(msgs...)
eq := reflect.DeepEqual(a.val, exp)
if !a.invert && !eq {
msg.multiLineErrorf("%+v\n\n\tdoes not equal\n\n%+v", a.val, exp)
return false
}
if a.invert && eq {
msg.multiLineErrorf("both values are:\n%+v", exp)
return false
}
return true
}
// reflectContains performs the reflection part of checking if the value
// provided contains the expected value.
func reflectContains(container reflect.Value, exp interface{}) bool {
switch container.Kind() {
case reflect.Ptr:
containerValue := container.Elem()
if !containerValue.IsValid() {
return false
}
return reflectContains(containerValue, exp)
case reflect.Slice, reflect.Array:
for i := 0; i < container.Len(); i += 1 {
if exp == container.Index(i).Interface() {
return true
}
}
case reflect.Map:
rcon := reflect.ValueOf(container)
for _, key := range rcon.MapKeys() {
if exp == rcon.MapIndex(key).Interface() {
return true
}
}
}
return false
}
// Contains checks the string, slice, map, or array to ensure it contains the
// expected value, failing the test if it doesn't. A string or string format and
// parameters may be provided to print a message on failure.
func (a *ValueAssertion) Contains(exp interface{}, vals ...interface{}) (ret bool) {
a.t.Helper()
msg := a.message(vals...)
if reader, ok := a.val.(io.Reader); ok {
if data, err := io.ReadAll(reader); err == nil {
a.val = data
}
}
castString := func(v interface{}) (string, bool) {
if sval, ok := a.val.(string); ok {
return sval, true
} else if dval, ok := a.val.([]byte); ok {
return string(dval), true
}
return "", false
}
var contains bool
var stringCompared bool
container := a.val
if sexp, ok := exp.(string); ok {
if sval, ok := castString(a.val); ok {
stringCompared = true
container = sval
contains = strings.Contains(sval, sexp)
}
}
if !stringCompared {
contains = reflectContains(reflect.ValueOf(a.val), exp)
}
if !contains && !a.invert {
msg.multiLineErrorf("%+v\n\n\tdoes not contain\n\n%+v", container, exp)
return false
}
if contains && a.invert {
msg.multiLineErrorf("%+v\n\n\tdoes contain\n\n%+v", container, exp)
return false
}
return true
}
// Contain is an alias for Contains for better reading.
func (a *ValueAssertion) Contain(exp interface{}, vals ...interface{}) (ret bool) {
return a.Contains(exp, vals...)
}
// HasKey checks a map to ensure it has the key provided, failing the test if it
// doesn't. A string or string format and parameters may be provided to print a
// message on failure.
func (a *ValueAssertion) HasKey(key interface{}, vals ...interface{}) bool {
a.t.Helper()
msg := a.message(vals...)
hasKey, err := reflectHasKey(a.val, key)
if err != nil {
msg.errorf("hasKey error: %s", err.Error())
return a.Not().False()
}
if !hasKey && !a.invert {
msg.errorf("%+v\n\n\tdoes not have key\n\n%+v\n", a.val, key)
return false
}
if hasKey && a.invert {
msg.errorf("%+v\n\n\tdoes have key\n\n%+v", a.val, key)
return false
}
return true
}
// HaveKey is an alias for HasKey for better reading.
func (a *ValueAssertion) HaveKey(key interface{}, vals ...interface{}) bool {
return a.HasKey(key, vals...)
}
// reflectHasKey performs the reflection part of checking if the value
// provided contains the expected key.
func reflectHasKey(value, key interface{}) (bool, error) {
if value == nil {
return false, nil
}
containerType := reflect.TypeOf(value)
keyType := reflect.TypeOf(key)
if containerType.Kind() != reflect.Map {
return false, fmt.Errorf("value of type %T is not a map", value)
}
if containerType.Key() != keyType {
return false, fmt.Errorf("map is keyed by type %T; key provided is type %T", containerType.Key(), keyType)
}
containerValue := reflect.ValueOf(value)
keyValue := reflect.ValueOf(key)
if containerValue.MapIndex(keyValue) != (reflect.Value{}) {
return true, nil
}
return false, nil
}
// valueAssertion stores the value and the common assertion for testing.
type FunctionAssertion struct {
*assertion
fn func() bool
}
// AssertFn starts an assetion for function.
func AssertFn(t testingT, fn func()) *FunctionAssertion {
t.Helper()
wrap := func() bool {
fn()
return true
}
return &FunctionAssertion{
assertion: newAssertion(t),
fn: wrap,
}
}
// Not inverts the assertion so that expected result is now the opposite.
func (a *FunctionAssertion) Not() *FunctionAssertion {
a.Invert()
return a
}
// deferExpectedPanic deals with a panic happening or not happening after the
// asserted function runs.
func (a *FunctionAssertion) deferExpectedPanic(retbool *bool, msg *message) {
r := recover()
if r == nil && !a.invert {
msg.errorf("did not panic")
*retbool = false
}
if r != nil && a.invert {
msg.errorf("code paniced with err: %s", r)
*retbool = false
}
*retbool = true
}
// Panics is an alias for Panic for better reading.
func (a *FunctionAssertion) Panics(vals ...interface{}) (ret bool) {
return a.Panic(vals...)
}
// Panic executes the asserted function and reports an error if a panic does not
// occur.
func (a *FunctionAssertion) Panic(vals ...interface{}) (ret bool) {
msg := a.message(vals...)
defer a.deferExpectedPanic(&ret, msg)
return a.fn()
}
// Promise converts the function assertion to a promise.
func (a *FunctionAssertion) Promise() *promise {
done := make(chan bool)
go func() { done <- a.fn() }()
return &promise{assertion: a.assertion, done: done}
}
// A promise is an assertion that contains an chan waiting for the result of the
// execution.
type promise struct {
*assertion
done chan bool
}
// Not inverts the assertion so that expected result is now the opposite.
func (p *promise) Not() *promise {
p.Invert()
return p
}
// Wait pulls from the channel causing the asserted function to trigger. This
// will always succeed.
func (p *promise) Wait() bool {
return <-(chan bool)(p.done)
}
// Timeout waits for either the asserted function to finish or for the timer to
// trigger, and fails the test accordingly.
func (p promise) Timeout(d time.Duration, vals ...interface{}) (ret bool) {
msg := p.message(vals...)
select {
case ret = <-(chan bool)(p.done):
if p.assertion.invert {
msg.errorf("function didn't meet the minimum duration of %s", d)
ret = false
}
case <-time.After(d):
if !p.assertion.invert {
msg.errorf("function reached timeout of %s", d)
} else {
ret = true
}
}
return
}
// message contains the information to print the assertion message, including
// the test message format and args, the assertions format and args, and a
// prefix defined by the the initial assertion call.
type message struct {
t testingT
testMessage string
testArgs []interface{}
assertionPrefix string
assertionMessage string
assertionArgs []interface{}
assertionMultiline bool
}
// errorf prints the message to the testing log.
func (m *message) errorf(format string, args ...interface{}) {
m.assertionMessage = format
m.assertionArgs = args
m.t.Errorf(m.String())
}
// multiLineErrorf sets the message to multiline and prints the message to the
// testing log.
func (m *message) multiLineErrorf(format string, args ...interface{}) {
m.assertionMultiline = true
m.errorf(format, args...)
}
/*
String prints the message in one of these formats:
[file:line] assertion message
[file:line]
test message
assertion message
[file:line]
long
assertion
message
[file:line]
test message
long
assertion
message
*/
func (m message) String() string {
b := &strings.Builder{}
fmt.Fprint(b, m.assertionPrefix)
// If there is no message and the assertion is a single line, print short
// form.
if m.testMessage == "" && !m.assertionMultiline {
fmt.Fprint(b, " ")
fmt.Fprintf(b, m.assertionMessage, m.assertionArgs...)
return b.String()
}
if m.testMessage != "" {
fmt.Fprintln(b)
fmt.Fprintf(b, m.testMessage, m.testArgs...)
}
fmt.Fprintln(b)
fmt.Fprintf(b, m.assertionMessage, m.assertionArgs...)
return b.String()
} | minass.go | 0.653901 | 0.451992 | minass.go | starcoder |
package launchpad
import (
"errors"
"fmt"
"gitlab.com/gomidi/midi"
"strings"
)
// Launchpad represents a device with an input and output MIDI stream.
type Launchpad interface {
// ListenToHits listens the input stream for hits.
// It will return an error if listening initialisation failed.
ListenToHits() (<-chan Hit, error)
// ListenToScrollTextEndMarker listens the input stream for text end marker events.
// It will return an error if listening initialisation failed.
ListenToScrollTextEndMarker() (<-chan interface{}, error)
// Light lights the button at x,y with the given color.
// x and y are [0, 8] and color can be a ColorS or ColorMK2 / ColorMK2RGB (depends on connected launchpad)
// Note that x=8 corresponds to the round scene buttons on the right side of the device,
// and y=8 corresponds to the round buttons on the top of the device.
Light(x, y int, color Color) error
// Text will return a scrolling text builder whether you can build and
// perform an text with the given color (for Launchpad MK2 only ColorMK2 will work) which will be scrolled on the launchpad.
Text(color Color) ScrollingTextBuilder
// TextLoop will return a scrolling text builder whether you can build and
// perform an text with the given color (for Launchpad MK2 only ColorMK2 will work) which will be scrolled endless on the launchpad.
// If you want to stop an text loop you have to build and execute an empty textLoop!
TextLoop(color Color) ScrollingTextBuilder
// Clear turns off all the LEDs on the Launchpad.
Clear() error
// Close will close all underlying resources such like the streams and so on.
// It will return an error if any of the underlying resources will return an error
// on closing.
Close() error
// Out will return the underlying midi output stream.
Out() midi.Out
// In will return the underlying midi input stream.
In() midi.In
}
//Color can be ColorS for "Launchpad S"-Devices and ColorMK2 or ColorMK2RGB for "Launchpad MK2"-Devices
type Color interface {
AsBytes() []byte
}
type Hit struct {
X int
Y int
Down bool
}
// ScrollingTextBuilder is used to build and display an scrolling text on the Launchpad.
type ScrollingTextBuilder interface {
// Add adds a text snipped with a given speed to the builder.
// The speed can be a value from 1-7. The text must be ASCII
// characters! Otherwise the result could be weired.
Add(speed byte, text string) ScrollingTextBuilder
// Perform sends the pre-built scrolling text to the launchpad.
Perform() error
}
// NewLaunchpad will create a new Launchpad instance. It will discover for connected
// Launchpads. If there is no Launchpad found, an error will returned.
func NewLaunchpad(driver midi.Driver) (Launchpad, error) {
backend, err := discover(driver)
if err != nil {
return nil, err
}
return backend, nil
}
func discover(driver midi.Driver) (Launchpad, error) {
ins, err := driver.Ins()
if err != nil {
return nil, err
}
outs, err := driver.Outs()
if err != nil {
return nil, err
}
var in midi.In
var out midi.Out
for i, _ := range ins {
if strings.Contains(ins[i].String(), "Launchpad") {
in = ins[i]
break
}
}
for i, _ := range outs {
if strings.Contains(outs[i].String(), "Launchpad") {
out = outs[i]
break
}
}
if in == nil {
return nil, fmt.Errorf("no lanchpad input stream connected")
}
if out == nil {
return nil, fmt.Errorf("no lanchpad output stream connected")
}
if strings.Contains(in.String(), "Launchpad S") {
return &LaunchpadS{
inputStream: in,
outputStream: out,
}, nil
} else if strings.Contains(in.String(), "Launchpad MK2") {
// Switch to the session mode.
out.Write([]byte{0xf0, 0x00, 0x20, 0x29, 0x02, 0x18, 0x22, 0x00, 0xf7})
return &LaunchpadMK2{
inputStream: in,
outputStream: out,
}, nil
}
return nil, errors.New("unsupported launchpad type")
} | launchpad.go | 0.712932 | 0.434101 | launchpad.go | starcoder |
package ioman
import (
"container/ring"
"time"
)
const _boxcarRatio float64 = 0.1 //division of of sample rate
const _breathInFlowThreshold = 5
const _breathOutFlowThreshold = 0
type calcStore struct {
flowAverageTotal float64
flowAverageN uint64
}
type bufferStore struct {
flowMovingAverage float64
flowRing *ring.Ring //N size circular buffer of previous flow measurements
}
type stateStore struct {
state EnumState
stateChange time.Time
lastState EnumState //state n-1
lastStateChange time.Time
}
type controller struct {
state stateStore
buffer bufferStore
calc calcStore
sampledRate time.Duration
}
func newController(sampledRate time.Duration) *controller {
blen := int(1/sampledRate.Seconds()) * 1
logf("controller", "Creating a new buffer of len %v", blen)
fr := ring.New(blen)
for i := 0; i < fr.Len()+1; i++ {
fr.Value = float64(0)
fr = fr.Next()
}
return &controller{
buffer: bufferStore{
flowRing: fr,
},
sampledRate: sampledRate,
}
}
var counter int = 0
var ticks int = 0
func (c *controller) buffers(sensors Sensors) {
c.buffer.flowRing = c.buffer.flowRing.Next()
c.buffer.flowRing.Value = float64(sensors.Flow.Val)
//Calculate current trailing moving average
boxcar := int(1 / (c.sampledRate.Seconds()) * _boxcarRatio) //Calculate boxcar width as ratio _boxcarRatio of sample rate
sum := float64(0)
c.buffer.flowRing = c.buffer.flowRing.Move(-(boxcar)) //Index to [N - boxcar]
for s := 0; s < boxcar; s++ { //Advance from [N - boxcar] to N
val := c.buffer.flowRing.Value.(float64)
sum = sum + val
c.buffer.flowRing = c.buffer.flowRing.Next()
}
c.buffer.flowMovingAverage = sum / float64(boxcar)
}
func (c *controller) states(sensors Sensors) EnumState {
newstate := StateRest
if c.buffer.flowMovingAverage > _breathInFlowThreshold {
newstate = StateBreathingIn
}
if newstate != c.state.state {
c.state.lastStateChange = c.state.stateChange
c.state.stateChange = sensors.Flow.Timestamp
logf("controller", "state changed from %v to %v. ADC1-0 = %v", c.state.lastState, newstate, sensors.ADC.Vals[0])
}
c.state.lastState = c.state.state
c.state.state = newstate
return newstate
}
func (c *controller) calculate(sensors Sensors) Calculated {
calc := Calculated{}
// If moving into breathing state, reset counters
if c.state.state == StateBreathingIn && c.state.lastState != StateBreathingIn {
c.calc.flowAverageTotal = 0
c.calc.flowAverageN = 0
}
// If in breathing state, increment counters
if c.state.state == StateBreathingIn {
c.calc.flowAverageTotal += float64(sensors.Flow.Val)
c.calc.flowAverageN++
}
// If leaving breathing state, calculate integrated flow.
if c.state.state == StateRest && c.state.lastState == StateBreathingIn {
duration := c.state.stateChange.Sub(c.state.lastStateChange)
flow := (c.calc.flowAverageTotal / float64(c.calc.flowAverageN)) * duration.Minutes()
calc.FlowIntegrated = flow
calc.FlowIntegratedTimestamp = c.state.stateChange
logf("controller", "breath calculated as %v liters at %v ", calc.FlowIntegrated, calc.FlowIntegratedTimestamp)
}
return calc
} | ioman/controller.go | 0.748812 | 0.425187 | controller.go | starcoder |
package curve
import "github.com/oasisprotocol/curve25519-voi/curve/scalar"
func edwardsMultiscalarMulStraus(out *EdwardsPoint, scalars []*scalar.Scalar, points []*EdwardsPoint) *EdwardsPoint {
switch supportsVectorizedEdwards {
case true:
return edwardsMultiscalarMulStrausVector(out, scalars, points)
default:
return edwardsMultiscalarMulStrausGeneric(out, scalars, points)
}
}
func edwardsMultiscalarMulStrausVartime(out *EdwardsPoint, scalars []*scalar.Scalar, points []*EdwardsPoint) *EdwardsPoint {
switch supportsVectorizedEdwards {
case true:
return edwardsMultiscalarMulStrausVartimeVector(out, scalars, points)
default:
return edwardsMultiscalarMulStrausVartimeGeneric(out, scalars, points)
}
}
func expandedEdwardsMultiscalarMulStrausVartime(out *EdwardsPoint, staticScalars []*scalar.Scalar, staticPoints []*ExpandedEdwardsPoint, dynamicScalars []*scalar.Scalar, dynamicPoints []*EdwardsPoint) *EdwardsPoint {
switch supportsVectorizedEdwards {
case true:
return expandedEdwardsMultiscalarMulStrausVartimeVector(out, staticScalars, staticPoints, dynamicScalars, dynamicPoints)
default:
return expandedEdwardsMultiscalarMulStrausVartimeGeneric(out, staticScalars, staticPoints, dynamicScalars, dynamicPoints)
}
}
func edwardsMultiscalarMulStrausGeneric(out *EdwardsPoint, scalars []*scalar.Scalar, points []*EdwardsPoint) *EdwardsPoint {
lookupTables := make([]projectiveNielsPointLookupTable, 0, len(points))
for _, point := range points {
lookupTables = append(lookupTables, newProjectiveNielsPointLookupTable(point))
}
// TODO: In theory this should be sanitized.
scalarDigitsVec := make([][64]int8, 0, len(scalars))
for _, scalar := range scalars {
scalarDigitsVec = append(scalarDigitsVec, scalar.ToRadix16())
}
out.Identity()
var sum completedPoint
for i := 63; i >= 0; i-- {
out.mulByPow2(out, 4)
for j := 0; j < len(points); j++ {
// R_i = s_{i,j} * P_i
R_i := lookupTables[j].Lookup(scalarDigitsVec[j][i])
// Q = Q + R_i
out.setCompleted(sum.AddEdwardsProjectiveNiels(out, &R_i))
}
}
return out
}
func edwardsMultiscalarMulStrausVartimeGeneric(out *EdwardsPoint, scalars []*scalar.Scalar, points []*EdwardsPoint) *EdwardsPoint {
lookupTables := make([]projectiveNielsPointNafLookupTable, 0, len(points))
for _, point := range points {
lookupTables = append(lookupTables, newProjectiveNielsPointNafLookupTable(point))
}
nafs := make([][256]int8, 0, len(scalars))
for _, scalar := range scalars {
nafs = append(nafs, scalar.NonAdjacentForm(5))
}
var r projectivePoint
r.Identity()
var (
tEp EdwardsPoint
t completedPoint
)
for i := 255; i >= 0; i-- {
t.Double(&r)
for j := 0; j < len(nafs); j++ {
naf_i := nafs[j][i]
if naf_i > 0 {
t.AddEdwardsProjectiveNiels(tEp.setCompleted(&t), lookupTables[j].Lookup(uint8(naf_i)))
} else if naf_i < 0 {
t.SubEdwardsProjectiveNiels(tEp.setCompleted(&t), lookupTables[j].Lookup(uint8(-naf_i)))
}
}
r.SetCompleted(&t)
}
return out.setProjective(&r)
}
func expandedEdwardsMultiscalarMulStrausVartimeGeneric(out *EdwardsPoint, staticScalars []*scalar.Scalar, staticPoints []*ExpandedEdwardsPoint, dynamicScalars []*scalar.Scalar, dynamicPoints []*EdwardsPoint) *EdwardsPoint {
staticLen, dynamicLen := len(staticScalars), len(dynamicScalars)
var (
staticTables []*projectiveNielsPointNafLookupTable
dynamicTables []projectiveNielsPointNafLookupTable
staticNafs, dynamicNafs [][256]int8
)
if staticLen > 0 {
staticTables = make([]*projectiveNielsPointNafLookupTable, 0, staticLen)
for _, point := range staticPoints {
staticTables = append(staticTables, point.inner)
}
staticNafs = make([][256]int8, 0, staticLen)
for _, scalar := range staticScalars {
staticNafs = append(staticNafs, scalar.NonAdjacentForm(5))
}
}
if dynamicLen > 0 {
dynamicTables = make([]projectiveNielsPointNafLookupTable, 0, dynamicLen)
for _, point := range dynamicPoints {
dynamicTables = append(dynamicTables, newProjectiveNielsPointNafLookupTable(point))
}
dynamicNafs = make([][256]int8, 0, dynamicLen)
for _, scalar := range dynamicScalars {
dynamicNafs = append(dynamicNafs, scalar.NonAdjacentForm(5))
}
}
var r projectivePoint
r.Identity()
var (
tEp EdwardsPoint
t completedPoint
)
for i := 255; i >= 0; i-- {
t.Double(&r)
for j := 0; j < staticLen; j++ {
naf_i := staticNafs[j][i]
if naf_i > 0 {
t.AddEdwardsProjectiveNiels(tEp.setCompleted(&t), staticTables[j].Lookup(uint8(naf_i)))
} else if naf_i < 0 {
t.SubEdwardsProjectiveNiels(tEp.setCompleted(&t), staticTables[j].Lookup(uint8(-naf_i)))
}
}
for j := 0; j < dynamicLen; j++ {
naf_i := dynamicNafs[j][i]
if naf_i > 0 {
t.AddEdwardsProjectiveNiels(tEp.setCompleted(&t), dynamicTables[j].Lookup(uint8(naf_i)))
} else if naf_i < 0 {
t.SubEdwardsProjectiveNiels(tEp.setCompleted(&t), dynamicTables[j].Lookup(uint8(-naf_i)))
}
}
r.SetCompleted(&t)
}
return out.setProjective(&r)
}
func edwardsMultiscalarMulStrausVector(out *EdwardsPoint, scalars []*scalar.Scalar, points []*EdwardsPoint) *EdwardsPoint {
lookupTables := make([]cachedPointLookupTable, 0, len(points))
for _, point := range points {
lookupTables = append(lookupTables, newCachedPointLookupTable(point))
}
// TODO: In theory this should be sanitized.
scalarDigitsVec := make([][64]int8, 0, len(scalars))
for _, scalar := range scalars {
scalarDigitsVec = append(scalarDigitsVec, scalar.ToRadix16())
}
var q extendedPoint
q.Identity()
for i := 63; i >= 0; i-- {
q.MulByPow2(&q, 4)
for j := 0; j < len(points); j++ {
// R_i = s_{i,j} * P_i
R_i := lookupTables[j].Lookup(scalarDigitsVec[j][i])
// Q = Q + R_i
q.AddExtendedCached(&q, &R_i)
}
}
return out.setExtended(&q)
}
func edwardsMultiscalarMulStrausVartimeVector(out *EdwardsPoint, scalars []*scalar.Scalar, points []*EdwardsPoint) *EdwardsPoint {
lookupTables := make([]cachedPointNafLookupTable, 0, len(points))
for _, point := range points {
lookupTables = append(lookupTables, newCachedPointNafLookupTable(point))
}
nafs := make([][256]int8, 0, len(scalars))
for _, scalar := range scalars {
nafs = append(nafs, scalar.NonAdjacentForm(5))
}
var q extendedPoint
q.Identity()
for i := 255; i >= 0; i-- {
q.Double(&q)
for j := 0; j < len(scalars); j++ {
naf_i := nafs[j][i]
if naf_i > 0 {
q.AddExtendedCached(&q, lookupTables[j].Lookup(uint8(naf_i)))
} else if naf_i < 0 {
q.SubExtendedCached(&q, lookupTables[j].Lookup(uint8(-naf_i)))
}
}
}
return out.setExtended(&q)
}
func expandedEdwardsMultiscalarMulStrausVartimeVector(out *EdwardsPoint, staticScalars []*scalar.Scalar, staticPoints []*ExpandedEdwardsPoint, dynamicScalars []*scalar.Scalar, dynamicPoints []*EdwardsPoint) *EdwardsPoint {
staticLen, dynamicLen := len(staticScalars), len(dynamicScalars)
var (
staticTables []*cachedPointNafLookupTable
dynamicTables []cachedPointNafLookupTable
staticNafs, dynamicNafs [][256]int8
)
if staticLen > 0 {
staticTables = make([]*cachedPointNafLookupTable, 0, staticLen)
for _, point := range staticPoints {
staticTables = append(staticTables, point.innerVector)
}
staticNafs = make([][256]int8, 0, staticLen)
for _, scalar := range staticScalars {
staticNafs = append(staticNafs, scalar.NonAdjacentForm(5))
}
}
if dynamicLen > 0 {
dynamicTables = make([]cachedPointNafLookupTable, 0, dynamicLen)
for _, point := range dynamicPoints {
dynamicTables = append(dynamicTables, newCachedPointNafLookupTable(point))
}
dynamicNafs = make([][256]int8, 0, dynamicLen)
for _, scalar := range dynamicScalars {
dynamicNafs = append(dynamicNafs, scalar.NonAdjacentForm(5))
}
}
var q extendedPoint
q.Identity()
for i := 255; i >= 0; i-- {
q.Double(&q)
for j := 0; j < staticLen; j++ {
naf_i := staticNafs[j][i]
if naf_i > 0 {
q.AddExtendedCached(&q, staticTables[j].Lookup(uint8(naf_i)))
} else if naf_i < 0 {
q.SubExtendedCached(&q, staticTables[j].Lookup(uint8(-naf_i)))
}
}
for j := 0; j < dynamicLen; j++ {
naf_i := dynamicNafs[j][i]
if naf_i > 0 {
q.AddExtendedCached(&q, dynamicTables[j].Lookup(uint8(naf_i)))
} else if naf_i < 0 {
q.SubExtendedCached(&q, dynamicTables[j].Lookup(uint8(-naf_i)))
}
}
}
return out.setExtended(&q)
} | curve/scalar_mul_straus.go | 0.583203 | 0.489503 | scalar_mul_straus.go | starcoder |
package game
import (
"fmt"
"time"
)
// Point represents a coordinate on the grid of the game
type Point struct {
X, Y int
}
type cell bool
func (c cell) String() string {
if c {
return "[0]"
}
return "[ ]"
}
// Game holds the game's logic and the grid of cells where the game takes place
type Game struct {
grid [][]cell // 2D slice of cells, true means alive and false means dead
rows, columns int
stop bool
}
// Seed set the living cells on the grid according to points
func (g *Game) Seed(points []Point) {
for _, p := range points {
if g.validPoint(p) {
g.grid[p.X][p.Y] = true
}
}
}
func (g *Game) validPoint(p Point) bool {
return p.X >= 0 && p.X < g.rows && p.Y >= 0 && p.Y < g.columns
}
// neighbours returns the count of alive and dead neighbours from the specified point
func (g *Game) neighbours(p Point) (alive int) {
deltas := []Point{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}
for _, d := range deltas {
x, y := p.X+d.X, p.Y+d.Y
if g.validPoint(Point{x, y}) { // Only count for valid indexes
if g.grid[x][y] {
alive++
}
}
}
return
}
// tick applies the rules of the game simultaneously for every cell on the grid and creates a new
// grid holding the next generation of cells.
func (g *Game) tick() {
nextGrid := newGrid(g.rows, g.columns)
for i := 0; i < g.rows; i++ {
for j := 0; j < g.columns; j++ {
c := bool(g.grid[i][j])
alive := g.neighbours(Point{i, j})
// Applying rules
if c && alive < 2 { // 1. Any live cell with fewer than two live neighbours dies
nextGrid[i][j] = cell(false)
} else if c && (alive == 2 || alive == 3) { // 2. Any live cell with two or three live neighbours lives on the next generation
nextGrid[i][j] = cell(true)
} else if c && alive > 3 { // 3. Any live cell with more than three live neighbours dies
nextGrid[i][j] = cell(false)
} else if !c && alive == 3 { // 4. Any dead cell with exactly three live neighbours become a live cell
nextGrid[i][j] = cell(true)
}
}
}
g.grid = nextGrid // Next generation
}
func (g *Game) String() string {
var s string
for _, row := range g.grid {
for _, cell := range row {
s += fmt.Sprintf("%1s", cell)
}
s += fmt.Sprint("\n")
}
s += fmt.Sprint("\n")
return s
}
// Start the game ticking sleeping 500 miliseconds between each tick
func (g *Game) Start() {
go func() {
for !g.stop {
fmt.Print(g)
g.tick()
time.Sleep(500 * time.Millisecond)
}
}()
}
// Stop stops the game ticking
func (g *Game) Stop() {
g.stop = true
}
// newGrid creates a new slice of cells of the specified size
func newGrid(rows, columns int) [][]cell {
grid := make([][]cell, rows)
for i := range grid {
grid[i] = make([]cell, columns)
}
return grid
}
// NewGame creates and returns a new Game struct pointer with a grid of the specified size
func NewGame(rows, columns int) *Game {
g := &Game{newGrid(rows, columns), rows, columns, false}
return g
} | game/game.go | 0.817137 | 0.641689 | game.go | starcoder |
package graph
import (
"sort"
)
type Vertex int
// Edge describes the edge of a weighted graph
type Edge struct {
Start Vertex
End Vertex
Weight int
}
// DisjointSetUnionElement describes what an element of DSU looks like
type DisjointSetUnionElement struct {
Parent Vertex
Rank int
}
// DisjointSetUnion is a data structure that treats its elements as separate sets
// and provides fast operations for set creation, merging sets, and finding the parent
// of the given element of a set.
type DisjointSetUnion []DisjointSetUnionElement
// NewDSU will return an initialised DSU using the value of n
// which will be treated as the number of elements out of which
// the DSU is being made
func NewDSU(n int) *DisjointSetUnion {
dsu := DisjointSetUnion(make([]DisjointSetUnionElement, n))
return &dsu
}
// MakeSet will create a set in the DSU for the given node
func (dsu DisjointSetUnion) MakeSet(node Vertex) {
dsu[node].Parent = node
dsu[node].Rank = 0
}
// FindSetRepresentative will return the parent element of the set the given node
// belongs to. Since every single element in the path from node to parent
// has the same parent, we store the parent value for each element in the
// path. This reduces consequent function calls and helps in going from O(n)
// to O(log n). This is known as path compression technique.
func (dsu DisjointSetUnion) FindSetRepresentative(node Vertex) Vertex {
if node == dsu[node].Parent {
return node
}
dsu[node].Parent = dsu.FindSetRepresentative(dsu[node].Parent)
return dsu[node].Parent
}
// unionSets will merge two given sets. The naive implementation of this
// always combines the secondNode's tree with the firstNode's tree. This can lead
// to creation of trees of length O(n) so we optimize by attaching the node with
// smaller rank to the node with bigger rank. Rank represents the upper bound depth of the tree.
func (dsu DisjointSetUnion) UnionSets(firstNode Vertex, secondNode Vertex) {
firstNode = dsu.FindSetRepresentative(firstNode)
secondNode = dsu.FindSetRepresentative(secondNode)
if firstNode != secondNode {
if dsu[firstNode].Rank < dsu[secondNode].Rank {
firstNode, secondNode = secondNode, firstNode
}
dsu[secondNode].Parent = firstNode
if dsu[firstNode].Rank == dsu[secondNode].Rank {
dsu[firstNode].Rank++
}
}
}
// KruskalMST will return a minimum spanning tree along with its total cost
// to using Kruskal's algorithm. Time complexity is O(m * log (n)) where m is
// the number of edges in the graph and n is number of nodes in it.
func KruskalMST(n int, edges []Edge) ([]Edge, int) {
var mst []Edge // The resultant minimum spanning tree
var cost int = 0
dsu := NewDSU(n)
for i := 0; i < n; i++ {
dsu.MakeSet(Vertex(i))
}
sort.SliceStable(edges, func(i, j int) bool {
return edges[i].Weight < edges[j].Weight
})
for _, edge := range edges {
if dsu.FindSetRepresentative(edge.Start) != dsu.FindSetRepresentative(edge.End) {
mst = append(mst, edge)
cost += edge.Weight
dsu.UnionSets(edge.Start, edge.End)
}
}
return mst, cost
} | graph/kruskal.go | 0.830903 | 0.643777 | kruskal.go | starcoder |
Package geo is a library package that provide utilities to process calculations on geographical points, hashes & boundaries.
Brief
The package has a few features that might be handy, including:
- Geo-point latlng normalization.
- Geo-point 8 decimal places precision handling.
- Measuring the distance between two given geo-points.
- Calculating the geo-hash of a given geo-point with a defined precision.
- Calculating the geo-point representing a given geo-hash.
- Calculating the needed geo-hash precision given the radius in kilometers.
- Calculating the neighbour geo-hashes of the given geo-hash.
- Creating normalized boundary boxes given two geo-points.
Usage
$ go get -u github.com/adzr/geo
Then, import the package:
import (
"github.com/adzr/geo"
)
Examples
Creating a normalized geo-point:
// lat = 130
// lng = 200
// This code will output (90, 0)
// because there is no lat above 90
// and lng is always 0 when lat is 90.
fmt.Printf("%v\n", geo.NewPoint(130, 200))
Geo-point precision is rounded to 8 places on 0.5:
// lat = -45.1234567851
// lng = -35.8765432138
// This code will output (-45.12345679, -35.87654321)
fmt.Printf("%v\n", geo.NewPoint(-45.1234567851, -35.8765432138))
Distance measurement is done using Haversine formula (https://en.wikipedia.org/wiki/Haversine_formula):
// latlng1 => (50.432356, 83.873793)
// latlng2 => (58.124521, 63.735753)
// This code will output the distance in kilometers which is around 1553.
fmt.Printf("%v\n", geo.GetDistance(geo.NewPoint(50.432356, 83.873793), geo.NewPoint(58.124521, 63.735753))
Now let's say we want to get the geo-hash of a given geo-point within 1km precision:
// latlng => (50.432356, 83.873793)
// This code will output "vbgw" which is the hash bits encoded into a base32 string.
fmt.Printf("%v\n", geo.GetHash(geo.NewPoint(50.432356, 83.873793), geo.GetNeededPrecision(1)))
Probably, it's easy now to go playing around with the rest of the API, I hope the apidocs explain it well.
*/
package geo | doc.go | 0.9339 | 0.827131 | doc.go | starcoder |
package merge
import "reflect"
func Interface(data ...interface{}) reflect.Value {
if len(data) == 0 {
return reflect.Value{}
}
firstRecordV, ok := data[0].(reflect.Value)
if !ok {
firstRecordV = reflect.ValueOf(data[0])
}
if firstRecordV.Type().Kind() == reflect.Ptr {
firstRecordV = firstRecordV.Elem()
}
result := reflect.MakeSlice(firstRecordV.Type(), 0, 0)
for _, datum := range data {
v, ok := datum.(reflect.Value)
if !ok {
v = reflect.ValueOf(datum)
}
if v.Type().Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Type().Kind() != reflect.Slice {
continue
}
for i := 0; i < v.Len(); i++ {
result = reflect.Append(result, v.Index(i))
}
}
return result
}
func String(data ...[]string) []string {
result := Interface(data)
return result.Interface().([]string)
}
func Int(data ...[]int) []int {
result := Interface(data)
return result.Interface().([]int)
}
func Int8(data ...[]int8) []int8 {
result := Interface(data)
return result.Interface().([]int8)
}
func Int16(data ...[]int16) []int16 {
result := Interface(data)
return result.Interface().([]int16)
}
func Int32(data ...[]int32) []int32 {
result := Interface(data)
return result.Interface().([]int32)
}
func Int64(data ...[]int64) []int64 {
result := Interface(data)
return result.Interface().([]int64)
}
func Uint(data ...[]uint) []uint {
result := Interface(data)
return result.Interface().([]uint)
}
func Uint8(data ...[]uint8) []uint8 {
result := Interface(data)
return result.Interface().([]uint8)
}
func Uint16(data ...[]uint16) []uint16 {
result := Interface(data)
return result.Interface().([]uint16)
}
func Uint32(data ...[]uint32) []uint32 {
result := Interface(data)
return result.Interface().([]uint32)
}
func Uint64(data ...[]uint64) []uint64 {
result := Interface(data)
return result.Interface().([]uint64)
}
func Float32(data ...[]float32) []float32 {
result := Interface(data)
return result.Interface().([]float32)
}
func Float64(data ...[]float64) []float64 {
result := Interface(data)
return result.Interface().([]float64)
} | helper/merge/merge.go | 0.513181 | 0.403626 | merge.go | starcoder |
package gap
import (
"fmt"
"runtime"
"time"
"github.com/stiganik/gap/combination"
"github.com/stiganik/gap/selection"
"github.com/stiganik/gap/solution"
// Statically import all selection and combination algorithms to make
// them register themselves at runtime.
_ "github.com/stiganik/gap/combination/all"
_ "github.com/stiganik/gap/selection/all"
)
var (
defaultPoolSize = uint(1000)
defaultElitism = uint(3)
defaultSelectionAlg = selection.SCX
defaultCombinationAlg = []combination.Algorithm{
combination.CROSSOVER_SINGLE_POINT,
}
defaultThreadCount = uint(runtime.NumCPU())
)
// FitnessFn defines a fitness function which takes in a solution in the form of
// a byte array calculates the fitness of the the solution and expresses it as a
// unsigned integer value from less to more fit, zero being totally unsuitable.
type FitnessFn func(s []byte) uint
// Algorithm defines a problem and the genetic algorithm used to solve the
// problem.
type Algorithm struct {
// The fitness function used to evaluate solutions.
FFn FitnessFn
// SolutionBitSize is the bit size of the solution slice.
SolutionBitSize uint
// SolutionPoolSize is the amount of solutions generated in each
// iteration of the alogirthm. The default value is 1000.
SolutionPoolSize uint
// Elitism is the percentage of values that pass on to the next generation
// without the selection and combination process. The value will be clipped
// between 0 and 100. If the value is nil the default value is used. The
// default value is 3.
Elitism *uint
// SelectionAlgorithm is the algorithm used to select solutions from the
// solution pool for crossover. The default value is selection.SCX.
SelectionAlgorithm selection.Algorithm
// CombinationAlgorithms is a slice of algortihms used to combine the
// selected solutions into the solution candidates. The combination
// algorithms are applied sequentially. the default value is
// []combination.Algorithm{combination.CROSSOVER_SINGLE_POINT}
CombinationAlgorithms []combination.Algorithm
// ThreadCount sets the amount of threads used by the genetic algorithm.
// By default it is set to the number of physical cores the processor
// has.
// Note: Currently not in use.
ThreadCount uint
}
func (a *Algorithm) check() error {
if a.FFn == nil {
return fmt.Errorf("Fitness function missing")
}
if a.SolutionBitSize == 0 {
return fmt.Errorf("Solution size 0")
}
if a.SolutionPoolSize == 0 {
a.SolutionPoolSize = defaultPoolSize
}
if a.Elitism == nil {
a.Elitism = &defaultElitism
} else {
if *a.Elitism > 100 {
*a.Elitism = 100
}
}
if a.SelectionAlgorithm == "" {
a.SelectionAlgorithm = defaultSelectionAlg
}
if len(a.CombinationAlgorithms) == 0 {
a.CombinationAlgorithms = defaultCombinationAlg
}
if a.ThreadCount == 0 {
a.ThreadCount = defaultThreadCount
}
return nil
}
// Result contains the result of a genetic algorithm and also additional
// information about the running of the algorithm.
type Result struct {
ElapsedTime time.Duration
Generation uint
Solution solution.Specimen
}
// New creates a new default genetic algorithm for solving the problem described
// by the fitness function fn. More customization can be achieved by editing the
// exported fields of the Algorithm object. sbl is the Solution Bit Length value
// which determines how many bits the solution must include.
func New(fn FitnessFn, sbl uint) *Algorithm {
return &Algorithm{
FFn: fn,
SolutionBitSize: sbl,
}
}
// Run runs the genetic algorithm and retrieves the correctest answer once the
// goal of the algorithm is reached.
func (a *Algorithm) Run(g Goal) (ret Result, err error) {
if err = a.check(); err != nil {
return
}
if err = g.init(); err != nil {
return
}
defer g.finalize()
poolA := solution.NewPool(a.SolutionPoolSize, a.SolutionBitSize)
poolB := solution.NewPool(a.SolutionPoolSize, a.SolutionBitSize)
if err = poolA.Seed(); err != nil {
return
}
sel, err := selection.New(a.SelectionAlgorithm, *a.Elitism)
if err != nil {
return
}
var combiners []combination.Combiner
for _, comb := range a.CombinationAlgorithms {
var c combination.Combiner
if c, err = combination.New(comb, *a.Elitism); err != nil {
return
}
combiners = append(combiners, c)
}
curPool := &poolA
otherPool := &poolB
var best solution.Specimen
best.Copy((*curPool).Specimens[0])
generation := uint(0)
start := time.Now()
for {
if g.checkGen(generation) || g.checkTime() {
break
}
// XXX: Generate initial workers
// XXX: Distribute work to workers
for i := range curPool.Specimens {
fitness := a.FFn((*curPool).Specimens[i].Buf)
(*curPool).Specimens[i].Fitness = fitness
if g.checkFitness(fitness) {
ret.ElapsedTime = time.Since(start)
ret.Generation = generation
ret.Solution.Copy((*curPool).Specimens[i])
return
}
}
(*curPool).Specimens.SortDesc()
best.Copy((*curPool).Specimens[0])
if g.checkTime() {
break
}
if err = sel.Select((*curPool), (*otherPool)); err != nil {
return
}
if g.checkTime() {
break
}
for _, combiner := range combiners {
if err = combiner.Combine((*otherPool)); err != nil {
return
}
}
if g.checkTime() {
break
}
// Switch buffers and repeat genetic algorithm
if curPool == &poolA {
curPool = &poolB
otherPool = &poolA
} else {
curPool = &poolA
otherPool = &poolB
}
generation++
}
ret.ElapsedTime = time.Since(start)
ret.Generation = generation
ret.Solution.Copy(best)
return
} | gap.go | 0.625781 | 0.505798 | gap.go | starcoder |
package ast
//BuiltInFunctionName returns the full function name for the given builtin symbol.
//The function returns an empty string when the symbol is not a known builtin symbol.
func BuiltInFunctionName(symbol string) string {
switch symbol {
case "==":
return "eq"
case "!=":
return "ne"
case "<":
return "lt"
case ">":
return "gt"
case "<=":
return "le"
case ">=":
return "ge"
case "~=":
return "regex"
case "*=":
return "contains"
case "^=":
return "hasPrefix"
case "$=":
return "hasSuffix"
case "::":
return "type"
}
return ""
}
// FunctionNameToBuiltIn returns the builtin constructor for a given function name.
// If a symbol does not exist, nil is returned.
func FunctionNameToBuiltIn(symbol string) func(*Expr) *Expr {
switch symbol {
case "eq":
return NewEqual
case "ne":
return NewNotEqual
case "lt":
return NewLessThan
case "gt":
return NewGreaterThan
case "le":
return NewLessEqual
case "ge":
return NewGreaterEqual
case "regex":
return NewRegex
case "contains":
return NewHasElem
case "hasPrefix":
return NewHasPrefix
case "hasSuffix":
return NewHasSuffix
case "type":
return NewType
}
return nil
}
//NewEqual returns an builtin equal expression.
// == e
func NewEqual(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newEqualEqual(),
Expr: e,
},
}
}
//NewNotEqual returns an builtin not equal expression.
// != e
func NewNotEqual(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newExclamationEqual(),
Expr: e,
},
}
}
//NewLessThan returns an builtin less than expression.
// < e
func NewLessThan(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newLessThan(),
Expr: e,
},
}
}
//NewGreaterThan returns an builtin greater than expression.
// > e
func NewGreaterThan(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newGreaterThan(),
Expr: e,
},
}
}
//NewLessEqual returns an builtin less than or equal expression.
// <= e
func NewLessEqual(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newLessEqual(),
Expr: e,
},
}
}
//NewGreaterEqual returns an builtin greater than or equal expression.
// >= e
func NewGreaterEqual(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newGreaterEqual(),
Expr: e,
},
}
}
//NewRegex returns an builtin regular expression.
// ~= e
func NewRegex(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newTildeEqual(),
Expr: e,
},
}
}
//NewHasElem returns an builtin contains expression.
// *= e
func NewHasElem(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newStarEqual(),
Expr: e,
},
}
}
//NewHasPrefix returns an builtin has prefix expression.
// ^= e
func NewHasPrefix(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newCaretEqual(),
Expr: e,
},
}
}
//NewHasSuffix returns an builtin has suffix expression.
// $= e
func NewHasSuffix(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newDollarEqual(),
Expr: e,
},
}
}
//NewType returns an builtin type expression.
// :: e
func NewType(e *Expr) *Expr {
return &Expr{
BuiltIn: &BuiltIn{
Symbol: newColonColon(),
Expr: e,
},
}
} | relapse/ast/builtin.go | 0.703855 | 0.551332 | builtin.go | starcoder |
package model
import "fmt"
// KeyphraseType enumerates the types of keyphrase.
type KeyphraseType int
const (
// KeyphraseTypeNone represents text that is not a keyphrase.
KeyphraseTypeNone KeyphraseType = iota
// KeyphraseTypeBlue represents a blue keyphrase.
KeyphraseTypeBlue
// KeyphraseTypeGreen represents a greenkeyphrase.
KeyphraseTypeGreen
)
// RecordType enumerates the types of records.
type RecordType int
const (
// RecordTypeTent is a record taken inside a tent.
RecordTypeTent RecordType = iota
// RecordTypeMailer is a record taken from the xelpud mailer.
RecordTypeMailer
// RecordTypeScanner is a record taken from a tablet.
RecordTypeScanner
// RecordTypeUnknown is a record from a screenshot that is not recognized.
RecordTypeUnknown
)
// Record represents a piece of interesting data in La Mulana
type Record struct {
Id int `storm:"id,increment" json:"id"`
Type RecordType `storm:"index" json:"type"`
Text string `json:"text"`
Subject string `json:"subject,omitempty"`
Index *int `json:"index,omitempty"`
Keyphrases map[KeyphraseType][]string `json:"keyphrases"`
}
func (t KeyphraseType) MarshalText() ([]byte, error) {
switch t {
case KeyphraseTypeNone:
return []byte("none"), nil
case KeyphraseTypeBlue:
return []byte("blue"), nil
case KeyphraseTypeGreen:
return []byte("green"), nil
}
return nil, fmt.Errorf("Unknown KeyphraseType %v", t)
}
func (t *KeyphraseType) UnmarshalText(text []byte) error {
switch string(text) {
case "none":
*t = KeyphraseTypeNone
return nil
case "blue":
*t = KeyphraseTypeBlue
return nil
case "green":
*t = KeyphraseTypeGreen
return nil
}
return fmt.Errorf("Unknown KeyphraseType %s", string(text))
}
func (t RecordType) MarshalText() ([]byte, error) {
switch t {
case RecordTypeTent:
return []byte("tent"), nil
case RecordTypeMailer:
return []byte("mailer"), nil
case RecordTypeScanner:
return []byte("scanner"), nil
case RecordTypeUnknown:
return []byte("unknown"), nil
}
return nil, fmt.Errorf("Unknown RecordType %v", t)
}
func (t *RecordType) UnmarshalText(text []byte) error {
switch string(text) {
case "tent":
*t = RecordTypeTent
return nil
case "mailer":
*t = RecordTypeMailer
return nil
case "scanner":
*t = RecordTypeScanner
return nil
case "unknown":
*t = RecordTypeUnknown
return nil
}
return fmt.Errorf("Unknown RecordType %s", string(text))
} | model/record.go | 0.652463 | 0.425009 | record.go | starcoder |
package daemon
import (
"log"
"math"
"time"
"github.com/larsth/go-gpsfix"
"github.com/larsth/go-rmsggpsbinmsg"
"github.com/larsth/rmsggpsd-gpspipe/cache"
"github.com/larsth/rmsggpsd-gpspipe/errors"
)
/*
calcBearing is a function that calculates the _inital_ bearing
from point p1(lat1, lon1) to point p2(lat2, lon2) by using the
haversine algorithm.
The bearing changes at any point between point 1 to
point 2 and vise versa.
The returned float64 value is the initial bearing in radians (not degrees).
*/
func calcBearing(this, other *binmsg.Message) (float64, error) {
/*
tc1=mod(atan2(sin(lon2-lon1)*cos(lat2),
cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)), 2*pi)
Algorithm is from:
http://mathforum.org/library/drmath/view/55417.html : Post #2
The algorithm had been translated to this pseudo code:
dlon = lon2 -lon1
sin_dlon = sin(dlon)
cos_lat2 = cos(lat2)
cos_lat1 = cos(lat1)
sin_lat2 = sin(lat2)
sin_lat1 = sin(lat1)
cos_dlon = cos(dlon)
atan2_x = sin_dlon*cos_lat2
atan2_y1 = cos_lat1*sin_lat2
atan2_y2 = sin_lat1*cos_lat2*cos_dlon
atan2_y = atan2_y1 - atan2_y2
mod_x = atan2(atan2_x, atan2_y)
mod_y = 2*pi
bearing=mod(mod_x, mod_y)
*/
var (
lon1, lat1, lon2, lat2 float64
dLon float64
sinLat2, sinLat1, sinDlon float64
cosLat2, cosLat1, cosDlon float64
atan2x, atan2y1, atan2y2, atan2y float64
modX, modY, bearing float64
err error
)
lat1 = this.Gps.Lat()
lat2 = other.Gps.Lat()
lon1 = this.Gps.Lon()
lon2 = other.Gps.Lon()
dLon = lon2 - lon1
sinDlon = math.Sin(dLon)
cosLat2 = math.Cos(lat2)
cosLat1 = math.Cos(lat1)
sinLat2 = math.Sin(lat2)
sinLat1 = math.Sin(lat1)
cosDlon = math.Cos(dLon)
atan2x = sinDlon * cosLat2
atan2y1 = cosLat1 * sinLat2
atan2y2 = sinLat1 * cosLat2 * cosDlon
atan2y = atan2y1 - atan2y2
if modX, err = atan2(atan2x, atan2y); err != nil {
return math.NaN(), errors.Trace(err)
}
modY = math.Pi * 2
bearing = math.Mod(modX, modY)
return bearing, nil
}
func updateBearingCache(this, other *binmsg.Message, logger *log.Logger, bc *cache.Bearing) {
var (
useTime time.Time
a, b, c, d bool
bearing float64
err error
)
if this.TimeStamp.Time.Before(other.TimeStamp.Time) {
useTime = this.TimeStamp.Time
} else {
useTime = other.TimeStamp.Time
}
a = this.Gps.FixMode == gpsfix.FixNotSeen
b = this.Gps.FixMode == gpsfix.FixNone
c = this.Gps.FixMode == gpsfix.FixNotSeen
d = this.Gps.FixMode == gpsfix.FixNone
if a || b || c || d {
bearing = math.NaN()
} else {
//FIXME
/* Also use sentinel values?, ie. : special float64 values outside 360
degrees (2*Pi rad) to give extra information to http request functions?
*/
bearing, err = calcBearing(this, other)
if err != nil {
logger.Println(err)
}
}
bc.Put(bearing, useTime)
}
func bearingGoRoutine(logger *log.Logger) {
var (
this = binmsg.MkFixNotSeenMessage()
other = binmsg.MkFixNotSeenMessage()
)
updateBearingCache(this, other, logger, bearingCache)
for {
select {
case this = <-thisChan:
updateBearingCache(this, other, logger, bearingCache)
case other = <-otherChan:
updateBearingCache(this, other, logger, bearingCache)
}
}
} | daemon/bearing.go | 0.53048 | 0.437824 | bearing.go | starcoder |
package model
import (
"bytes"
"encoding/gob"
"github.com/therfoo/therfoo/metrics"
"github.com/therfoo/therfoo/optimizers"
"github.com/therfoo/therfoo/tensor"
"io/ioutil"
"math/rand"
"os"
"sync"
"time"
)
type Model struct {
accurate func(yTrue, yEstimate *tensor.Vector) bool
lossFunction func(yTrue, yEstimate *tensor.Vector) *tensor.Vector
lossPrime func(yTrue, yEstimate *tensor.Vector) *tensor.Vector
generator struct {
testing Generator
training Generator
validating Generator
}
inputShape tensor.Shape
layers []Layer
layersCount int
learningRate float64
metricsConsumers []metrics.Consumer
neuronsCount []int
optimizer optimizers.Optimizer
epochs int
skipOutputDerivative bool
}
func (m *Model) activate(activation *tensor.Vector) *[]tensor.Vector {
n := m.layersCount + 1
activations := make([]tensor.Vector, n, n)
activations[0] = *activation
for l := 0; l < m.layersCount; l++ {
activations[l+1] = *m.layers[l].Activate(&(activations[l]))
}
return &activations
}
func (m *Model) Add(neuronsCount int, layer Layer) {
m.neuronsCount = append(m.neuronsCount, neuronsCount)
m.layers = append(m.layers, layer)
m.layersCount++
}
func (m *Model) Compile() error {
neurons := make([][]int, m.layersCount, m.layersCount)
for l := range m.layers {
var weightsCount int
if l == 0 {
weightsCount = m.inputShape.Size()
} else {
weightsCount = m.neuronsCount[l-1]
}
m.layers[l].Init(m.neuronsCount[l], weightsCount)
neurons[l] = []int{m.neuronsCount[l], weightsCount}
}
m.optimizer.Init(&neurons)
return nil
}
func (m *Model) Fit() {
for epoch := 0; epoch < m.epochs; epoch++ {
rand.Seed(time.Now().Unix())
for _, batch := range rand.Perm(m.generator.training.Len()) {
xBatch, yBatch := m.generator.training.Get(batch)
wg := sync.WaitGroup{}
batchSize := len(*xBatch)
wg.Add(batchSize)
for i := range *xBatch {
go func(s int) {
x := (*xBatch)[s]
m.minimize(&((*yBatch)[s]), m.activate(&x))
wg.Done()
}(i)
}
wg.Wait()
m.optimize(m.optimizer.Optimizations())
}
m.validate(epoch)
}
}
func (m *Model) Load(filename string) (err error) {
f, err := os.Open(filename)
var weights [][]byte
gob.NewDecoder(f).Decode(&weights)
for l := range m.layers {
err = m.layers[l].Load(weights[l])
if err != nil {
return err
}
}
return nil
}
func (m *Model) minimize(yTrue *tensor.Vector, activations *[]tensor.Vector) {
yEstimate := (*activations)[m.layersCount]
nablaLoss := m.lossPrime(yTrue, &yEstimate)
if !m.skipOutputDerivative {
m.layers[m.layersCount-1].Derive(&((*activations)[m.layersCount-1]), nablaLoss)
}
m.optimizer.Add(m.layersCount-1, &((*activations)[m.layersCount-1]), nablaLoss)
ll := m.layersCount - 2
for l := ll; l > -1; l-- {
nablaLoss = m.layers[l+1].NextCost(nablaLoss)
m.layers[l].Derive(&((*activations)[l+1]), nablaLoss)
m.optimizer.Add(l, &((*activations)[l]), nablaLoss)
}
}
func (m *Model) optimize(optimizations *[][][]float64) {
for layer := range *optimizations {
m.layers[layer].Adjust(&((*optimizations)[layer]))
}
}
func (m *Model) Predict(xBatch *[]tensor.Vector) *[]tensor.Vector {
predictions := make([]tensor.Vector, len(*xBatch), len(*xBatch))
for i := range *xBatch {
predictions[i] = (*m.activate(&(*xBatch)[i]))[m.layersCount]
}
return &predictions
}
func (m *Model) Save(filename string) (err error) {
weights := make([][]byte, m.layersCount, m.layersCount)
for l := range m.layers {
weights[l], err = m.layers[l].Bytes()
if err != nil {
return err
}
}
var b bytes.Buffer
err = gob.NewEncoder(&b).Encode(weights)
if err == nil {
ioutil.WriteFile(filename, b.Bytes(), 0755)
}
return err
}
func (m *Model) validate(epoch int) {
rand.Seed(time.Now().Unix())
n := m.generator.validating.Len()
mm := metrics.Metrics{Epoch: epoch}
accurate, total := 0., 0.
for _, batch := range rand.Perm(n) {
xBatch, yBatch := m.generator.training.Get(batch)
yBatchEstimate := m.Predict(xBatch)
cost := 0.
for i := range *yBatch {
cost += m.lossFunction(&(*yBatch)[i], &(*yBatchEstimate)[i]).Sum()
total++
if m.accurate(&(*yBatch)[i], &(*yBatchEstimate)[i]) {
accurate++
}
}
mm.Cost += cost / float64(len(*yBatch))
}
mm.Accuracy, mm.Cost = accurate/total, mm.Cost/float64(n)
for _, consume := range m.metricsConsumers {
consume(&mm)
}
}
func New(options ...Option) *Model {
m := Model{}
for i := range options {
options[i](&m)
}
return &m
} | model/model.go | 0.677367 | 0.475179 | model.go | starcoder |
package golife
import (
"fmt"
"math/rand"
"github.com/gdamore/tcell"
)
// CellState represents the state of a cell
// 0 is dead and 1 is alive
type CellState int
const (
dead CellState = iota
alive
)
// Board represents the game board
type Board struct {
Game *Game
Grid [][]CellState
Dimension
}
// newBoard returns a new Board instance
func newBoard(x, y, w, h int) *Board {
return &Board{
Dimension: Dimension{
x,
y,
w,
h,
},
}
}
// draw paints the Board grid to the screen
func (b *Board) draw() {
s := b.Game.Screen
for i := b.y; i < len(b.Grid); i++ {
for j := b.x; j < len(b.Grid[0]); j++ {
value := b.Grid[i][j]
if value == 1 {
cellStyle := tcell.StyleDefault.Foreground(b.Game.CellColor).Background(b.Game.Background)
s.SetContent(j*2, i, tcell.RuneBlock, nil, cellStyle)
s.SetContent(j*2+1, i, tcell.RuneBlock, nil, cellStyle)
}
}
}
}
// generateGrid generates the grid for the game
func (b *Board) generateGrid() {
grid := make([][]CellState, b.h)
for i := 0; i < b.h; i++ {
grid[i] = make([]CellState, b.w)
}
b.Grid = grid
}
// random populates the grid with a random
// arrangement of cells
func (b *Board) random() {
for i := 0; i < b.h; i++ {
for j := 0; j < b.w; j++ {
b.Grid[i][j] = CellState(rand.Int() % 2)
}
}
}
// preset populates the grid with a preset
// arrangement of cells
func (b *Board) preset() error {
p := b.Game.PresetPattern
ph := len(p.Cells)
if ph == 0 {
return fmt.Errorf("Something went wrong. Please check the pattern file or URL")
}
pw := len(p.Cells[0])
if pw > b.w || ph > b.h {
return fmt.Errorf("The current board is not big enough for this preset")
}
x := (b.w*2/2 - pw) / 2
y := (b.h - ph) / 2
for i := 0; i < ph; i++ {
for j := 0; j < pw; j++ {
if y+i < b.h && x+j < b.w*2 {
b.Grid[y+i][x+j] = CellState(p.Cells[i][j])
}
}
}
return nil
}
// countNeighbours determines the number of live
// neighbours a cell has depending on whether
// wrapping is enabled or not
func (b *Board) countNeighbours(x int, y int) int {
var sum int
numberOfRows := len(b.Grid)
numberOfCols := len(b.Grid[0])
for i := -1; i < 2; i++ {
for j := -1; j < 2; j++ {
// skip over the current cell
if i == 0 && j == 0 {
continue
}
if b.Game.EdgeWrap {
row := (x + i + numberOfRows) % numberOfRows
col := (y + j + numberOfCols) % numberOfCols
sum += int(b.Grid[row][col])
} else {
row := x + i
col := y + j
if row >= 0 && col >= 0 && row < numberOfRows && col < numberOfCols {
sum += int(b.Grid[row][col])
}
}
}
}
return sum
}
// nextGeneration calculates the next generation
// based on the current one and returns the
// number of living cells
func (b *Board) nextGeneration() int {
nextGrid := make([][]CellState, len(b.Grid))
for i := 0; i < len(b.Grid); i++ {
nextGrid[i] = make([]CellState, len(b.Grid[0]))
}
var livingCells int
for i := 0; i < len(b.Grid); i++ {
for j := 0; j < len(b.Grid[0]); j++ {
value := b.Grid[i][j]
neighbours := b.countNeighbours(i, j)
if value == dead && containsInt(b.Game.Rule.Born, neighbours) {
nextGrid[i][j] = alive
} else if value == 1 && !containsInt(b.Game.Rule.Survives, neighbours) {
nextGrid[i][j] = dead
} else {
nextGrid[i][j] = value
}
if nextGrid[i][j] == alive {
livingCells++
}
}
}
b.Grid = nextGrid
return livingCells
} | board.go | 0.664431 | 0.438785 | board.go | starcoder |
package guetzli_patapon
// Returns true if and only if x has a zero byte, i.e. one of
// x & 0xff, x & 0xff00, ..., x & 0xff00000000000000 is zero.
func HasZeroByte(x uint64) bool {
return ((x - 0x0101010101010101) & ^x & 0x8080808080808080) != 0;
}
// Handles the packing of bits into output bytes.
type BitWriter struct {
length int;
data []byte;
pos int;
put_buffer uint64;
put_bits int;
overflow bool;
};
func NewBitWriter(length int) *BitWriter {
return &BitWriter{
length: length,
data: make([]byte, length),
pos: 0,
put_buffer: 0,
put_bits: 64,
overflow: false,
}
}
func (bw *BitWriter) WriteBits(nbits int, bits uint64) {
bw.put_bits -= nbits;
bw.put_buffer |= (bits << uint(bw.put_bits));
if (bw.put_bits <= 16) {
// At this point we are ready to emit the most significant 6 bytes of
// put_buffer_ to the output.
// The JPEG format requires that after every 0xff byte in the entropy
// coded section, there is a zero byte, therefore we first check if any of
// the 6 most significant bytes of put_buffer_ is 0xff.
if (HasZeroByte(^bw.put_buffer | 0xffff)) {
// We have a 0xff byte somewhere, examine each byte and append a zero
// byte if necessary.
bw.EmitByte(int((bw.put_buffer >> 56) & 0xff));
bw.EmitByte(int((bw.put_buffer >> 48) & 0xff));
bw.EmitByte(int((bw.put_buffer >> 40) & 0xff));
bw.EmitByte(int((bw.put_buffer >> 32) & 0xff));
bw.EmitByte(int((bw.put_buffer >> 24) & 0xff));
bw.EmitByte(int((bw.put_buffer >> 16) & 0xff));
} else if (bw.pos + 6 < bw.length) {
// We don't have any 0xff bytes, output all 6 bytes without checking.
bw.data[bw.pos] = byte((bw.put_buffer >> 56) & 0xff);
bw.data[bw.pos + 1] = byte((bw.put_buffer >> 48) & 0xff);
bw.data[bw.pos + 2] = byte((bw.put_buffer >> 40) & 0xff);
bw.data[bw.pos + 3] = byte((bw.put_buffer >> 32) & 0xff);
bw.data[bw.pos + 4] = byte((bw.put_buffer >> 24) & 0xff);
bw.data[bw.pos + 5] = byte((bw.put_buffer >> 16) & 0xff);
bw.pos += 6;
} else {
bw.overflow = true;
}
bw.put_buffer <<= 48;
bw.put_bits += 48;
}
}
// Writes the given byte to the output, writes an extra zero if byte is 0xff.
func (bw *BitWriter) EmitByte(byte_ int) {
if (bw.pos < bw.length) {
bw.data[bw.pos] = byte(byte_);
bw.pos++
} else {
bw.overflow = true;
}
if (byte_ == 0xff) {
bw.EmitByte(0);
}
}
func (bw *BitWriter) JumpToByteBoundary() {
for (bw.put_bits <= 56) {
c := (bw.put_buffer >> 56) & 0xff;
bw.EmitByte(int(c));
bw.put_buffer <<= 8;
bw.put_bits += 8;
}
if (bw.put_bits < 64) {
padmask := 0xff >> (64 - uint(bw.put_bits));
c := (int(bw.put_buffer >> 56) & ^padmask) | padmask;
bw.EmitByte(c);
}
bw.put_buffer = 0;
bw.put_bits = 64;
} | jpeg_bit_writer.go | 0.756537 | 0.529872 | jpeg_bit_writer.go | starcoder |
package main
import (
"fmt"
"log"
"net/http"
)
type data struct {
host string
path string
}
type test struct {
name string
args data
expected string
fallback bool
status int
comment string
}
var tests = []test{
{
name: "Redirect a path record without specified v=",
args: data{
host: "noversion.path.path.example.com",
path: "/",
},
expected: "https://noversion-redirect.path.path.example.com",
},
{
name: "Redirect a path record without specified root=",
args: data{
host: "noroot.path.path.example.com",
path: "/",
},
expected: "https://noroot-redirect.path.path.example.com",
},
{
name: "Redirect a path record using predefined regex records",
args: data{
host: "predefined-regex.path.path.example.com",
path: "/test1",
},
expected: "https://predefined-redirect.host.path.example.com/second/test1",
},
{
name: "Redirect a path record using predefined regex records",
args: data{
host: "predefined-regex.path.path.example.com",
path: "/test1/test2",
},
expected: "https://predefined-redirect.host.path.example.com/first/test1/test2",
},
{
name: "Fallback to \"to=\" when wildcard not found",
args: data{
host: "path.path.example.com",
path: "/not/found",
},
fallback: true,
expected: "https://fallback-to.path.path.example.com",
},
{
name: "Fallback to \"to=\" when \"re=\" and \"from=\" both exist",
args: data{
host: "fallback-refrom.path.path.example.com",
path: "/",
},
fallback: true,
expected: "https://fallback-to.path.path.example.com",
},
{
name: "Fallback to \"to=\" when \"from=\" length doesn't match request's path length",
args: data{
host: "fallback-lenfrom.path.path.example.com",
path: "/",
},
fallback: true,
expected: "https://fallback-to.path.path.example.com",
},
{
name: "Redirect using the use= field and upstream record",
args: data{
host: "sourcerecord.path.path.example.com",
path: "/testing",
},
expected: "https://upstream.path.path.example.com",
},
{
name: "Redirect to upstream record using multiple use= fields and skipping non-working upstream",
args: data{
host: "src-multiple-use.path.path.example.com",
path: "/testing",
},
expected: "https://upstream.path.path.example.com",
},
{
name: "Fallback when the upstream record doesn't respond",
args: data{
host: "fallbackupstream.path.path.example.com",
path: "/testing",
},
fallback: true,
status: 404,
},
{
name: "Prioritise the parent record's to= field to chained records in fallback",
args: data{
host: "pathchain.path.path.example.com",
path: "/",
},
expected: "https://fallback-to.path.path.example.com",
},
{
name: "Fallback when wrong path is given to chained path records",
args: data{
host: "pathchain.path.path.example.com",
path: "/wrong",
},
expected: "https://fallback-unknown-path.path.path.example.com",
},
{
name: "Use regex placeholders in fallback triggered by chained record",
args: data{
host: "chaining-regex.path.path.example.com",
path: "/fallback-placeholder/",
},
expected: "https://fallback.path.path.example.com/fallback-placeholder",
},
{
name: "Fallback to root= when path is empty for custom regex",
args: data{
host: "numbered-regex.host.path.example.com",
path: "",
},
expected: "https://fallback.host.path.example.com",
comment: "for: apt.k8s.io",
},
{
name: "Redirect to host record's to= field using numbered regex",
args: data{
host: "numbered-regex.host.path.example.com",
path: "/testing",
},
expected: "https://package.host.path.example.com/apt/testing",
comment: "for: apt.k8s.io",
},
{
name: "Redirect to root= when path is / for custom regex",
args: data{
host: "custom-numbered.host.path.example.com",
path: "/",
},
expected: "https://index.host.path.example.com",
comment: "for: changelog.k8s.io",
},
{
name: "Redirect to host record's to= for custom regex using placeholders",
args: data{
host: "custom-numbered.host.path.example.com",
path: "/testing",
},
expected: "https://redirect.host.path.example.com/testing",
comment: "for: changelog.k8s.io",
},
{
name: "Fallback to root= when path is empty for predefined regexes",
args: data{
host: "predefined-numbered.host.path.example.com",
path: "/",
},
expected: "https://index.host.path.example.com",
comment: "for: ci-test.k8s.io",
},
{
name: "Redirect to host record's to= when path contains digits for predefined regex",
args: data{
host: "predefined-numbered.host.path.example.com",
path: "/testing/1",
},
expected: "https://first-record.host.path.example.com/testing/1",
comment: "for: ci-test.k8s.io",
},
{
name: "Redirect to host record's to= when path contains two slashes for predefined regex",
args: data{
host: "predefined-numbered.host.path.example.com",
path: "/testing/",
},
expected: "https://second-record.host.path.example.com/testing/",
comment: "for: ci-test.k8s.io",
},
{
name: "Redirect to host record's to= when path is one part for predefined regex",
args: data{
host: "predefined-numbered.host.path.example.com",
path: "/testing",
},
expected: "https://third-record.host.path.example.com/testing",
comment: "for: ci-test.k8s.io",
},
{
name: "Redirect to host record's to= when path is a semantic version",
args: data{
host: "predefined-multinumbered.host.path.example.com",
path: "/v0.0.1/",
},
expected: "https://first-record.host.path.example.com/v0.0.1/",
comment: "for: dl.k8s.io",
},
{
name: "Redirect to host record's to= when path contains a word from custom regex",
args: data{
host: "predefined-multinumbered.host.path.example.com",
path: "/ci-cross/test",
},
expected: "https://second-record.host.path.example.com/ci-cross/test",
comment: "for: dl.k8s.io",
},
{
name: "Redirect to host record's to= when path contains a word from custom regex",
args: data{
host: "predefined-multinumbered.host.path.example.com",
path: "/ci/test",
},
expected: "https://second-record.host.path.example.com/ci/test",
comment: "for: dl.k8s.io",
},
{
name: "Redirect to host record's to= when path contains any character",
args: data{
host: "predefined-multinumbered.host.path.example.com",
path: "/notdefined",
},
expected: "https://third-record.host.path.example.com/notdefined",
comment: "for: dl.k8s.io",
},
{
name: "Redirect to host record's to= when path contains a version",
args: data{
host: "predefined-version.host.path.example.com",
path: "/v0.0/beta",
},
expected: "https://first-record.host.path.example.com/v0.0/beta",
comment: "for: docs.k8s.io",
},
{
name: "Redirect to second host record's to= when path doesn't contain a version",
args: data{
host: "predefined-version.host.path.example.com",
path: "/testing",
},
expected: "https://second-record.host.path.example.com/docs/testing",
comment: "for: docs.k8s.io",
},
{
name: "Redirect to host record's to= when path contains a version and word",
args: data{
host: "predefined-versionword.host.path.example.com",
path: "/v0.0/beta",
},
expected: "https://first-record.host.path.example.com/release-0.0/examples/beta",
comment: "for: examples.k8s.io",
},
{
name: "Redirect to second host record's to= when path doesn't contain a version and word",
args: data{
host: "predefined-versionword.host.path.example.com",
path: "/testing",
},
expected: "https://second-record.host.path.example.com/testing",
comment: "for: examples.k8s.io",
},
{
name: "Redirect to host record's to= when path contains brackets",
args: data{
host: "predefined-simpletospecific.host.path.example.com",
path: "/[test]/",
},
expected: "https://first-record.host.path.example.com/[test]/",
comment: "for: git.k8s.io",
},
{
name: "Redirect to host record's to= when path contains brackets and words",
args: data{
host: "predefined-simpletospecific.host.path.example.com",
path: "/[test]/testing",
},
expected: "https://first-record.host.path.example.com/[test]/testing",
comment: "for: git.k8s.io",
},
{
name: "Redirect to second host record's to= when path doesn't contain brackets",
args: data{
host: "predefined-simpletospecific.host.path.example.com",
path: "/testing",
},
expected: "https://second-record.host.path.example.com/testing",
comment: "for: git.k8s.io",
},
{
name: "Redirect to host record's to= using multiple predefined regexes",
args: data{
host: "path-subdomain.host.path.example.com",
path: "/good-first-issue",
},
expected: "https://path-subdomain-redirect.host.path.example.com/4",
comment: "for: go.k8s.io",
},
{
name: "Redirect to host record's to= when path contains release",
args: data{
host: "predefined-release.host.path.example.com",
path: "/v0.0.1/beta",
},
expected: "https://predefined-regex.host.path.example.com/v0.0.1/beta",
comment: "for: releases.k8s.io",
},
{
name: "Redirect using to= field from the upstream path record in the apex zone wildcard",
args: data{
host: "apexuse.path.path.example.com",
path: "/test",
},
expected: "https://apexuse-to.path.path.example.com",
},
}
func main() {
result := make(map[bool][]test)
for _, test := range tests {
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s%s", test.args.host, test.args.path), nil)
resp, err := client.Do(req)
if err != nil {
result[false] = append(result[false], test)
log.Printf("[%s]: Couldn't send the request: %s", test.name, err.Error())
continue
}
// Check response's status code
if test.status != 0 {
if resp.StatusCode != test.status {
result[false] = append(result[false], test)
log.Printf("[%s]: Expected %d status code, got %d", test.name, test.status, resp.StatusCode)
continue
}
result[true] = append(result[true], test)
continue
}
location, err := resp.Location()
if err == http.ErrNoLocation {
result[false] = append(result[false], test)
log.Printf("[%s]: Location header is empty", test.name)
continue
}
if location.String() != test.expected {
result[false] = append(result[false], test)
log.Printf("[%s]: Expected %s, got %s", test.name, test.expected, location)
continue
}
result[true] = append(result[true], test)
}
log.Printf("TestCase: \"path\", Total: %d, Passed: %d, Failed: %d", len(tests), len(result[true]), len(result[false]))
} | e2e/path/main.go | 0.505127 | 0.514156 | main.go | starcoder |
package httpref
// WellKnownPorts is the list of all known IANA reserved ports
var WellKnownPorts = References{
{
Name: "Well Known Ports",
IsTitle: true,
Summary: "The port numbers in the range from 0 to 1023 (0 to 2^10 − 1)",
Description: `The port numbers in the range from 0 to 1023 (0 to 210 − 1) are the well-known ports or system ports.[2] They are used by system processes that provide widely used types of network services. On Unix-like operating systems, a process must execute with superuser privileges to be able to bind a network socket to an IP address using one of the well-known ports.
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "0",
Description: `Reserved
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
In programming APIs (not in communication between hosts), requests a system-allocated (dynamic) port
IANA Status - Unofficial
TCP - N/A
UDP - N/A
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "1",
Description: `TCP Port Service Multiplexer ( https://en.wikipedia.org/wiki/TCP_Port_Service_Multiplexer ) (TCPMUX). Historic. Both TCP and UDP have been assigned to TCPMUX by IANA, but by design only TCP is specified.
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "5",
Description: `Remote Job Entry ( https://en.wikipedia.org/wiki/Remote_Job_Entry ) was historically using socket 5 in its old socket form ( https://en.wikipedia.org/wiki/Network_socket#History ), while MIB PIM has identified it as TCP/5 and IANA has assigned both TCP and UDP 5 to it.
IANA Status - Official
TCP - Assigned
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "7",
Description: `Echo Protocol ( https://en.wikipedia.org/wiki/Echo_Protocol )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "9",
Description: `Discard Protocol ( https://en.wikipedia.org/wiki/Discard_Protocol )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Yes
Wake-on-LAN ( https://en.wikipedia.org/wiki/Wake-on-LAN )
IANA Status - Unofficial
TCP - No
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "11",
Description: `Active Users (systat ( https://en.wikipedia.org/wiki/Systat_(protocol) ) service)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "13",
Description: `Daytime Protocol ( https://en.wikipedia.org/wiki/Daytime_Protocol )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "15",
Description: `Previously netstat ( https://en.wikipedia.org/wiki/Netstat ) service
IANA Status - Unofficial
TCP - Yes
UDP - No
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "17",
Description: `Quote of the Day ( https://en.wikipedia.org/wiki/QOTD ) (QOTD)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "18",
Description: `Message Send Protocol ( https://en.wikipedia.org/wiki/Message_Send_Protocol )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "19",
Description: `Character Generator Protocol ( https://en.wikipedia.org/wiki/Character_Generator_Protocol ) (CHARGEN)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "20",
Description: `File Transfer Protocol ( https://en.wikipedia.org/wiki/File_Transfer_Protocol ) (FTP) data transfer
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Yes
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "21",
Description: `File Transfer Protocol ( https://en.wikipedia.org/wiki/File_Transfer_Protocol ) (FTP) control (command)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Yes
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "22",
Description: `Secure Shell ( https://en.wikipedia.org/wiki/Secure_Shell ) (SSH), secure logins, file transfers ( https://en.wikipedia.org/wiki/File_transfer ) (scp ( https://en.wikipedia.org/wiki/Secure_copy ), sftp ( https://en.wikipedia.org/wiki/SSH_file_transfer_protocol )) and port forwarding
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Yes
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "23",
Description: `Telnet ( https://en.wikipedia.org/wiki/Telnet ) protocol—unencrypted text communications
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "25",
Description: `Simple Mail Transfer Protocol ( https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol ) (SMTP), used for email routing between mail servers
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "37",
Description: `Time Protocol ( https://en.wikipedia.org/wiki/Time_Protocol )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "42",
Description: `Host Name Server Protocol ( https://en.wikipedia.org/wiki/ARPA_Host_Name_Server_Protocol )
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "43",
Description: `WHOIS ( https://en.wikipedia.org/wiki/WHOIS ) protocol
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "47",
Description: `Unspecified
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "49",
Description: `TACACS ( https://en.wikipedia.org/wiki/TACACS ) Login Host protocol. TACACS+ ( https://en.wikipedia.org/wiki/TACACS%2B ), still in draft which is an improved but distinct version of TACACS, only uses TCP 49.
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "51",
Description: `Historically used for Interface Message Processor ( https://en.wikipedia.org/wiki/Interface_Message_Processor ) logical address management, entry has been removed by IANA on 2013-05-25
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "52",
Description: `Xerox Network Systems ( https://en.wikipedia.org/wiki/Xerox_Network_Systems ) (XNS) Time Protocol. Despite this port being assigned by IANA, the service is meant to work on SPP ( https://en.wikipedia.org/wiki/Sequenced_Packet_Protocol ) (ancestor of IPX/SPX ( https://en.wikipedia.org/wiki/IPX/SPX )), instead of TCP/IP.
IANA Status - Official
TCP - Assigned
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "53",
Description: `Domain Name System ( https://en.wikipedia.org/wiki/Domain_Name_System ) (DNS)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "54",
Description: `Xerox Network Systems (XNS) Clearinghouse (Name Server). Despite this port being assigned by IANA, the service is meant to work on SPP ( https://en.wikipedia.org/wiki/Sequenced_Packet_Protocol ) (ancestor of IPX/SPX ( https://en.wikipedia.org/wiki/IPX/SPX )), instead of TCP/IP.
IANA Status - Official
TCP - Assigned
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "56",
Description: `Xerox Network Systems (XNS) Authentication Protocol. Despite this port being assigned by IANA, the service is meant to work on SPP ( https://en.wikipedia.org/wiki/Sequenced_Packet_Protocol ) (ancestor of IPX/SPX ( https://en.wikipedia.org/wiki/IPX/SPX )), instead of TCP/IP.
IANA Status - Official
TCP - Assigned
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "58",
Description: `Xerox Network Systems (XNS) Mail. Despite this port being assigned by IANA, the service is meant to work on SPP ( https://en.wikipedia.org/wiki/Sequenced_Packet_Protocol ) (ancestor of IPX/SPX ( https://en.wikipedia.org/wiki/IPX/SPX )), instead of TCP/IP.
IANA Status - Official
TCP - Assigned
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "61",
Description: `Historically assigned to the NIFTP-Based Mail ( https://en.wikipedia.org/w/index.php?title=NIFTP-Based_Mail&action=edit&redlink=1 ) protocol, but was never documented in the related IEN ( https://en.wikipedia.org/wiki/Internet_Experiment_Note ). The port number entry was removed from IANA's registry on 2017-05-18.
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "67",
Description: `Bootstrap Protocol ( https://en.wikipedia.org/wiki/Bootstrap_Protocol ) (BOOTP) server; also used by Dynamic Host Configuration Protocol ( https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol ) (DHCP)
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "68",
Description: `Bootstrap Protocol (BOOTP) client; also used by Dynamic Host Configuration Protocol (DHCP)
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "69",
Description: `Trivial File Transfer Protocol ( https://en.wikipedia.org/wiki/Trivial_File_Transfer_Protocol ) (TFTP)
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "70",
Description: `Gopher ( https://en.wikipedia.org/wiki/Gopher_(protocol) ) protocol
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "71-74",
Description: `NETRJS ( https://en.wikipedia.org/wiki/NETRJS ) protocol
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "79",
Description: `Finger protocol ( https://en.wikipedia.org/wiki/Finger_protocol )
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "80",
Description: `Hypertext Transfer Protocol ( https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol ) (HTTP)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Yes
QUIC ( https://en.wikipedia.org/wiki/QUIC ), a transport protocol over UDP (still in draft as of April 2020[update] ( https://en.wikipedia.org/w/index.php?title=List_of_TCP_and_UDP_port_numbers&action=edit )), using stream multiplexing ( https://en.wikipedia.org/wiki/Multiplexing ), encryption by default with TLS ( https://en.wikipedia.org/wiki/Transport_Layer_Security ), and currently supporting HTTP/2 ( https://en.wikipedia.org/wiki/HTTP/2 ). QUIC has been renamed to HTTP/3 ( https://en.wikipedia.org/wiki/HTTP/3 ), which is currently an Internet Draft ( https://en.wikipedia.org/wiki/Internet_Draft ).
IANA Status - Unofficial
TCP - No
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "81",
Description: `TorPark ( https://en.wikipedia.org/wiki/TorPark ) onion routing ( https://en.wikipedia.org/wiki/Onion_routing )
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "82",
Description: `TorPark ( https://en.wikipedia.org/wiki/TorPark ) control
IANA Status - Unofficial
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "83",
Description: `MIT ML Device, networking file system
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "88",
Description: `Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) authentication system
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "90",
Description: `PointCast (dotcom) ( https://en.wikipedia.org/wiki/PointCast_(dotcom) )
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "95",
Description: `SUPDUP, terminal-independent remote login
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "101",
Description: `NIC ( https://en.wikipedia.org/wiki/History_of_the_Internet#NIC,_InterNIC,_IANA_and_ICANN ) host name ( https://en.wikipedia.org/wiki/Hostname )
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "102",
Description: `ISO ( https://en.wikipedia.org/wiki/International_Organization_for_Standardization ) Transport Service Access Point (TSAP ( https://en.wikipedia.org/wiki/TSAP )) Class 0 protocol;
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "104",
Description: `Digital Imaging and Communications in Medicine ( https://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine ) (DICOM; also port 11112)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "105",
Description: `CCSO Nameserver ( https://en.wikipedia.org/wiki/CCSO_Nameserver )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "107",
Description: `Remote User Telnet Service ( https://en.wikipedia.org/wiki/Rtelnet ) (RTelnet)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "108",
Description: `IBM Systems Network Architecture ( https://en.wikipedia.org/wiki/Systems_Network_Architecture ) (SNA) gateway access server
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "109",
Description: `Post Office Protocol ( https://en.wikipedia.org/wiki/Post_Office_Protocol ), version 2 (POP2)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "110",
Description: `Post Office Protocol, version 3 (POP3)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "111",
Description: `Open Network Computing Remote Procedure Call ( https://en.wikipedia.org/wiki/Open_Network_Computing_Remote_Procedure_Call ) (ONC RPC, sometimes referred to as Sun RPC)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "113",
Description: `Ident ( https://en.wikipedia.org/wiki/Ident_protocol ), authentication service/identification protocol, used by IRC ( https://en.wikipedia.org/wiki/Internet_Relay_Chat ) servers to identify users
IANA Status - Official
TCP - Yes
UDP - No
SCTP - Unspecified
Authentication Service (auth), the predecessor to identification protocol. Used to determine a user's identity of a particular TCP connection.
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "115",
Description: `Simple File Transfer Protocol ( https://en.wikipedia.org/wiki/Simple_File_Transfer_Protocol )
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "117",
Description: `UUCP Mapping Project ( https://en.wikipedia.org/wiki/UUCP_Mapping_Project ) (path service)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "118",
Description: `Structured Query Language (SQL ( https://en.wikipedia.org/wiki/SQL )) Services
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "119",
Description: `Network News Transfer Protocol ( https://en.wikipedia.org/wiki/Network_News_Transfer_Protocol ) (NNTP), retrieval of newsgroup messages
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "123",
Description: `Network Time Protocol ( https://en.wikipedia.org/wiki/Network_Time_Protocol ) (NTP), used for time synchronization
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "126",
Description: `Formerly Unisys ( https://en.wikipedia.org/wiki/Unisys ) Unitary Login, renamed by Unisys to NXEdit. Used by Unisys Programmer's Workbench for Clearpath MCP, an IDE for Unisys MCP software development ( https://en.wikipedia.org/wiki/Unisys_MCP_programming_languages )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "135",
Description: `DCE ( https://en.wikipedia.org/wiki/Distributed_Computing_Environment ) endpoint ( https://en.wikipedia.org/wiki/Communication_endpoint ) resolution
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
Microsoft ( https://en.wikipedia.org/wiki/Microsoft ) EPMAP (End Point Mapper), also known as DCE/RPC ( https://en.wikipedia.org/wiki/Remote_procedure_call ) Locator service, used to remotely manage services including DHCP server ( https://en.wikipedia.org/wiki/DHCP_server ), DNS ( https://en.wikipedia.org/wiki/Domain_Name_System ) server and WINS ( https://en.wikipedia.org/wiki/Windows_Internet_Name_Service ). Also used by DCOM ( https://en.wikipedia.org/wiki/Distributed_Component_Object_Model )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "137",
Description: `NetBIOS ( https://en.wikipedia.org/wiki/NetBIOS ) Name Service, used for name registration and resolution ( https://en.wikipedia.org/wiki/Name_resolution_(computer_systems) )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "138",
Description: `NetBIOS Datagram Service
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "139",
Description: `NetBIOS Session Service
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "143",
Description: `Internet Message Access Protocol ( https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol ) (IMAP), management of electronic mail ( https://en.wikipedia.org/wiki/Email ) messages on a server
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "152",
Description: `Background File Transfer Program ( https://en.wikipedia.org/w/index.php?title=Background_File_Transfer_Program&action=edit&redlink=1 ) (BFTP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "153",
Description: `Simple Gateway Monitoring Protocol ( https://en.wikipedia.org/wiki/Simple_Gateway_Monitoring_Protocol ) (SGMP), a protocol for remote inspection and alteration of gateway management information
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "156",
Description: `Structured Query Language (SQL ( https://en.wikipedia.org/wiki/SQL )) Service
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "158",
Description: `Distributed Mail System Protocol ( https://en.wikipedia.org/w/index.php?title=Distributed_Mail_System_Protocol&action=edit&redlink=1 ) (DMSP, sometimes referred to as Pcmail)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "161",
Description: `Simple Network Management Protocol ( https://en.wikipedia.org/wiki/Simple_Network_Management_Protocol ) (SNMP)
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "162",
Description: `Simple Network Management Protocol ( https://en.wikipedia.org/wiki/Simple_Network_Management_Protocol ) Trap (SNMPTRAP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "170",
Description: `Network PostScript ( https://en.wikipedia.org/wiki/PostScript ) print server ( https://en.wikipedia.org/wiki/Print_server )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "177",
Description: `X Display Manager Control Protocol ( https://en.wikipedia.org/wiki/X_Display_Manager_Control_Protocol ) (XDMCP), used for remote logins to an X Display Manager ( https://en.wikipedia.org/wiki/X_display_manager_(program_type) ) server
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "179",
Description: `Border Gateway Protocol ( https://en.wikipedia.org/wiki/Border_Gateway_Protocol ) (BGP), used to exchange routing and reachability information among autonomous systems ( https://en.wikipedia.org/wiki/Autonomous_system_(Internet) ) (AS) on the Internet ( https://en.wikipedia.org/wiki/Internet )
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Yes
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "194",
Description: `Internet Relay Chat ( https://en.wikipedia.org/wiki/Internet_Relay_Chat ) (IRC)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "199",
Description: `SNMP ( https://en.wikipedia.org/wiki/SNMP ) Unix Multiplexer (SMUX)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "201",
Description: `AppleTalk ( https://en.wikipedia.org/wiki/AppleTalk ) Routing Maintenance
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "209",
Description: `Quick Mail Transfer Protocol ( https://en.wikipedia.org/wiki/Quick_Mail_Transfer_Protocol )
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "210",
Description: `ANSI ( https://en.wikipedia.org/wiki/ANSI ) Z39.50 ( https://en.wikipedia.org/wiki/Z39.50 )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "213",
Description: `Internetwork Packet Exchange ( https://en.wikipedia.org/wiki/Internetwork_Packet_Exchange ) (IPX)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "218",
Description: `Message posting protocol (MPP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "220",
Description: `Internet Message Access Protocol ( https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol ) (IMAP), version 3
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "225-241",
Description: `Unspecified
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "249-255",
Description: `Unspecified
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "259",
Description: `Efficient Short Remote Operations (ESRO)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "262",
Description: `Arcisdms
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "264",
Description: `Border Gateway Multicast Protocol ( https://en.wikipedia.org/wiki/Border_Gateway_Multicast_Protocol ) (BGMP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "280",
Description: `http-mgmt
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "300",
Description: `ThinLinc ( https://en.wikipedia.org/wiki/ThinLinc ) Web Access
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "308",
Description: `Novastor Online Backup
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "311",
Description: `Mac OS X Server ( https://en.wikipedia.org/wiki/Mac_OS_X_Server ) Admin (officially AppleShare ( https://en.wikipedia.org/wiki/AppleShare ) IP Web administration)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "318",
Description: `PKIX Time Stamp Protocol ( https://en.wikipedia.org/wiki/Time_Stamp_Protocol ) (TSP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "319",
Description: `Precision Time Protocol ( https://en.wikipedia.org/wiki/Precision_Time_Protocol ) (PTP) event messages
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "320",
Description: `Precision Time Protocol ( https://en.wikipedia.org/wiki/Precision_Time_Protocol ) (PTP) general messages
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "350",
Description: `Mapping of Airline Traffic over Internet Protocol ( https://en.wikipedia.org/wiki/Mapping_of_Airline_Traffic_over_Internet_Protocol ) (MATIP) type A
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "351",
Description: `MATIP type B
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "356",
Description: `cloanto-net-1 (used by Cloanto Amiga Explorer and VMs)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "366",
Description: `On-Demand Mail Relay (ODMR)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "369",
Description: `Rpc2portmap
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "370",
Description: `codaauth2, Coda authentication server
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
securecast1, outgoing packets to NAI ( https://en.wikipedia.org/wiki/McAfee )'s SecureCast serversAs of 2000[update] ( https://en.wikipedia.org/w/index.php?title=List_of_TCP_and_UDP_port_numbers&action=edit )
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "371",
Description: `ClearCase albd
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "383",
Description: `HP data alarm manager
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "384",
Description: `A Remote Network Server System
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "387",
Description: `AURP (AppleTalk ( https://en.wikipedia.org/wiki/AppleTalk ) Update-based Routing Protocol)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "388",
Description: `Unidata LDM ( https://en.wikipedia.org/wiki/Local_Data_Manager ) near real-time data distribution protocol
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "389",
Description: `Lightweight Directory Access Protocol ( https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol ) (LDAP)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "399",
Description: `Digital Equipment Corporation ( https://en.wikipedia.org/wiki/Digital_Equipment_Corporation ) DECnet+ ( https://en.wikipedia.org/w/index.php?title=DECnet%2B&action=edit&redlink=1 ) (Phase V) over TCP/IP (RFC1859)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "401",
Description: `Uninterruptible power supply ( https://en.wikipedia.org/wiki/Uninterruptible_power_supply ) (UPS)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "427",
Description: `Service Location Protocol ( https://en.wikipedia.org/wiki/Service_Location_Protocol ) (SLP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "433",
Description: `NNSP, part of Network News Transfer Protocol ( https://en.wikipedia.org/wiki/Network_News_Transfer_Protocol )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "434",
Description: `Mobile IP ( https://en.wikipedia.org/wiki/Mobile_IP ) Agent (RFC 5944 ( https://tools.ietf.org/html/rfc5944 ))
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "443",
Description: `Hypertext Transfer Protocol ( https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (HTTPS ( https://en.wikipedia.org/wiki/HTTPS ))
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Yes
Quick UDP Internet Connections ( https://en.wikipedia.org/wiki/QUIC ) (QUIC), a transport protocol over UDP (still in draft as of April 2020[update] ( https://en.wikipedia.org/w/index.php?title=List_of_TCP_and_UDP_port_numbers&action=edit )), using stream multiplexing ( https://en.wikipedia.org/wiki/Multiplexing ), encryption by default with TLS ( https://en.wikipedia.org/wiki/Transport_Layer_Security ), and currently supporting HTTP/2 ( https://en.wikipedia.org/wiki/HTTP/2 ).
IANA Status - Unofficial
TCP - No
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "444",
Description: `Simple Network Paging Protocol ( https://en.wikipedia.org/wiki/Simple_Network_Paging_Protocol ) (SNPP), RFC 1568 ( https://tools.ietf.org/html/rfc1568 )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "445",
Description: `Microsoft-DS (Directory Services) Active Directory ( https://en.wikipedia.org/wiki/Active_Directory ), Windows shares
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
Microsoft-DS (Directory Services) SMB ( https://en.wikipedia.org/wiki/Server_Message_Block ) file sharing
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "464",
Description: `Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) Change/Set password
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "465",
Description: `URL Rendezvous Directory for SSM (Cisco protocol)
IANA Status - Official
TCP - Yes
UDP - No
SCTP - Unspecified
Authenticated SMTP ( https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (SMTPS ( https://en.wikipedia.org/wiki/SMTPS ))
IANA Status - Official
TCP - Yes
UDP - No
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "475",
Description: `tcpnethaspsrv, Aladdin Knowledge Systems ( https://en.wikipedia.org/wiki/Aladdin_Knowledge_Systems ) Hasp services
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "491",
Description: `GO-Global remote access and application publishing software ( https://en.wikipedia.org/wiki/GO-Global )
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "497",
Description: `Retrospect ( https://en.wikipedia.org/wiki/Retrospect_(software) )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "500",
Description: `Internet Security Association and Key Management Protocol ( https://en.wikipedia.org/wiki/Internet_Security_Association_and_Key_Management_Protocol ) (ISAKMP) / Internet Key Exchange ( https://en.wikipedia.org/wiki/Internet_Key_Exchange ) (IKE)
IANA Status - Official
TCP - Assigned
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "502",
Description: `Modbus ( https://en.wikipedia.org/wiki/Modbus ) Protocol
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "504",
Description: `Citadel ( https://en.wikipedia.org/wiki/Citadel/UX ), multiservice protocol for dedicated clients for the Citadel groupware system
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "510",
Description: `FirstClass Protocol (FCP), used by FirstClass ( https://en.wikipedia.org/wiki/FirstClass ) client/server groupware system
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "512",
Description: `Rexec ( https://en.wikipedia.org/wiki/Remote_Process_Execution ), Remote Process Execution
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
comsat, together with biff ( https://en.wikipedia.org/wiki/Biff_(Unix) )
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "513",
Description: `rlogin ( https://en.wikipedia.org/wiki/Rlogin )
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
Who
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "514",
Description: `Remote Shell ( https://en.wikipedia.org/wiki/Remote_Shell ), used to execute non-interactive commands on a remote system (Remote Shell, rsh, remsh)
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
Syslog ( https://en.wikipedia.org/wiki/Syslog ), used for system logging
IANA Status - Official
TCP - No
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "515",
Description: `Line Printer Daemon ( https://en.wikipedia.org/wiki/Line_Printer_Daemon_protocol ) (LPD), print service
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "517",
Description: `Talk
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "518",
Description: `NTalk
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "520",
Description: `efs, extended file name server
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
Routing Information Protocol ( https://en.wikipedia.org/wiki/Routing_Information_Protocol ) (RIP)
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "521",
Description: `Routing Information Protocol Next Generation ( https://en.wikipedia.org/wiki/RIPng ) (RIPng)
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "524",
Description: `NetWare Core Protocol ( https://en.wikipedia.org/wiki/NetWare_Core_Protocol ) (NCP) is used for a variety things such as access to primary NetWare server resources, Time Synchronization, etc.
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "525",
Description: `Timed, Timeserver ( https://en.wikipedia.org/wiki/Timeserver )
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "530",
Description: `Remote procedure call ( https://en.wikipedia.org/wiki/Remote_procedure_call ) (RPC)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "532",
Description: `netnews
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "533",
Description: `netwall, For Emergency Broadcasts
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "540",
Description: `Unix-to-Unix Copy Protocol (UUCP ( https://en.wikipedia.org/wiki/UUCP ))
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "542",
Description: `commerce ( https://en.wikipedia.org/wiki/Commerce ) (Commerce Applications)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "543",
Description: `klogin, Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) login
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "544",
Description: `kshell, Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) Remote shell
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "546",
Description: `DHCPv6 ( https://en.wikipedia.org/wiki/DHCPv6 ) client
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "547",
Description: `DHCPv6 ( https://en.wikipedia.org/wiki/DHCPv6 ) server
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "548",
Description: `Apple Filing Protocol ( https://en.wikipedia.org/wiki/Apple_Filing_Protocol ) (AFP) over TCP ( https://en.wikipedia.org/wiki/Transmission_Control_Protocol )
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "550",
Description: `new-rwho, new-who
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "554",
Description: `Real Time Streaming Protocol ( https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol ) (RTSP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "556",
Description: `Remotefs, RFS ( https://en.wikipedia.org/wiki/Remote_File_System ), rfs_server
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "560",
Description: `rmonitor, Remote Monitor
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "561",
Description: `monitor
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "563",
Description: `NNTP ( https://en.wikipedia.org/wiki/NNTP ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (NNTPS)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "564",
Description: `9P ( https://en.wikipedia.org/wiki/9P_(protocol) ) (Plan 9 ( https://en.wikipedia.org/wiki/Plan_9_from_Bell_Labs ))
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "585",
Description: `Legacy use of Internet Message Access Protocol ( https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (IMAPS), now in use at port 993.
IANA Status - Unofficial
TCP - Port 993
UDP - ?
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "587",
Description: `email message submission ( https://en.wikipedia.org/wiki/Mail_submission_agent ) (SMTP ( https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol ))
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "591",
Description: `FileMaker ( https://en.wikipedia.org/wiki/FileMaker ) 6.0 (and later) Web Sharing (HTTP Alternate, also see port 80)
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "593",
Description: `HTTP RPC Ep Map, Remote procedure call ( https://en.wikipedia.org/wiki/Remote_procedure_call ) over Hypertext Transfer Protocol ( https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol ), often used by Distributed Component Object Model ( https://en.wikipedia.org/wiki/Distributed_Component_Object_Model ) services and Microsoft Exchange Server ( https://en.wikipedia.org/wiki/Microsoft_Exchange_Server )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "601",
Description: `Reliable Syslog ( https://en.wikipedia.org/wiki/Syslog ) Service — used for system logging
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "604",
Description: `TUNNEL profile, a protocol for BEEP ( https://en.wikipedia.org/wiki/BEEP ) peers ( https://en.wikipedia.org/wiki/Peer-to-peer ) to form an application layer ( https://en.wikipedia.org/wiki/Application_layer ) tunnel ( https://en.wikipedia.org/wiki/Tunneling_protocol )
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "623",
Description: `ASF Remote Management and Control Protocol (ASF-RMCP) & IPMI Remote Management Protocol
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "625",
Description: `Open Directory Proxy (ODProxy)
IANA Status - Unofficial
TCP - Yes
UDP - No
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "631",
Description: `Internet Printing Protocol ( https://en.wikipedia.org/wiki/Internet_Printing_Protocol ) (IPP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
Common Unix Printing System ( https://en.wikipedia.org/wiki/Common_Unix_Printing_System ) (CUPS) administration console (extension to IPP)
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "635",
Description: `RLZ DBase
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "636",
Description: `Lightweight Directory Access Protocol ( https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (LDAPS)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "639",
Description: `MSDP, Multicast Source Discovery Protocol ( https://en.wikipedia.org/wiki/Multicast_Source_Discovery_Protocol )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "641",
Description: `SupportSoft Nexus Remote Command (control/listening), a proxy gateway connecting remote control traffic
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "643",
Description: `SANity
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "646",
Description: `Label Distribution Protocol ( https://en.wikipedia.org/wiki/Label_Distribution_Protocol ) (LDP), a routing protocol used in MPLS ( https://en.wikipedia.org/wiki/Multiprotocol_Label_Switching ) networks
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "647",
Description: `DHCP Failover ( https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol#Reliability ) protocol
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "648",
Description: `Registry Registrar Protocol (RRP)
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "651",
Description: `IEEE-MMS
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "653",
Description: `SupportSoft Nexus Remote Command (data), a proxy gateway connecting remote control traffic
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "654",
Description: `Media Management System (MMS) Media Management Protocol (MMP)
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "655",
Description: `Tinc ( https://en.wikipedia.org/wiki/Tinc_(protocol) ) VPN daemon
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "657",
Description: `IBM ( https://en.wikipedia.org/wiki/IBM ) RMC (Remote monitoring and Control) protocol, used by System p5 ( https://en.wikipedia.org/wiki/IBM_System_p ) AIX ( https://en.wikipedia.org/wiki/IBM_AIX ) Integrated Virtualization Manager (IVM) and Hardware Management Console ( https://en.wikipedia.org/wiki/IBM_Hardware_Management_Console ) to connect managed logical partitions (LPAR) ( https://en.wikipedia.org/wiki/LPAR ) to enable dynamic partition reconfiguration
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "660",
Description: `Mac OS X Server ( https://en.wikipedia.org/wiki/Mac_OS_X_Server ) administration, version 10.4 and earlier
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "666",
Description: `Doom ( https://en.wikipedia.org/wiki/Doom_(game) ), first online first-person shooter ( https://en.wikipedia.org/wiki/First-person_shooter )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
airserv-ng ( http://www.aircrack-ng.org/doku.php?id=airserv-ng ), aircrack-ng ( https://en.wikipedia.org/wiki/Aircrack-ng )'s server for remote-controlling wireless devices
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "674",
Description: `Application Configuration Access Protocol ( https://en.wikipedia.org/wiki/Application_Configuration_Access_Protocol ) (ACAP)
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "688",
Description: `REALM-RUSD (ApplianceWare Server Appliance Management Protocol)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "690",
Description: `Velneo Application Transfer Protocol (VATP)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "691",
Description: `MS ( https://en.wikipedia.org/wiki/Microsoft ) Exchange ( https://en.wikipedia.org/wiki/Microsoft_Exchange_Server ) Routing
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "694",
Description: `Linux-HA ( https://en.wikipedia.org/wiki/Linux-HA ) high-availability heartbeat
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "695",
Description: `IEEE ( https://en.wikipedia.org/wiki/IEEE ) Media Management System over SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (IEEE-MMS-SSL)
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "698",
Description: `Optimized Link State Routing ( https://en.wikipedia.org/wiki/Optimized_Link_State_Routing_protocol ) (OLSR)
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "700",
Description: `Extensible Provisioning Protocol ( https://en.wikipedia.org/wiki/Extensible_Provisioning_Protocol ) (EPP), a protocol for communication between domain name registries ( https://en.wikipedia.org/wiki/Domain_name_registry ) and registrars ( https://en.wikipedia.org/wiki/Domain_name_registrar ) (RFC 5734 ( https://tools.ietf.org/html/rfc5734 ))
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "701",
Description: `Link Management Protocol (LMP), a protocol that runs between a pair of nodes ( https://en.wikipedia.org/wiki/Node_(networking) ) and is used to manage traffic engineering ( https://en.wikipedia.org/wiki/Teletraffic_engineering ) (TE) links ( https://en.wikipedia.org/wiki/Telecommunications_link )
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "702",
Description: `IRIS (Internet Registry Information Service) over BEEP ( https://en.wikipedia.org/wiki/BEEP ) (Blocks Extensible Exchange Protocol) (RFC 3983 ( https://tools.ietf.org/html/rfc3983 ))
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "706",
Description: `Secure Internet Live Conferencing ( https://en.wikipedia.org/wiki/SILC_(protocol) ) (SILC)
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "711",
Description: `Cisco ( https://en.wikipedia.org/wiki/Cisco ) Tag Distribution Protocol—being replaced by the MPLS Label Distribution Protocol ( https://en.wikipedia.org/wiki/Label_Distribution_Protocol )
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "712",
Description: `Topology Broadcast based on Reverse-Path Forwarding routing protocol ( https://en.wikipedia.org/wiki/Topology_Broadcast_based_on_Reverse-Path_Forwarding_routing_protocol ) (TBRPF; RFC 3684 ( https://tools.ietf.org/html/rfc3684 ))
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "749",
Description: `Kerberos (protocol) ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) administration
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "750",
Description: `kerberos-iv, Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) version IV
IANA Status - Official
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "751",
Description: `kerberos_master, Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) authentication
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "752",
Description: `passwd_server, Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) password (kpasswd) server
IANA Status - Unofficial
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "753",
Description: `Reverse Routing Header (RRH)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
userreg_server, Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) userreg server
IANA Status - Unofficial
TCP - Unspecified
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "754",
Description: `tell send
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
krb5_prop, Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) v5 slave propagation
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "760",
Description: `krbupdate [kreg], Kerberos ( https://en.wikipedia.org/wiki/Kerberos_(protocol) ) registration
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "782",
Description: `Conserver ( https://en.wikipedia.org/wiki/Conserver ) serial-console management server
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "783",
Description: `SpamAssassin ( https://en.wikipedia.org/wiki/SpamAssassin ) spamd daemon
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "800",
Description: `mdbs-daemon
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "802",
Description: `MODBUS ( https://en.wikipedia.org/wiki/Modbus )/TCP Security
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "808",
Description: `Microsoft Net.TCP Port Sharing Service
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "829",
Description: `Certificate Management Protocol ( https://en.wikipedia.org/wiki/Certificate_Management_Protocol )
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "830",
Description: `NETCONF ( https://en.wikipedia.org/wiki/NETCONF ) over SSH ( https://en.wikipedia.org/wiki/Secure_Shell )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "831",
Description: `NETCONF over BEEP ( https://en.wikipedia.org/wiki/BEEP )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "832",
Description: `NETCONF for SOAP ( https://en.wikipedia.org/wiki/SOAP ) over HTTPS ( https://en.wikipedia.org/wiki/HTTPS )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "833",
Description: `NETCONF for SOAP over BEEP ( https://en.wikipedia.org/wiki/BEEP )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "843",
Description: `Adobe Flash ( https://en.wikipedia.org/wiki/Adobe_Flash )
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "847",
Description: `DHCP Failover ( https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol#Reliability ) protocol
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "848",
Description: `Group Domain Of Interpretation (GDOI) protocol
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "853",
Description: `DNS ( https://en.wikipedia.org/wiki/Domain_Name_System ) over TLS ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (RFC 7858 ( https://tools.ietf.org/html/rfc7858 ))
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "860",
Description: `iSCSI ( https://en.wikipedia.org/wiki/ISCSI ) (RFC 3720 ( https://tools.ietf.org/html/rfc3720 ))
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "861",
Description: `OWAMP control (RFC 4656 ( https://tools.ietf.org/html/rfc4656 ))
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "862",
Description: `TWAMP control (RFC 5357 ( https://tools.ietf.org/html/rfc5357 ))
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "873",
Description: `rsync ( https://en.wikipedia.org/wiki/Rsync ) file synchronization protocol
IANA Status - Official
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "888",
Description: `cddbp, CD DataBase ( https://en.wikipedia.org/wiki/CD_database ) (CDDB ( https://en.wikipedia.org/wiki/CDDB )) protocol (CDDBP)
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
IBM Endpoint Manager Remote Control
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "897",
Description: `Brocade ( https://en.wikipedia.org/wiki/Brocade_Communications_Systems ) SMI-S RPC
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "898",
Description: `Brocade SMI-S RPC SSL
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "902",
Description: `VMware ESXi ( https://en.wikipedia.org/wiki/VMware_ESXi )
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "903",
Description: `VMware ESXi
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "953",
Description: `BIND ( https://en.wikipedia.org/wiki/BIND ) remote name daemon control (RNDC)
IANA Status - Official
TCP - Yes
UDP - Reserved
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "981",
Description: `Remote HTTPS management for firewall devices running embedded Check Point VPN-1 ( https://en.wikipedia.org/wiki/Check_Point_VPN-1 ) software
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "987",
Description: `Microsoft Remote Web Workplace ( https://en.wikipedia.org/wiki/Microsoft_Remote_Web_Workplace ), a feature of Windows Small Business Server ( https://en.wikipedia.org/wiki/Windows_Small_Business_Server )
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "989",
Description: `FTPS ( https://en.wikipedia.org/wiki/FTPS ) Protocol (data), FTP ( https://en.wikipedia.org/wiki/FTP ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "990",
Description: `FTPS ( https://en.wikipedia.org/wiki/FTPS ) Protocol (control), FTP ( https://en.wikipedia.org/wiki/FTP ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "991",
Description: `Netnews ( https://en.wikipedia.org/wiki/Netnews ) Administration System (NAS)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "992",
Description: `Telnet ( https://en.wikipedia.org/wiki/Telnet ) protocol over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security )
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "993",
Description: `Internet Message Access Protocol ( https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (IMAPS)
IANA Status - Official
TCP - Yes
UDP - Assigned
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "994",
Description: `Unspecified
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
Internet Relay Chat ( https://en.wikipedia.org/wiki/Internet_Relay_Chat ) over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (IRCS). Previously assigned, but not used in common practice.
IANA Status - Unofficial
TCP - Maybe
UDP - Maybe
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "995",
Description: `Post Office Protocol ( https://en.wikipedia.org/wiki/Post_Office_Protocol ) 3 over TLS/SSL ( https://en.wikipedia.org/wiki/Transport_Layer_Security ) (POP3S)
IANA Status - Official
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "1010",
Description: `ThinLinc ( https://en.wikipedia.org/wiki/ThinLinc ) web-based administration interface
IANA Status - Unofficial
TCP - Yes
UDP - Unspecified
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "1011-1020",
Description: `Unspecified
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
{
Name: "1023",
Description: `''
IANA Status - Official
TCP - Reserved
UDP - Reserved
SCTP - Unspecified
z/OS ( https://en.wikipedia.org/wiki/Z/OS ) Network File System (NFS) (potentially ports 991-1023)
IANA Status - Unofficial
TCP - Yes
UDP - Yes
SCTP - Unspecified
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports`,
},
} | well-known-ports.go | 0.802168 | 0.553686 | well-known-ports.go | starcoder |
package main
import (
"math"
)
type Texture interface {
ApplyAtHit(ii *IntersectionInfo)
}
type Pattern interface {
Transformable
Texture
PatternAt(point Tuple) Color
ColorAt(object Patternable, point Tuple) Color
}
type LocalPatternAt func(point Tuple) Color
type BasicPattern struct {
Transformer
LocalPatternAt LocalPatternAt
}
type ProxyPattern struct {
P Pattern
O Patternable
}
func NewProxyPattern(object Patternable, pattern Pattern) (p Pattern) {
if pattern != nil {
p = &ProxyPattern{O: object, P: pattern}
}
return p
}
func (p *ProxyPattern) SetTransform(transforms ...Matrix) {
p.P.SetTransform(transforms...)
}
func (p *ProxyPattern) Transform() Matrix {
return p.P.Transform()
}
func (p *ProxyPattern) InverseTransform() Matrix {
return p.P.InverseTransform()
}
func (p *ProxyPattern) PatternAt(point Tuple) Color {
return p.P.PatternAt(point)
}
func (p *ProxyPattern) ColorAt(object Patternable, point Tuple) Color {
return p.P.ColorAt(p.O, point)
}
func (p *ProxyPattern) ApplyAtHit(ii *IntersectionInfo) {
ii.Mat.DiffuseColor = p.P.ColorAt(ii.O, ii.Point)
}
func NewBasicPattern(localPatternAt LocalPatternAt) Pattern {
p := &BasicPattern{LocalPatternAt: localPatternAt}
p.SetTransform()
return p
}
func (p *BasicPattern) PatternAt(point Tuple) Color {
return p.LocalPatternAt(point)
}
func (p *BasicPattern) ColorAt(object Patternable, point Tuple) Color {
objectPoint := object.WorldToObject(point) // Convert from world to object space
patternPoint := p.Tinverse.MulT(objectPoint) // Convert from object to pattern space
return p.LocalPatternAt(patternPoint)
}
func (p *BasicPattern) ApplyAtHit(ii *IntersectionInfo) {
ii.Mat.DiffuseColor = p.ColorAt(ii.O, ii.Point)
}
func NewSolidColorPattern(c Color) Pattern {
return NewBasicPattern(func(point Tuple) Color {
return c
})
}
func NewStripePattern(a, b Color) Pattern {
c := [2]Color{a, b}
return NewBasicPattern(func(point Tuple) Color {
return c[uint(math.Floor(point.X))%2]
})
}
func NewCheckerPattern(a, b Color) Pattern {
c := [2]Color{a, b}
return NewBasicPattern(func(point Tuple) Color {
return c[uint(math.Floor(point.X)+math.Floor(point.Y)+math.Floor(point.Z))%2]
})
}
func NewGradientPattern(a, b Color) Pattern {
return NewBasicPattern(func(point Tuple) Color {
return a.Add((b.Sub(a)).Mul(point.X - math.Floor(point.X)))
})
}
func NewBlendedPattern(patterns ...Pattern) Pattern {
return NewBasicPattern(func(point Tuple) Color {
c := Black
for _, p := range patterns {
c = c.Add(p.PatternAt(point))
}
return c
})
}
func NewPointPattern() Pattern { // Used mainly for test: returns the point coordinates as a color
return NewBasicPattern(func(point Tuple) Color {
return RGB(point.X, point.Y, point.Z)
})
}
func NewPerlinNoisePattern(a, b Color, interpolators ...Interpolator) Pattern {
pn := NewPerlinNoise()
return NewBasicPattern(func(point Tuple) Color {
noise := pn.at(point.X, point.Y, point.Z)
noise = (noise + 1) / 2 // Perlin noise is in the [-1,+1] range, take it to [0,1]
for _, interp := range interpolators {
noise = interp(noise)
}
return a.Gradient(b, noise)
})
} | pattern.go | 0.85984 | 0.546133 | pattern.go | starcoder |
package pricecalculator
import (
ec "github.com/mjah/price-calculator/server/errors"
)
// PriceCalculator stores the price, costs, and fees
type PriceCalculator struct {
SellPrice float64 `json:"sell_price"`
FreeDeliveryPrice float64 `json:"free_delivery_price"`
Cost float64 `json:"cost"`
Fees struct {
SalesTax struct {
Rate float64 `json:"rate"`
} `json:"sales_tax"`
Payment struct {
Rate float64 `json:"rate"`
Fixed float64 `json:"fixed"`
} `json:"payment"`
Channel struct {
Rate float64 `json:"rate"`
Fixed float64 `json:"fixed"`
IsCapped bool `json:"is_capped"`
CappedValue float64 `json:"capped_value"`
} `json:"channel"`
Other struct {
Rate float64 `json:"rate"`
Fixed float64 `json:"fixed"`
} `json:"other"`
} `json:"fees"`
Profit struct {
Rate float64 `json:"rate"`
} `json:"profit"`
}
// New creates and returns a new instance of PriceCalculator
func New() *PriceCalculator {
return &PriceCalculator{}
}
// GetSellPriceByProfitRate calculates and returns the sell price given the profit rate
func (pc *PriceCalculator) GetSellPriceByProfitRate() (float64, error) {
numerator := pc.Cost
numerator += pc.FreeDeliveryPrice
numerator += pc.Fees.Payment.Fixed
numerator += pc.Fees.Channel.Fixed
numerator += pc.Fees.Other.Fixed
denominator := (1 / (1 + pc.Fees.SalesTax.Rate))
denominator -= pc.Fees.Payment.Rate
denominator -= pc.Fees.Channel.Rate
denominator -= pc.Fees.Other.Rate
denominator -= pc.Profit.Rate
sellPriceUncappedFees := numerator / denominator
if !pc.Fees.Channel.IsCapped || pc.Fees.Channel.CappedValue == 0 {
if denominator <= 0 {
err := ec.New(ec.NegDenUncappedFees, "Negative denomiator with uncapped fees.")
return 0, err
}
return sellPriceUncappedFees, nil
} else if denominator+pc.Fees.Channel.Rate <= 0 {
err := ec.New(ec.NegDenCappedFees, "Negative denominator with capped fees.")
return 0, err
}
channelFees := sellPriceUncappedFees*pc.Fees.Channel.Rate + pc.Fees.Channel.Fixed
if channelFees < pc.Fees.Channel.Fixed || channelFees > pc.Fees.Channel.CappedValue {
channelFees = pc.Fees.Channel.CappedValue
}
sellPriceCappedFees := (numerator + channelFees) / (denominator + pc.Fees.Channel.Rate)
return sellPriceCappedFees, nil
}
// GetFeesTotal calculates and returns the total fees
func (pc *PriceCalculator) GetFeesTotal() float64 {
feesTotal := pc.GetSalesTaxFeesTotal()
feesTotal += pc.GetChannelFeesTotal()
feesTotal += pc.GetPaymentFeesTotal()
feesTotal += pc.GetOtherFeesTotal()
return feesTotal
}
// GetSalesTaxFeesTotal calculates and returns the sales tax
func (pc *PriceCalculator) GetSalesTaxFeesTotal() float64 {
return pc.SellPrice * (1 - (1 / (1 + pc.Fees.SalesTax.Rate)))
}
// GetPaymentFeesTotal calculates and returns the payments fees
func (pc *PriceCalculator) GetPaymentFeesTotal() float64 {
return pc.SellPrice*pc.Fees.Payment.Rate + pc.Fees.Payment.Fixed
}
// GetChannelFeesTotal calculates and returns the channel fees
func (pc *PriceCalculator) GetChannelFeesTotal() float64 {
channelFeesUncapped := pc.SellPrice*pc.Fees.Channel.Rate + pc.Fees.Channel.Fixed
channelFees := channelFeesUncapped
if pc.Fees.Channel.IsCapped &&
pc.Fees.Channel.CappedValue != 0 &&
channelFeesUncapped > pc.Fees.Channel.CappedValue {
channelFees = pc.Fees.Channel.CappedValue
}
return channelFees
}
// GetOtherFeesTotal calculates and returns the other fees
func (pc *PriceCalculator) GetOtherFeesTotal() float64 {
return pc.SellPrice*pc.Fees.Other.Rate + pc.Fees.Other.Fixed
}
// GetProfitTotal calculates and returns the profit total
func (pc *PriceCalculator) GetProfitTotal() float64 {
profitTotal := pc.SellPrice
profitTotal -= pc.GetFeesTotal()
profitTotal -= pc.Cost
profitTotal -= pc.FreeDeliveryPrice
return profitTotal
}
// IsValidProfitRate checks if the profit rate is valid
func (pc *PriceCalculator) IsValidProfitRate() bool {
denominator := (1 / (1 + pc.Fees.SalesTax.Rate))
denominator -= pc.Fees.Payment.Rate
denominator -= pc.Fees.Channel.Rate
denominator -= pc.Fees.Other.Rate
denominator -= pc.Profit.Rate
if !pc.Fees.Channel.IsCapped || pc.Fees.Channel.CappedValue == 0 {
if denominator <= 0 {
return false
}
} else if denominator+pc.Fees.Channel.Rate <= 0 {
return false
}
return true
} | server/pricecalculator/pricecalculator.go | 0.839504 | 0.433921 | pricecalculator.go | starcoder |
package element
func (e Element) AriaAtomic() (string, error) {
return e.GetAttributeString("ariaAtomic")
}
func (e Element) SetAriaAtomic(value string) error {
return e.SetAttributeString("ariaAtomic", value)
}
func (e Element) AriaAutoComplete() (string, error) {
return e.GetAttributeString("ariaAutoComplete")
}
func (e Element) SetAriaAutoComplete(value string) error {
return e.SetAttributeString("ariaAutoComplete", value)
}
func (e Element) AriaBusy() (string, error) {
return e.GetAttributeString("ariaBusy")
}
func (e Element) SetAriaBusy(value string) error {
return e.SetAttributeString("ariaBusy", value)
}
func (e Element) AriaChecked() (string, error) {
return e.GetAttributeString("ariaChecked")
}
func (e Element) SetAriaChecked(value string) error {
return e.SetAttributeString("ariaChecked", value)
}
func (e Element) AriaColCount() (string, error) {
return e.GetAttributeString("ariaColCount")
}
func (e Element) SetAriaColCount(value string) error {
return e.SetAttributeString("ariaColCount", value)
}
func (e Element) AriaColIndex() (string, error) {
return e.GetAttributeString("ariaColIndex")
}
func (e Element) SetAriaColIndex(value string) error {
return e.SetAttributeString("ariaColIndex", value)
}
func (e Element) AriaColIndexText() (string, error) {
return e.GetAttributeString("ariaColIndexText")
}
func (e Element) SetAriaColIndexText(value string) error {
return e.SetAttributeString("ariaColIndexText", value)
}
func (e Element) AriaColSpan() (string, error) {
return e.GetAttributeString("ariaColSpan")
}
func (e Element) SetAriaColSpan(value string) error {
return e.SetAttributeString("ariaColSpan", value)
}
func (e Element) AriaCurrent() (string, error) {
return e.GetAttributeString("ariaCurrent")
}
func (e Element) SetAriaCurrent(value string) error {
return e.SetAttributeString("ariaCurrent", value)
}
func (e Element) AriaDescription() (string, error) {
return e.GetAttributeString("ariaDescription")
}
func (e Element) SetAriaDescription(value string) error {
return e.SetAttributeString("ariaDescription", value)
}
func (e Element) AriaDisabled() (string, error) {
return e.GetAttributeString("ariaDisabled")
}
func (e Element) SetAriaDisabled(value string) error {
return e.SetAttributeString("ariaDisabled", value)
}
func (e Element) AriaExpanded() (string, error) {
return e.GetAttributeString("ariaExpanded")
}
func (e Element) SetAriaExpanded(value string) error {
return e.SetAttributeString("ariaExpanded", value)
}
func (e Element) AriaHasPopup() (string, error) {
return e.GetAttributeString("ariaHasPopup")
}
func (e Element) SetAriaHasPopup(value string) error {
return e.SetAttributeString("ariaHasPopup", value)
}
func (e Element) AriaHidden() (string, error) {
return e.GetAttributeString("ariaHidden")
}
func (e Element) SetAriaHidden(value string) error {
return e.SetAttributeString("ariaHidden", value)
}
func (e Element) AriaKeyShortcuts() (string, error) {
return e.GetAttributeString("ariaKeyShortcuts")
}
func (e Element) SetAriaKeyShortcuts(value string) error {
return e.SetAttributeString("ariaKeyShortcuts", value)
}
func (e Element) AriaLabel() (string, error) {
return e.GetAttributeString("ariaLabel")
}
func (e Element) SetAriaLabel(value string) error {
return e.SetAttributeString("ariaLabel", value)
}
func (e Element) AriaLevel() (string, error) {
return e.GetAttributeString("ariaLevel")
}
func (e Element) SetAriaLevel(value string) error {
return e.SetAttributeString("ariaLevel", value)
}
func (e Element) AriaLive() (string, error) {
return e.GetAttributeString("ariaLive")
}
func (e Element) SetAriaLive(value string) error {
return e.SetAttributeString("ariaLive", value)
}
func (e Element) AriaModal() (string, error) {
return e.GetAttributeString("ariaModal")
}
func (e Element) SetAriaModal(value string) error {
return e.SetAttributeString("ariaModal", value)
}
func (e Element) AriaMultiline() (string, error) {
return e.GetAttributeString("ariaMultiline")
}
func (e Element) SetAriaMultiline(value string) error {
return e.SetAttributeString("ariaMultiline", value)
}
func (e Element) AriaMultiSelectable() (string, error) {
return e.GetAttributeString("ariaMultiSelectable")
}
func (e Element) SetAriaMultiSelectable(value string) error {
return e.SetAttributeString("ariaMultiSelectable", value)
}
func (e Element) AriaOrientation() (string, error) {
return e.GetAttributeString("ariaOrientation")
}
func (e Element) SetAriaOrientation(value string) error {
return e.SetAttributeString("ariaOrientation", value)
}
func (e Element) AriaPlaceholder() (string, error) {
return e.GetAttributeString("ariaPlaceholder")
}
func (e Element) SetAriaPlaceholder(value string) error {
return e.SetAttributeString("ariaPlaceholder", value)
}
func (e Element) AriaPosInSet() (string, error) {
return e.GetAttributeString("ariaPosInSet")
}
func (e Element) SetAriaPosInSet(value string) error {
return e.SetAttributeString("ariaPosInSet", value)
}
func (e Element) AriaPressed() (string, error) {
return e.GetAttributeString("ariaPressed")
}
func (e Element) SetAriaPressed(value string) error {
return e.SetAttributeString("ariaPressed", value)
}
func (e Element) AriaReadOnly() (string, error) {
return e.GetAttributeString("ariaReadOnly")
}
func (e Element) SetAriaReadOnly(value string) error {
return e.SetAttributeString("ariaReadOnly", value)
}
func (e Element) AriaRelevant() (string, error) {
return e.GetAttributeString("ariaRelevant")
}
func (e Element) SetAriaRelevant(value string) error {
return e.SetAttributeString("ariaRelevant", value)
}
func (e Element) AriaRequired() (string, error) {
return e.GetAttributeString("ariaRequired")
}
func (e Element) SetAriaRequired(value string) error {
return e.SetAttributeString("ariaRequired", value)
}
func (e Element) AriaRoleDescription() (string, error) {
return e.GetAttributeString("ariaRoleDescription")
}
func (e Element) SetAriaRoleDescription(value string) error {
return e.SetAttributeString("ariaRoleDescription", value)
}
func (e Element) AriaRowCount() (string, error) {
return e.GetAttributeString("ariaRowCount")
}
func (e Element) SetAriaRowCount(value string) error {
return e.SetAttributeString("ariaRowCount", value)
}
func (e Element) AriaRowIndex() (string, error) {
return e.GetAttributeString("ariaRowIndex")
}
func (e Element) SetAriaRowIndex(value string) error {
return e.SetAttributeString("ariaRowIndex", value)
}
func (e Element) AriaRowIndexText() (string, error) {
return e.GetAttributeString("ariaRowIndexText")
}
func (e Element) SetAriaRowIndexText(value string) error {
return e.SetAttributeString("ariaRowIndexText", value)
}
func (e Element) AriaRowSpan() (string, error) {
return e.GetAttributeString("ariaRowSpan")
}
func (e Element) SetAriaRowSpan(value string) error {
return e.SetAttributeString("ariaRowSpan", value)
}
func (e Element) AriaSelected() (string, error) {
return e.GetAttributeString("ariaSelected")
}
func (e Element) SetAriaSelected(value string) error {
return e.SetAttributeString("ariaSelected", value)
}
func (e Element) AriaSetSize() (string, error) {
return e.GetAttributeString("ariaSetSize")
}
func (e Element) SetAriaSetSize(value string) error {
return e.SetAttributeString("ariaSetSize", value)
}
func (e Element) AriaSort() (string, error) {
return e.GetAttributeString("ariaSort")
}
func (e Element) SetAriaSort(value string) error {
return e.SetAttributeString("ariaSort", value)
}
func (e Element) AriaValueMax() (string, error) {
return e.GetAttributeString("ariaValueMax")
}
func (e Element) SetAriaValueMax(value string) error {
return e.SetAttributeString("ariaValueMax", value)
}
func (e Element) AriaValueMin() (string, error) {
return e.GetAttributeString("ariaValueMin")
}
func (e Element) SetAriaValueMin(value string) error {
return e.SetAttributeString("ariaValueMin", value)
}
func (e Element) AriaValueNow() (string, error) {
return e.GetAttributeString("ariaValueNow")
}
func (e Element) SetAriaValueNow(value string) error {
return e.SetAttributeString("ariaValueNow", value)
}
func (e Element) AriaValueText() (string, error) {
return e.GetAttributeString("ariaValueText")
}
func (e Element) SetAriaValueText(value string) error {
return e.SetAttributeString("ariaValueText", value)
} | element/accessibility.go | 0.761627 | 0.625038 | accessibility.go | starcoder |
package lshtree
import (
"errors"
"github.com/justinfargnoli/lshforest/pkg/hash"
)
// Trie is a prefix tree which uses a Element.hash, a []Bit, to determine the
// elements prefix
type Trie struct {
root *Node
}
// NewTrie constructs an empty Trie
func NewTrie() Trie {
return Trie{}
}
// Preorder performs a preorder traversal of the tree
func (t Trie) Preorder(function func(*Node)) {
if t.root != nil {
t.root.preorder(function)
}
}
// Postorder performs a postorder traversal of the tree
func (t Trie) Postorder(function func(*Node)) {
if t.root != nil {
t.root.postorder(function)
}
}
// Inorder performs a inorder traversal of the tree
func (t Trie) Inorder(function func(*Node)) {
if t.root != nil {
t.root.inorder(function)
}
}
// Insert adds an element to the tire
func (t *Trie) Insert(element Element) error {
if element.hash == nil {
return errors.New("element.hash == nil")
}
if t.root == nil {
t.root = &Node{Elements: []Element{element}}
} else {
t.root.insert(element, 0)
}
return nil
}
// Descend returns the leaf with the larges prefix matching hash
func (t *Trie) Descend(hash *[]hash.Bit) (*Node, uint) {
if hash == nil {
panic("lshforest/lshtree/Trie Trie.Descend()")
}
if t.root == nil {
return nil, 0
}
return t.root.descend(hash, 0)
}
// Get returns elements with equal hash values
func (t *Trie) Get(hash *[]hash.Bit) *[]Element {
if hash == nil {
panic("lshforest/lshtree/Trie Trie.Get()")
}
if t.root == nil {
return &[]Element{}
}
return t.root.get(hash, 0)
}
const (
left = 0
right = 1
)
// Node is a node in the Trie
type Node struct {
Elements []Element
left, right, Parent *Node
}
func (n *Node) isInternal() bool {
return n.left != nil || n.right != nil
}
func (n *Node) isLeaf() bool {
return n.left == nil && n.right == nil && len(n.Elements) == 1
}
func (n *Node) isLeafBucket() bool {
return n.left == nil && n.right == nil && len(n.Elements) >= 1
}
// Decendants returns the children of the node
func (n *Node) Decendants() []*Node {
var nodes []*Node
if n.left != nil {
n.left.preorder(func(node *Node) {
nodes = append(nodes, node)
})
}
if n.right != nil {
n.right.preorder(func(node *Node) {
nodes = append(nodes, node)
})
}
return nodes
}
func (n *Node) preorder(function func(*Node)) {
function(n)
if n.left != nil {
n.left.preorder(function)
}
if n.right != nil {
n.right.preorder(function)
}
}
func (n *Node) postorder(function func(*Node)) {
if n.left != nil {
n.left.postorder(function)
}
if n.right != nil {
n.right.postorder(function)
}
function(n)
}
func (n *Node) inorder(function func(*Node)) {
if n.left != nil {
n.left.inorder(function)
}
function(n)
if n.right != nil {
n.right.inorder(function)
}
}
func (n *Node) descend(hash *[]hash.Bit, depth uint) (*Node, uint) {
if n.isInternal() {
if (*hash)[depth] == left {
if n.left == nil {
return n.right.descend(hash, depth+1)
}
return n.left.descend(hash, depth+1)
}
if n.right == nil {
return n.left.descend(hash, depth+1)
}
return n.right.descend(hash, depth+1)
}
return n, depth
}
func (n *Node) get(hash *[]hash.Bit, depth uint) *[]Element {
if n.isInternal() {
if (*hash)[depth] == left {
if n.left == nil {
return &[]Element{}
}
return n.left.get(hash, depth+1)
}
if n.right == nil {
return &[]Element{}
}
return n.right.get(hash, depth+1)
}
return &n.Elements
}
func (n *Node) insert(element Element, depth uint) {
if n.isInternal() {
if (*element.hash)[depth] == left {
if n.left == nil {
n.left = &Node{Elements: []Element{element}, Parent: n}
} else {
n.left.insert(element, depth+1)
}
} else {
if n.right == nil {
n.right = &Node{Elements: []Element{element}, Parent: n}
} else {
n.right.insert(element, depth+1)
}
}
} else if n.isLeaf() {
if depth == uint(len(*element.hash)) {
n.Elements = append(n.Elements, element)
return
}
if (*element.hash)[depth] == (*n.Elements[0].hash)[depth] { // they're going the same way
if (*element.hash)[depth] == left { // they're going left
n.left = &Node{Parent: n, Elements: n.Elements}
n.Elements = []Element{}
n.left.insert(element, depth+1)
} else { // they're going right
n.right = &Node{Parent: n, Elements: n.Elements}
n.Elements = []Element{}
n.right.insert(element, depth+1)
}
} else { // they're going different ways
if (*element.hash)[depth] == left { // element goes left & node goes right
n.left = &Node{Parent: n, Elements: []Element{element}}
n.right = &Node{Parent: n, Elements: n.Elements}
n.Elements = []Element{}
} else { // node goes left & element goes right
n.left = &Node{Parent: n, Elements: n.Elements}
n.right = &Node{Parent: n, Elements: []Element{element}}
n.Elements = []Element{}
}
}
} else {
n.Elements = append(n.Elements, element)
}
} | pkg/lshtree/trie.go | 0.71423 | 0.476092 | trie.go | starcoder |
package parser
import (
"regexp"
"strconv"
"strings"
)
var nDashDigitRe = regexp.MustCompile("^n(-[0-9]+)$")
// Parse `<An+B> <http://dev.w3.org/csswg/css-syntax-3/#anb>`_,
// as found in `:nth-child()
// <http://dev.w3.org/csswg/selectors/#nth-child-pseudo>`
// and related Selector pseudo-classes.
// Although tinycss2 does not include a full Selector parser,
// this bit of syntax is included as it is particularly tricky to define
// on top of a CSS tokenizer.
// Returns [a, b] or nil
func ParseNth(input []Token) *[2]int {
tokens := NewTokenIterator(input)
token_ := nextSignificant(tokens)
if token_ == nil {
return nil
}
switch token := token_.(type) {
case NumberToken:
if token.IsInteger {
return parseEnd(tokens, 0, token.IntValue())
}
case DimensionToken:
if token.IsInteger {
unit := token.Unit.Lower()
if unit == "n" {
return parseB(tokens, token.IntValue())
} else if unit == "n-" {
return parseSignlessB(tokens, token.IntValue(), -1)
} else {
if match, b := matchInt(unit); match {
return parseEnd(tokens, token.IntValue(), b)
}
}
}
case IdentToken:
ident := token.Value.Lower()
if ident == "even" {
return parseEnd(tokens, 2, 0)
} else if ident == "odd" {
return parseEnd(tokens, 2, 1)
} else if ident == "n" {
return parseB(tokens, 1)
} else if ident == "-n" {
return parseB(tokens, -1)
} else if ident == "n-" {
return parseSignlessB(tokens, 1, -1)
} else if ident == "-n-" {
return parseSignlessB(tokens, -1, -1)
} else if ident[0] == '-' {
if match, b := matchInt(ident[1:]); match {
return parseEnd(tokens, -1, b)
}
} else {
if match, b := matchInt(ident); match {
return parseEnd(tokens, 1, b)
}
}
case LiteralToken:
if token.Value == "+" {
token_ = tokens.Next() // Whitespace after an initial "+" is invalid.
if identToken, ok := token_.(IdentToken); ok {
ident := identToken.Value.Lower()
if ident == "n" {
return parseB(tokens, 1)
} else if ident == "n-" {
return parseSignlessB(tokens, 1, -1)
} else {
if match, b := matchInt(ident); match {
return parseEnd(tokens, 1, b)
}
}
}
}
}
return nil
}
func matchInt(s string) (bool, int) {
match := nDashDigitRe.FindStringSubmatch(s)
if len(match) > 0 {
if out, err := strconv.Atoi(match[1]); err == nil {
return true, out
}
}
return false, 0
}
func parseB(tokens *TokenIterator, a int) *[2]int {
token := nextSignificant(tokens)
if token == nil {
return &[2]int{a, 0}
}
lit, ok := token.(LiteralToken)
if ok && lit.Value == "+" {
return parseSignlessB(tokens, a, 1)
} else if ok && lit.Value == "-" {
return parseSignlessB(tokens, a, -1)
}
if number, ok := token.(NumberToken); ok && number.IsInteger && strings.Contains("-+", number.Representation[0:1]) {
return parseEnd(tokens, a, number.IntValue())
}
return nil
}
func parseSignlessB(tokens *TokenIterator, a, bSign int) *[2]int {
token := nextSignificant(tokens)
if number, ok := token.(NumberToken); ok && number.IsInteger && !strings.Contains("-+", number.Representation[0:1]) {
return parseEnd(tokens, a, bSign*number.IntValue())
}
return nil
}
func parseEnd(tokens *TokenIterator, a, b int) *[2]int {
if nextSignificant(tokens) == nil {
return &[2]int{a, b}
}
return nil
} | css/parser/nth.go | 0.636127 | 0.419232 | nth.go | starcoder |
// Animation inspired by http://blog.golang.org/concurrency-is-not-parallelism.
// Gopher logo by <NAME>. The design is licensed under the Creative Commons 3.0 Attributions license.
// For more details see http://blog.golang.org/gopher.
package main
import (
"math/rand"
"strings"
"time"
"github.com/gopherjs/gopherjs/js"
)
func main() {
Start()
}
// the globals below are inspected by the GopherJS interface code below to move and change sprites to create the animation
var bigpile, smallpile, oven chan int
var Sprite1X, Sprite1Y, Sprite2X, Sprite2Y float64
var Sprite1state, Sprite2state int
const ( // constants for the state of a gopher, also used by Haxe code
Pick = iota
Full
Shovel
Empty
)
// This function is called to set-off the gophers
func startGophers() {
bigpile = make(chan int)
smallpile = make(chan int, 1) // len() does not work in GopherJS without a length of 1
oven = make(chan int)
// now start off the two gophers
go gopher(&Sprite1X, &Sprite1Y, &Sprite1state, bigpile, smallpile)
go gopher(&Sprite2X, &Sprite2Y, &Sprite2state, smallpile, oven)
go fire() // burn everything that arrives!
bigpile <- 1 // start low, so that left-hand gopher moves fast
smallpile <- 10 // start high, so that right-hand gopher moves slow
go fillbigpile() // keep adding randomly to the big pile
}
func fillbigpile() {
for {
bigpile <- rand.Intn(9) + 1
Gosched()
}
}
func fire() {
for {
<-oven
Gosched()
}
}
// an individual gopher, animated with logos by the GopherJS code
func gopher(x, y *float64, state *int, in, out chan int) {
for {
cartLoad := pickBooks(x, y, state, in)
pushBooks(x, y, state, cartLoad)
fireBooks(x, y, state, cartLoad, out)
moreBooks(x, y, state)
}
}
func pickBooks(x, y *float64, state *int, in chan int) int {
*state = Pick
*x = 0
v := <-in
loop(v) // spend longer picking some loads and putting them on the cart
return v
}
func pushBooks(x, y *float64, state *int, cartLoad int) {
*state = Full
for *x = 0.0; *x < 150.0; (*x) += 10.0 / float64(cartLoad) {
if *y > 0.0 { // create bumps in the road
*y = 0.0
} else {
*y = float64(rand.Intn(3)) // random small bumps
}
Gosched() // without this, the animation would not show each state
}
if *x > 150.0 { // constrain large x offsets
*x = 150.0
}
*y = 0.0
}
func fireBooks(x, y *float64, state *int, cartLoad int, out chan int) {
*state = Shovel
loop(cartLoad) // spend longer unloading some loads into the fire
out <- cartLoad
}
func moreBooks(x, y *float64, state *int) {
*state = Empty
for *x > 0.0 {
*x -= 10.0
if *x < 0.0 { // no -ve x offsets please
*x = 0.0
}
if *y > 0.0 { // create bumps in the road
*y = 0.0
} else {
*y = float64(rand.Intn(5)) // random bigger bumps
}
Gosched() // would not show state without this, the animation would jump.
}
*y = 0.0
}
func loop(n int) { // add some delay when required
for n > 0 {
n--
Gosched() // give up control in order to show the gopher waiting
}
}
/**** JS interface code ****/
var Books, Logo1, Logo2, Sprite1, Sprite2 *Sprite
const (
s1x = 90
s1y = 45
s2x = 420
s2y = 45
)
func makeText(selectable bool, x, y, width, height, textColor int, text string) js.Object {
context.Set("font", "12px Arial")
ss := strings.Split(text, "\n")
for k, v := range ss {
context.Call("fillText", v, x, y+(12*k))
}
return nil // Dummy
}
func makeBitmap(file string) js.Object {
img := js.Global.Get("Image").New()
img.Set("src", file)
return img
}
type Sprite struct {
bitmap js.Object
x, y int
}
func makeSprite(bitmap js.Object, x, y int) *Sprite {
sp := &Sprite{
bitmap: bitmap,
x: x,
y: y,
}
bitmap.Call("addEventListener", "load", func() {
context.Call("drawImage", bitmap, x, y)
sp.bitmap = bitmap
sp.x = x
sp.y = y
}, false)
return sp
}
var emptyPilePng, smallPilePng, pickPng1, pickPng2, fullPng1, fullPng2, emptyPng1, emptyPng2, shovelPng1, shovelPng2, white, L1, L2, WT js.Object
var context js.Object
var lastTime time.Time
// headline at the top
func makeHeadline() {
now := time.Now()
if now.Minute() != lastTime.Minute() {
makeText(false, 195, 15, 500, 50, 0x008000,
"Written in Go, compiled by GopherJS and run live on "+
now.Format("Jan 2, 2006 at 3:04pm (MST)"))
lastTime = now
}
}
func Start() {
doc := js.Global.Get("document")
canvas := doc.Call("getElementById", "myCanvas")
context = canvas.Call("getContext", "2d")
// setup the animated PNG bitmaps
emptyPilePng = makeBitmap("assets/emptypile.png")
smallPilePng = makeBitmap("assets/smallpile.png")
pickPng1 = makeBitmap("assets/pick.png")
pickPng2 = makeBitmap("assets/pick.png")
fullPng1 = makeBitmap("assets/full.png")
fullPng2 = makeBitmap("assets/full.png")
emptyPng1 = makeBitmap("assets/empty.png")
emptyPng2 = makeBitmap("assets/empty.png")
shovelPng1 = makeBitmap("assets/shovel.png")
shovelPng2 = makeBitmap("assets/shovel.png")
white = makeBitmap("assets/white.png")
WT = makeBitmap("assets/whitethumb.png")
makeHeadline()
// Explation text on the left
makeText(false, 10, 140, 180, 200, 0x008000, `Both animated gophers are
running the code on the right.
The 2 logos show where they
each are in that code now.
Go translated to JS using
GopherJS.`)
// the code extract in the centre
makeSprite(makeBitmap("assets/function.png"), 200, 110)
// the "inspired by"" text
makeText(true, 630, 140, 200, 200, 0x008000, `Inspired by <NAME>:
"Concurrency is not Parallelism"
http://blog.golang.org/
concurrency-is-not-parallelism
- Gopher by <NAME>`)
// big pile of books on the left
makeSprite(makeBitmap("assets/bigpile.png"), 10, 20)
// oven on the right
makeSprite(makeBitmap("assets/oven.png"), 690, 0)
// books in the middle
Books = makeSprite(emptyPilePng, 390, 50)
// the left hand code indicator
L1 = makeBitmap("assets/gophercolor16x16.png")
Logo1 = makeSprite(L1, 230, 140)
// the right hand code indicator
L2 = makeBitmap("assets/gophercolor16x16flipped.png")
Logo2 = makeSprite(L2, 540, 140)
// the left hand gopher
Sprite1 = makeSprite(pickPng1, s1x, s1y)
// the right hand gopher
Sprite2 = makeSprite(pickPng2, s2x, s2y)
RAF() // show the picture before we start moving
startGophers() // start the animation logic
for { // this to ensure that the main function does not finish
Gosched()
}
}
func replaceBitmap(sprite *Sprite, bitmap *js.Object) { // pointers here to avoid a Haxe object copy when passing by value
sprite.bitmap = *bitmap
context.Call("drawImage", sprite.bitmap, sprite.x, sprite.y)
RAF()
}
var showingBooks bool = true
var s1state, s2state int = Pick, Pick
func monitor() {
RAF()
// make the pile of books appear or disappear
if len(smallpile) > 0 { // take the length of the channel here
if !showingBooks {
replaceBitmap(Books, &smallPilePng)
showingBooks = true
}
} else {
if showingBooks {
replaceBitmap(Books, &emptyPilePng)
showingBooks = false
}
}
// animate left-hand sprite and it's code logo
newY1 := 140 + (15 * Sprite1state) // move the logo to reflect the new state
if Logo1.y != newY1 {
replaceBitmap(Logo1, &WT)
Logo1.y = newY1
replaceBitmap(Logo1, &L1)
}
if s1state != Sprite1state {
switch s1state {
case Shovel, Pick:
replaceBitmap(Sprite1, &white)
}
s1state = Sprite1state
}
newS1X := int(s1x + Sprite1X)
newS1Y := int(s1y + Sprite1Y)
if Sprite1.x != newS1X || Sprite1.y != newS1Y {
Sprite1.x = newS1X
Sprite1.y = newS1Y
switch Sprite1state {
case Pick:
replaceBitmap(Sprite1, &pickPng1)
case Full:
replaceBitmap(Sprite1, &fullPng1)
case Shovel:
replaceBitmap(Sprite1, &shovelPng1)
case Empty:
replaceBitmap(Sprite1, &emptyPng1)
}
}
// animate right-hand sprite and it's code logo
newY2 := 140 + (15 * Sprite2state) // move the logo to reflect the new state
if Logo2.y != newY2 {
replaceBitmap(Logo2, &WT)
Logo2.y = newY2
replaceBitmap(Logo2, &L2)
}
if s2state != Sprite2state {
switch s2state {
case Shovel, Pick:
replaceBitmap(Sprite2, &white)
}
s2state = Sprite2state
}
newS2X := int(s2x + Sprite2X)
newS2Y := int(s2y + Sprite2Y)
if Sprite2.x != newS2X || Sprite2.y != newS2Y {
Sprite2.x = newS2X
Sprite2.y = newS2Y
switch Sprite2state {
case Pick:
replaceBitmap(Sprite2, &pickPng2)
case Full:
replaceBitmap(Sprite2, &fullPng2)
case Shovel:
replaceBitmap(Sprite2, &shovelPng2)
case Empty:
replaceBitmap(Sprite2, &emptyPng2)
}
}
}
// Gosched both schedules other goroutines and shows their state.
func Gosched() {
monitor()
time.Sleep(0)
}
// RAF - Request Animation Frame
func RAF() {
js.Global.Get("window").Call("requestAnimationFrame", RAF_callback)
<-RAF_chan
}
var RAF_chan = make(chan bool)
func RAF_callback() {
go func() { RAF_chan <- true }()
} | gopherjs/gophers/gophers.go | 0.531453 | 0.409929 | gophers.go | starcoder |
package main
import (
"fmt"
"log"
"math"
"runtime"
"time"
)
var (
epsilon = 32
)
func SetMemUsage(x int, y int, a float64, b float64, c float64, d float64, e float64, f float64, g float64, h float64) *[][]int8 {
var overall [][]int8
var i uint
mem := getMemoryUsage(x, y, a, b, c, d, e, f, g, h)
for ; i < mem; i++ {
// Giga
a := make([]int8, 0, 1048576*epsilon)
overall = append(overall, a)
//memUsage(mem)
if i % 100 == 0 {
time.Sleep(time.Millisecond * 10)
}
}
memUsage(mem)
return &overall
}
func getMemoryUsage(x int, y int, a float64, b float64, c float64, d float64, e float64, f float64, g float64, h float64) uint {
var x_param float64
var y_param float64
if x%2 == 0 {
x_param = func_x_1(a, b, c, d)
} else {
x_param = func_x_2(d, e, h)
}
if y%2 == 0 {
y_param = func_y_1(a, c, e, f, g)
} else {
y_param = func_y_2(b, e, f)
}
return himmelblau(x_param, y_param)
}
func FreeMemUsed(overall *[][]int8) {
overall = nil
fmt.Printf("free memory")
memUsage(0)
runtime.GC()
memUsage(0)
}
func memUsage(expected uint) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc))
fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc))
fmt.Printf("\tSys = %v MiB", bToMb(m.Sys))
fmt.Printf("\tNumGc = %v\n", m.NumGC)
fmt.Printf("\tExpected = %v\n", expected)
}
func bToMb(b uint64) uint64 {
return b / uint64(epsilon) / 1024 / 1024
}
// https://caffinc.github.io/2016/03/cpu-load-generator/
func InfinityCpuUsage(x int, y int, a float64, b float64, c float64, d float64, e float64, f float64, g float64, h float64) {
FinityCpuUsage(0, x, y, a, b, c, d, e, f, g, h)
}
func getCpuUsage(x int, y int, a float64, b float64, c float64, d float64, e float64, f float64, g float64, h float64) float64 {
var x_param float64
var y_param float64
if x%2 == 0 {
x_param = func_x_1(a, b, c, d)
} else {
x_param = func_x_2(d, e, h)
}
if y%2 == 0 {
y_param = func_y_1(a, c, e, f, g)
} else {
y_param = func_y_2(b, e, f)
}
return beale(x_param, y_param) * 100
}
// set CPU usage in $load% for $timeElapsed ms
func FinityCpuUsage(timeElapsed uint, x int, y int, a float64, b float64, c float64, d float64, e float64, f float64, g float64, h float64) time.Duration {
start := time.Now()
sleepTime := getCpuUsage(x, y, a, b, c, d, e, f, g, h)
var elapsed time.Duration
for {
unladenTime := time.Now().UnixNano() / int64(time.Millisecond)
if unladenTime%100 == 0 {
time.Sleep(time.Millisecond * time.Duration(sleepTime))
}
elapsed = time.Now().Sub(start)
if timeElapsed > 0 && uint(elapsed/time.Millisecond) >= timeElapsed {
break
}
}
return elapsed
}
func beale(x float64, y float64) float64 {
var val = 0.0
// We use our range as [-4.5, 4.5] because it starts to grow too rapidly beyond those values
if x >= -4.5 && x <= 4.5 && y >= -4.5 && y <= 4.5 {
// Beale Function
val = math.Pow((1.5-x+x*y), 2) + math.Pow((2.25-x+(x*math.Pow(y, 2))), 2) + math.Pow((2.625-x+(x*math.Pow(y, 3))), 2)
// Maximum for this function is approx. 178000, so we can normalize it to a value between 0 and 0.2 by dividing by 890000
val = val/890000 + 0.8 // Make it a value between 0.2 and 1.0
log.Printf("beale(%f, %f) val: %f\n", x, y, val)
} else {
// For these cases, we received values outside of our valid search domains
// Therefore, let's just use a catch-all function that'll take any parameters
val = 0.5 * (math.Sin(math.Min(x,y) * math.Pi) + 1)/2
log.Printf("beale fallback (math.Sin((%f*%f) * math.Pi) + 1)/2 = %f\n", x, y, val)
}
// to maximize the value
return 1-val
}
func himmelblau(x float64, y float64) uint {
var pct = 0.0
if x >= -5 && x <= 5 && y >= -5 && y <= 5 {
// Himmelblau Function
pct = math.Pow(math.Pow(x, 2)+y-11, 2) + math.Pow(x+math.Pow(y, 2)-7, 2)
// Maximum for this function is approx. 890
pct = pct / 890 // make it a value between 0 and 1
log.Printf("himmelblau(%f, %f) val: %f\n", x, y, pct)
} else {
// For these cases, we received values outside of our valid search domains
// Therefore, let's just use a catch-all function that'll take any parameters
pct = 0.5 * (math.Cos(math.Min(x,y) * math.Pi) + 1)/2
log.Printf("himmelblau fallback (math.Cos((%f*%f) * math.Pi) + 1)/2 = %f\n", x, y, pct)
}
pct = 1- pct
// this can be changed; let's use 1024 as our maximum and 0 as our minimum
val := uint(float64(1024) * pct) // note that we're changing it to a uint32 => nearest integer val
return val
}
func func_x_1(a float64, b float64, c float64, d float64) float64 {
// Our function won't work if log(d) = 0 because of a divide-by-zero, so just return the maximal value 5
if math.Log(d) == 0 {
return 5
}
// (a^2 + bc) / (500*log(d))
return (math.Pow(a, 2) + (b * c)) / (500 * math.Log(d))
}
func func_y_1(a float64, c float64, e float64, f float64, g float64) float64 {
// sin(a*c*pi) * cos(f^g*pi) - 2*e
return (math.Sin((a/c)*math.Pi)*math.Cos(f*g*math.Pi) - 2*e)
}
func func_x_2(d float64, e float64, h float64) float64 {
return (math.Log(d) - (e * h / 32))
}
func func_y_2(b float64, e float64, f float64) float64 {
if b*e < 0 {
// Just to make sure that we end up with a positive value to sqrt
e = -e
}
return math.Sqrt(b*e) / f
} | metrics.go | 0.552298 | 0.474327 | metrics.go | starcoder |
package telemetry
import (
"context"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
)
var (
// HistogramBounds defines a unified bucket boundaries for all histogram typed time metrics in Open Match
HistogramBounds = []float64{0, 50, 100, 200, 400, 800, 1600, 3200, 6400, 12800, 25600, 51200}
)
// Gauge creates a gauge metric to be recorded with dimensionless unit.
func Gauge(name string, description string, tags ...tag.Key) *stats.Int64Measure {
s := stats.Int64(name, description, "1")
gaugeView(s, tags...)
return s
}
// SetGauge sets the value of the metric
func SetGauge(ctx context.Context, s *stats.Int64Measure, n int64, tags ...tag.Mutator) {
mCtx, err := tag.New(ctx, tags...)
if err != nil {
return
}
stats.Record(mCtx, s.M(n))
}
// Counter creates a counter metric to be recorded with dimensionless unit.
func Counter(name string, description string, tags ...tag.Key) *stats.Int64Measure {
s := stats.Int64(name, "Count of "+description+".", stats.UnitDimensionless)
counterView(s, tags...)
return s
}
// HistogramWithBounds creates a prometheus histogram metric to be recorded with specified bounds and metric type.
func HistogramWithBounds(name string, description string, unit string, bounds []float64, tags ...tag.Key) *stats.Int64Measure {
s := stats.Int64(name, description, unit)
histogramView(s, bounds, tags...)
return s
}
// RecordUnitMeasurement records a data point using the input metric by one unit with given tags.
func RecordUnitMeasurement(ctx context.Context, s *stats.Int64Measure, tags ...tag.Mutator) {
RecordNUnitMeasurement(ctx, s, 1, tags...)
}
// RecordNUnitMeasurement records a data point using the input metric by N units with given tags.
func RecordNUnitMeasurement(ctx context.Context, s *stats.Int64Measure, n int64, tags ...tag.Mutator) {
if err := stats.RecordWithTags(ctx, tags, s.M(n)); err != nil {
logger.WithError(err).Infof("cannot record stat with tags %#v", tags)
return
}
}
// histogramView converts the measurement into a view for a histogram metric.
func histogramView(s *stats.Int64Measure, bounds []float64, tags ...tag.Key) *view.View {
v := &view.View{
Name: s.Name(),
Measure: s,
Description: s.Description(),
Aggregation: view.Distribution(bounds...),
TagKeys: tags,
}
err := view.Register(v)
if err != nil {
logger.WithError(err).Infof("cannot register view for metric: %s, it will not be reported", s.Name())
}
return v
}
// gaugeView converts the measurement into a view for a gauge metric.
func gaugeView(s *stats.Int64Measure, tags ...tag.Key) *view.View {
v := &view.View{
Name: s.Name(),
Measure: s,
Description: s.Description(),
Aggregation: view.LastValue(),
TagKeys: tags,
}
err := view.Register(v)
if err != nil {
logger.WithError(err).Infof("cannot register view for metric: %s, it will not be reported", s.Name())
}
return v
}
// counterView converts the measurement into a view for a counter.
func counterView(s *stats.Int64Measure, tags ...tag.Key) *view.View {
v := &view.View{
Name: s.Name(),
Measure: s,
Description: s.Description(),
Aggregation: view.Count(),
TagKeys: tags,
}
err := view.Register(v)
if err != nil {
logger.WithError(err).Infof("cannot register view for metric: %s, it will not be reported", s.Name())
}
return v
} | internal/telemetry/metrics.go | 0.717111 | 0.422743 | metrics.go | starcoder |
package jaeger
import (
"time"
"github.com/welcome112s/jaeger-client-go/log"
)
// SamplerOption is a function that sets some option on the sampler
type SamplerOption func(options *samplerOptions)
// SamplerOptions is a factory for all available SamplerOption's.
var SamplerOptions SamplerOptionsFactory
// SamplerOptionsFactory is a factory for all available SamplerOption's.
// The type acts as a namespace for factory functions. It is public to
// make the functions discoverable via godoc. Recommended to be used
// via global SamplerOptions variable.
type SamplerOptionsFactory struct{}
type samplerOptions struct {
metrics *Metrics
sampler SamplerV2
logger Logger
samplingServerURL string
samplingRefreshInterval time.Duration
samplingFetcher SamplingStrategyFetcher
samplingParser SamplingStrategyParser
updaters []SamplerUpdater
posParams PerOperationSamplerParams
}
// Metrics creates a SamplerOption that initializes Metrics on the sampler,
// which is used to emit statistics.
func (SamplerOptionsFactory) Metrics(m *Metrics) SamplerOption {
return func(o *samplerOptions) {
o.metrics = m
}
}
// MaxOperations creates a SamplerOption that sets the maximum number of
// operations the sampler will keep track of.
func (SamplerOptionsFactory) MaxOperations(maxOperations int) SamplerOption {
return func(o *samplerOptions) {
o.posParams.MaxOperations = maxOperations
}
}
// OperationNameLateBinding creates a SamplerOption that sets the respective
// field in the PerOperationSamplerParams.
func (SamplerOptionsFactory) OperationNameLateBinding(enable bool) SamplerOption {
return func(o *samplerOptions) {
o.posParams.OperationNameLateBinding = enable
}
}
// InitialSampler creates a SamplerOption that sets the initial sampler
// to use before a remote sampler is created and used.
func (SamplerOptionsFactory) InitialSampler(sampler Sampler) SamplerOption {
return func(o *samplerOptions) {
o.sampler = samplerV1toV2(sampler)
}
}
// Logger creates a SamplerOption that sets the logger used by the sampler.
func (SamplerOptionsFactory) Logger(logger Logger) SamplerOption {
return func(o *samplerOptions) {
o.logger = logger
}
}
// SamplingServerURL creates a SamplerOption that sets the sampling server url
// of the local agent that contains the sampling strategies.
func (SamplerOptionsFactory) SamplingServerURL(samplingServerURL string) SamplerOption {
return func(o *samplerOptions) {
o.samplingServerURL = samplingServerURL
}
}
// SamplingRefreshInterval creates a SamplerOption that sets how often the
// sampler will poll local agent for the appropriate sampling strategy.
func (SamplerOptionsFactory) SamplingRefreshInterval(samplingRefreshInterval time.Duration) SamplerOption {
return func(o *samplerOptions) {
o.samplingRefreshInterval = samplingRefreshInterval
}
}
// SamplingStrategyFetcher creates a SamplerOption that initializes sampling strategy fetcher.
func (SamplerOptionsFactory) SamplingStrategyFetcher(fetcher SamplingStrategyFetcher) SamplerOption {
return func(o *samplerOptions) {
o.samplingFetcher = fetcher
}
}
// SamplingStrategyParser creates a SamplerOption that initializes sampling strategy parser.
func (SamplerOptionsFactory) SamplingStrategyParser(parser SamplingStrategyParser) SamplerOption {
return func(o *samplerOptions) {
o.samplingParser = parser
}
}
// Updaters creates a SamplerOption that initializes sampler updaters.
func (SamplerOptionsFactory) Updaters(updaters ...SamplerUpdater) SamplerOption {
return func(o *samplerOptions) {
o.updaters = updaters
}
}
func (o *samplerOptions) applyOptionsAndDefaults(opts ...SamplerOption) *samplerOptions {
for _, option := range opts {
option(o)
}
if o.sampler == nil {
o.sampler = newProbabilisticSampler(0.001)
}
if o.logger == nil {
o.logger = log.NullLogger
}
if o.samplingServerURL == "" {
o.samplingServerURL = DefaultSamplingServerURL
}
if o.metrics == nil {
o.metrics = NewNullMetrics()
}
if o.samplingRefreshInterval <= 0 {
o.samplingRefreshInterval = defaultSamplingRefreshInterval
}
if o.samplingFetcher == nil {
o.samplingFetcher = &httpSamplingStrategyFetcher{
serverURL: o.samplingServerURL,
logger: o.logger,
}
}
if o.samplingParser == nil {
o.samplingParser = new(samplingStrategyParser)
}
if o.updaters == nil {
o.updaters = []SamplerUpdater{
&AdaptiveSamplerUpdater{
MaxOperations: o.posParams.MaxOperations,
OperationNameLateBinding: o.posParams.OperationNameLateBinding,
},
new(ProbabilisticSamplerUpdater),
new(RateLimitingSamplerUpdater),
}
}
return o
} | sampler_remote_options.go | 0.617513 | 0.44059 | sampler_remote_options.go | starcoder |
package schema
import "github.com/elimity-com/scim/optional"
// BinaryParams are the parameters used to create a simple attribute with a data type of "binary".
// The attribute value MUST be base64 encoded. In JSON representation, the encoded values are represented as a JSON string.
// A binary is case exact and has no uniqueness.
type BinaryParams struct {
Description optional.String
MultiValued bool
Mutability AttributeMutability
Name string
Required bool
Returned AttributeReturned
}
// BooleanParams are the parameters used to create a simple attribute with a data type of "boolean".
// The literal "true" or "false". A boolean has no case sensitivity or uniqueness.
type BooleanParams struct {
Description optional.String
MultiValued bool
Mutability AttributeMutability
Name string
Required bool
Returned AttributeReturned
}
// DateTimeParams are the parameters used to create a simple attribute with a data type of "dateTime".
// A DateTime value (e.g., 2008-01-23T04:56:22Z). A date time format has no case sensitivity or uniqueness.
type DateTimeParams struct {
Description optional.String
MultiValued bool
Mutability AttributeMutability
Name string
Required bool
Returned AttributeReturned
}
// NumberParams are the parameters used to create a simple attribute with a data type of "decimal" or "integer".
// A number has no case sensitivity.
type NumberParams struct {
Description optional.String
MultiValued bool
Mutability AttributeMutability
Name string
Required bool
Returned AttributeReturned
Type AttributeDataType
Uniqueness AttributeUniqueness
}
// ReferenceParams are the parameters used to create a simple attribute with a data type of "reference".
// A reference is case exact. A reference has a "referenceTypes" attribute that indicates what types of resources may
// be linked.
type ReferenceParams struct {
Description optional.String
MultiValued bool
Mutability AttributeMutability
Name string
ReferenceTypes []AttributeReferenceType
Required bool
Returned AttributeReturned
Uniqueness AttributeUniqueness
}
// SimpleParams are the parameters used to create a simple attribute.
type SimpleParams struct {
canonicalValues []string
caseExact bool
description optional.String
multiValued bool
mutability attributeMutability
name string
referenceTypes []AttributeReferenceType
required bool
returned attributeReturned
typ attributeType
uniqueness attributeUniqueness
}
// SimpleBinaryParams converts given binary parameters to their corresponding simple parameters.
func SimpleBinaryParams(params BinaryParams) SimpleParams {
return SimpleParams{
caseExact: true,
description: params.Description,
multiValued: params.MultiValued,
mutability: params.Mutability.m,
name: params.Name,
required: params.Required,
returned: params.Returned.r,
typ: attributeDataTypeBinary,
uniqueness: attributeUniquenessNone,
}
}
// SimpleBooleanParams converts given boolean parameters to their corresponding simple parameters.
func SimpleBooleanParams(params BooleanParams) SimpleParams {
return SimpleParams{
caseExact: false,
description: params.Description,
multiValued: params.MultiValued,
mutability: params.Mutability.m,
name: params.Name,
required: params.Required,
returned: params.Returned.r,
typ: attributeDataTypeBoolean,
uniqueness: attributeUniquenessNone,
}
}
// SimpleDateTimeParams converts given date time parameters to their corresponding simple parameters.
func SimpleDateTimeParams(params DateTimeParams) SimpleParams {
return SimpleParams{
caseExact: false,
description: params.Description,
multiValued: params.MultiValued,
mutability: params.Mutability.m,
name: params.Name,
required: params.Required,
returned: params.Returned.r,
typ: attributeDataTypeDateTime,
uniqueness: attributeUniquenessNone,
}
}
// SimpleNumberParams converts given number parameters to their corresponding simple parameters.
func SimpleNumberParams(params NumberParams) SimpleParams {
return SimpleParams{
caseExact: false,
description: params.Description,
multiValued: params.MultiValued,
mutability: params.Mutability.m,
name: params.Name,
required: params.Required,
returned: params.Returned.r,
typ: params.Type.t,
uniqueness: params.Uniqueness.u,
}
}
// SimpleReferenceParams converts given reference parameters to their corresponding simple parameters.
func SimpleReferenceParams(params ReferenceParams) SimpleParams {
return SimpleParams{
caseExact: true,
description: params.Description,
multiValued: params.MultiValued,
mutability: params.Mutability.m,
name: params.Name,
referenceTypes: params.ReferenceTypes,
required: params.Required,
returned: params.Returned.r,
typ: attributeDataTypeReference,
uniqueness: params.Uniqueness.u,
}
}
// SimpleStringParams converts given string parameters to their corresponding simple parameters.
func SimpleStringParams(params StringParams) SimpleParams {
return SimpleParams{
canonicalValues: params.CanonicalValues,
caseExact: params.CaseExact,
description: params.Description,
multiValued: params.MultiValued,
mutability: params.Mutability.m,
name: params.Name,
required: params.Required,
returned: params.Returned.r,
typ: attributeDataTypeString,
uniqueness: params.Uniqueness.u,
}
}
// StringParams are the parameters used to create a simple attribute with a data type of "string".
// A string is a sequence of zero or more Unicode characters encoded using UTF-8.
type StringParams struct {
CanonicalValues []string
CaseExact bool
Description optional.String
MultiValued bool
Mutability AttributeMutability
Name string
Required bool
Returned AttributeReturned
Uniqueness AttributeUniqueness
} | schema/simple.go | 0.817538 | 0.520923 | simple.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.