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

package frontend

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"github.com/matrixorigin/matrixone/pkg/common/moerr"
	"github.com/matrixorigin/matrixone/pkg/defines"
	"github.com/matrixorigin/matrixone/pkg/logutil"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/dialect"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
)

type SpStatus int

const (
	SpOk        SpStatus = 0
	SpNotOk     SpStatus = 1
	SpBranchHit SpStatus = 2
	SpLeaveLoop SpStatus = 3
	SpIterLoop  SpStatus = 4
)

type Interpreter struct {
	ctx         context.Context
	ses         *Session
	bh          BackgroundExec
	varScope    *[]map[string]interface{}
	fmtctx      *tree.FmtCtx
	result      []ExecResult
	argsAttr    map[string]tree.InOutArgType // used for IN, OUT, IN/OUT check
	argsMap     map[string]tree.Expr         // used for argument to parameter mapping
	outParamMap map[string]interface{}       // used for storing and updating OUT type arg
}

func (interpreter *Interpreter) GetResult() []ExecResult {
	return interpreter.result
}

func (interpreter *Interpreter) GetExprString(input tree.Expr) string {
	interpreter.fmtctx.Reset()
	input.Format(interpreter.fmtctx)
	return interpreter.fmtctx.String()
}

func (interpreter *Interpreter) GetStatementString(input tree.Statement) string {
	interpreter.fmtctx.Reset()
	input.Format(interpreter.fmtctx)
	return interpreter.fmtctx.String()
}

func (interpreter *Interpreter) GetSpVar(varName string) (interface{}, error) {
	for i := len(*interpreter.varScope) - 1; i >= 0; i-- {
		curScope := (*interpreter.varScope)[i]
		val, ok := curScope[strings.ToLower(varName)]
		if ok {
			return val, nil
		}
	}
	return "", nil
}

// Return error if variable is not declared yet. PARAM is an exception!
func (interpreter *Interpreter) SetSpVar(name string, value interface{}) error {
	for i := len(*interpreter.varScope) - 1; i >= 0; i-- {
		curScope := (*interpreter.varScope)[i]
		if _, ok := curScope[strings.ToLower(name)]; ok {
			curScope[strings.ToLower(name)] = value
			return nil
		}
	}
	// loop up OUT param and SET in-place
	if _, ok := interpreter.outParamMap[name]; ok {
		// save at local
		interpreter.outParamMap[name] = value
		return nil
	}
	return moerr.NewNotSupported(interpreter.ctx, fmt.Sprintf("variable %s has to be declared using DECLARE.", name))
}

func (interpreter *Interpreter) FlushParam() error {
	for k, v := range (*interpreter.varScope)[0] {
		if _, ok := interpreter.argsMap[k]; ok && interpreter.argsAttr[k] == tree.TYPE_INOUT {
			// save INOUT at session
			interpreter.bh.ClearExecResultSet()
			// system setvar execution
			err := interpreter.ses.SetUserDefinedVar(interpreter.argsMap[k].(*tree.VarExpr).Name, v)
			if err != nil {
				return err
			}
		}
	}

	for k, v := range interpreter.outParamMap {
		// save at session
		interpreter.bh.ClearExecResultSet()
		// system setvar execution
		err := interpreter.ses.SetUserDefinedVar(interpreter.argsMap[k].(*tree.VarExpr).Name, v)
		if err != nil {
			return err
		}
	}

	return nil
}

func (interpreter *Interpreter) GetSimpleExprValueWithSpVar(e tree.Expr) (interface{}, error) {
	newExpr, err := interpreter.MatchExpr(e)
	if err != nil {
		return nil, err
	}
	retStmt, err := parsers.ParseOne(interpreter.ctx, dialect.MYSQL, "select "+interpreter.GetExprString(newExpr), 1)
	if err != nil {
		return nil, err
	}
	retExpr := retStmt.(*tree.Select).Select.(*tree.SelectClause).Exprs[0].Expr
	if err != nil {
		return nil, err
	}
	return GetSimpleExprValue(retExpr, interpreter.ses)
}

// Currently we support only binary, unary and comparison expression.
func (interpreter *Interpreter) MatchExpr(expr tree.Expr) (tree.Expr, error) {
	switch e := expr.(type) {
	case *tree.BinaryExpr:
		leftExpr, err := interpreter.MatchExpr(e.Left)
		if err != nil {
			return nil, err
		}
		rightExpr, err := interpreter.MatchExpr(e.Right)
		if err != nil {
			return nil, err
		}
		return &tree.BinaryExpr{
			Op:    e.Op,
			Left:  leftExpr,
			Right: rightExpr,
		}, nil
	case *tree.UnaryExpr:
	case *tree.ComparisonExpr:
		leftExpr, err := interpreter.MatchExpr(e.Left)
		if err != nil {
			return nil, err
		}
		rightExpr, err := interpreter.MatchExpr(e.Right)
		if err != nil {
			return nil, err
		}
		return &tree.ComparisonExpr{
			Op:     e.Op,
			SubOp:  e.SubOp,
			Left:   leftExpr,
			Right:  rightExpr,
			Escape: e.Escape,
		}, nil
	case *tree.AndExpr:
	case *tree.XorExpr:
	case *tree.OrExpr:
	case *tree.NotExpr:
	case *tree.IsNullExpr:
	case *tree.IsNotNullExpr:
	case *tree.IsUnknownExpr:
	case *tree.IsNotUnknownExpr:
	case *tree.IsTrueExpr:
	case *tree.IsNotTrueExpr:
	case *tree.IsFalseExpr:
	case *tree.IsNotFalseExpr:
	case *tree.FuncExpr:
	case *tree.UnresolvedName:
		// change column name to var name
		val, err := interpreter.GetSpVar(e.Parts[0])
		if err != nil {
			return nil, err
		}
		retName := &tree.UnresolvedName{
			NumParts: e.NumParts,
			Star:     e.Star,
			Parts:    e.Parts,
		}
		retName.Parts[0] = fmt.Sprintf("%v", val)
		return retName, nil
	default:
		return e, nil
	}
	return nil, nil
}

// Evaluate condition by sending it to bh with a select
func (interpreter *Interpreter) EvalCond(cond string) (int, error) {
	interpreter.bh.ClearExecResultSet()
	interpreter.ctx = context.WithValue(interpreter.ctx, defines.VarScopeKey{}, interpreter.varScope)
	interpreter.ctx = context.WithValue(interpreter.ctx, defines.InSp{}, true)
	err := interpreter.bh.Exec(interpreter.ctx, "select "+cond)
	if err != nil {
		return 0, err
	}
	erArray, err := getResultSet(interpreter.ctx, interpreter.bh)
	if err != nil {
		return 0, err
	}

	if execResultArrayHasData(erArray) {
		cond, err := erArray[0].GetInt64(interpreter.ctx, 0, 0)
		if err != nil {
			return 0, err
		}
		return int(cond), nil
	}
	return 0, nil
}

func (interpreter *Interpreter) ExecuteSp(stmt tree.Statement, dbName string) (err error) {
	curScope := make(map[string]interface{})
	interpreter.bh.ClearExecResultSet()

	// use current database as default
	err = interpreter.bh.Exec(interpreter.ctx, "use "+dbName)
	if err != nil {
		return err
	}

	// make sure the entire sp is in a single transaction
	err = interpreter.bh.Exec(interpreter.ctx, "begin;")
	defer func() {
		err = finishTxn(interpreter.ctx, interpreter.bh, err)
	}()
	if err != nil {
		return err
	}

	// save parameters as local variables
	*interpreter.varScope = append(*interpreter.varScope, curScope)
	for k, v := range interpreter.argsMap {
		var value interface{}
		if varParam, ok := v.(*tree.VarExpr); ok {
			// For OUT type, store it in a separate map only for SET to update it and flush at the end
			if interpreter.argsAttr[k] == tree.TYPE_OUT {
				interpreter.outParamMap[k] = 0
			} else { // For INOUT and IN type, fetch store its previous value
				interpreter.bh.ClearExecResultSet()
				_, value, _ := interpreter.ses.GetUserDefinedVar(varParam.Name)
				if value == nil {
					// raise an error as INOUT / IN type param has to have a value
					return moerr.NewNotSupported(interpreter.ctx, fmt.Sprintf("parameter %s with type INOUT or IN has to have a specified value.", k))
				}
				// save param to local var scope
				(*interpreter.varScope)[len(*interpreter.varScope)-1][strings.ToLower(k)] = value
			}
		} else {
			// if param type is INOUT or OUT and the param is not provided with variable expr, raise an error
			if interpreter.argsAttr[k] == tree.TYPE_INOUT || interpreter.argsAttr[k] == tree.TYPE_OUT {
				return moerr.NewNotSupported(interpreter.ctx, fmt.Sprintf("parameter %s with type INOUT or OUT has to be passed in using @.", k))
			}
			// evaluate the param
			value, err = interpreter.GetSimpleExprValueWithSpVar(v)
			if err != nil {
				return err
			}
			// save param to local var scope
			(*interpreter.varScope)[len(*interpreter.varScope)-1][strings.ToLower(k)] = value
		}
	}

	_, err = interpreter.interpret(stmt)

	if err != nil {
		return err
	}

	// // commit the param flush part of sp
	// err = interpreter.bh.Exec(interpreter.ctx, "begin;")
	// if err != nil {
	// 	return err
	// }

	err = interpreter.FlushParam()
	if err != nil {
		return err
	}

	// err = interpreter.bh.Exec(interpreter.ctx, "commit;")
	// if err != nil {
	// 	return err
	// }

	return nil
}

func (interpreter *Interpreter) interpret(stmt tree.Statement) (SpStatus, error) {
	if stmt == nil {
		return SpOk, nil
	}
	switch st := stmt.(type) {
	case *tree.CompoundStmt:
		// create new variable scope and push it
		curScope := make(map[string]interface{})
		*interpreter.varScope = append(*interpreter.varScope, curScope)
		logutil.Info("current scope level: " + strconv.Itoa(len(*interpreter.varScope)))
		// recursively execute
		for _, innerSt := range st.Stmts {
			_, err := interpreter.interpret(innerSt)
			if err != nil {
				return SpNotOk, err
			}
		}
		// pop current scope
		*interpreter.varScope = (*interpreter.varScope)[:len(*interpreter.varScope)-1]
		return SpOk, nil
	case *tree.RepeatStmt:
		for {
			// first execute body
			for _, stmt := range st.Body {
				_, err := interpreter.interpret(stmt)
				if err != nil {
					return SpNotOk, err
				}
			}
			// then evaluate condition
			condStr := interpreter.GetExprString(st.Cond)
			condVal, err := interpreter.EvalCond(condStr)
			if err != nil {
				return SpNotOk, err
			}
			if condVal == 1 {
				break
			}
		}
	case *tree.WhileStmt:
		for {
			// first evaluate
			condStr := interpreter.GetExprString(st.Cond)
			condVal, err := interpreter.EvalCond(condStr)
			if err != nil {
				return SpNotOk, err
			}
			if condVal == 0 {
				break
			}
			// then execute body
			for _, stmt := range st.Body {
				_, err := interpreter.interpret(stmt)
				if err != nil {
					return SpNotOk, err
				}
			}
		}
	case *tree.LoopStmt:
	start:
		for {
			for _, stmt := range st.Body {
				status, err := interpreter.interpret(stmt)
				if err != nil {
					return SpNotOk, err
				}
				if status == SpLeaveLoop {
					// check label here using stmt
					goto exit
				}
				if status == SpIterLoop {
					// check label here using stmt
					goto start
				}
			}
		}
	exit:
		return SpOk, nil
	case *tree.IterateStmt:
		return SpIterLoop, nil
	case *tree.LeaveStmt:
		return SpLeaveLoop, nil
	case *tree.ElseIfStmt:
		// evaluate condition
		condStr := interpreter.GetExprString(st.Cond)
		condVal, err := interpreter.EvalCond(condStr)
		if err != nil {
			return SpNotOk, err
		}
		if condVal == 1 {
			// execute current else-if branch, remember to terminate other else-if
			for _, bodyStmt := range st.Body {
				status, err := interpreter.interpret(bodyStmt)
				if err != nil {
					return SpNotOk, err
				}
				if status == SpBranchHit || status == SpIterLoop || status == SpLeaveLoop {
					return status, nil
				}
			}
			return SpBranchHit, nil
		} else {
			return SpOk, nil
		}
	case *tree.IfStmt:
		// evaluate condition
		condStr := interpreter.GetExprString(st.Cond)
		condVal, err := interpreter.EvalCond(condStr)
		if err != nil {
			return SpNotOk, err
		}
		if condVal == 1 {
			// execute current branch
			for _, bodyStmt := range st.Body {
				status, err := interpreter.interpret(bodyStmt)
				if err != nil {
					return SpNotOk, err
				}
				if status == SpBranchHit || status == SpIterLoop || status == SpLeaveLoop {
					return status, nil
				}
			}
		} else {
			if len(st.Elifs) != 0 {
				// bunch of elif branch
				for _, elifStmt := range st.Elifs {
					status, err := interpreter.interpret(elifStmt)
					if err != nil {
						return SpNotOk, err
					}
					if status == SpBranchHit {
						// this means this else-if branch gets executed, no need to execute the rest elseif and else.
						goto end
					}
					if status == SpIterLoop || status == SpLeaveLoop {
						return status, nil
					}
				}
			}
			// else branch
			for _, elseStmt := range st.Else {
				status, err := interpreter.interpret(elseStmt)
				if err != nil {
					return SpNotOk, err
				}
				if status == SpBranchHit || status == SpIterLoop || status == SpLeaveLoop {
					return status, nil
				}
			}
		end:
			break
		}
	case *tree.WhenStmt:
		// any whenstmt that comes here will get executed, as we've already evaluated the condition in casestmt
		for _, stmt := range st.Body {
			// we use this branch
			_, err := interpreter.interpret(stmt)
			if err != nil {
				return SpNotOk, err
			}
		}
	case *tree.CaseStmt:
		// match case expression with all of its whens
		for _, whenStmt := range st.Whens {
			// build equality checker
			equalityExpr := &tree.ComparisonExpr{
				Op:    tree.EQUAL,
				Left:  st.Expr,
				Right: whenStmt.Cond,
			}
			condVal, err := interpreter.EvalCond(interpreter.GetExprString(equalityExpr))
			if err != nil {
				return SpNotOk, nil
			}
			if condVal == 1 {
				// we use this branch
				_, err := interpreter.interpret(whenStmt)
				if err != nil {
					return SpNotOk, err
				}
				return SpOk, nil
			}
		}

		// none of the WHEN branch hit, we execute ELSE
		for _, stmt := range st.Else {
			_, err := interpreter.interpret(stmt)
			if err != nil {
				return SpNotOk, err
			}
		}
		return SpOk, nil
	case *tree.Declare:
		var err error
		var value interface{}
		// store variables into current scope
		if st.DefaultVal != nil {
			value, err = GetSimpleExprValue(st.DefaultVal, interpreter.ses)
			if err != nil {
				return SpNotOk, nil
			}
		}
		for _, v := range st.Variables {
			(*interpreter.varScope)[len(*interpreter.varScope)-1][v] = value
		}
		return SpOk, nil
	case *tree.SetVar:
		for _, assign := range st.Assignments {
			name := assign.Name

			// if this is a system set, ignore if it's not a INOUT/OUT arg
			if strings.Contains(interpreter.GetExprString(st), "@") {
				str := interpreter.GetExprString(st)
				interpreter.bh.ClearExecResultSet()
				// system setvar execution
				err := interpreter.bh.Exec(interpreter.ctx, str)
				if err != nil {
					return SpNotOk, err
				}
			} else {
				// custom defined variable
				var value interface{}
				// get updated value
				value, err := interpreter.GetSimpleExprValueWithSpVar(assign.Value)
				if err != nil {
					return SpNotOk, err
				}

				// update local value
				err = interpreter.SetSpVar(name, value)
				if err != nil {
					return SpNotOk, err
				}
			}
		}
	default: // normal sql. Since we don't support SELECT INTO for now, we don't have to worry about updating variables
		str := interpreter.GetStatementString(st)
		interpreter.bh.ClearExecResultSet()
		// For sp variable replacement
		interpreter.ctx = context.WithValue(interpreter.ctx, defines.VarScopeKey{}, interpreter.varScope)
		interpreter.ctx = context.WithValue(interpreter.ctx, defines.InSp{}, true)
		err := interpreter.bh.Exec(interpreter.ctx, str)
		if err != nil {
			return SpNotOk, err
		}
		erArray, err := getResultSet(interpreter.ctx, interpreter.bh)
		if err != nil {
			return SpNotOk, err
		}
		if execResultArrayHasData(erArray) {
			interpreter.result = append(interpreter.result, erArray[0])
		}
		return SpOk, nil
	}
	return SpOk, nil
}

repository: matrixorigin/matrixone

repo_name: matrixorigin/matrixone


text:
SECTION = "devel/chicken"
DESCRIPTION = "PS/Tk: Portable Scheme interface to Tk"
LICENSE = "PD"
LIC_FILES_CHKSUM = "file://pstk.meta;md5=8c4216e24949be051d96eedfd8a1a6f0"

SRC_URI = "http://code.call-cc.org/egg-tarballs/4/pstk/pstk-${PV}.tar.gz"

SRC_URI[md5sum] = "d1dccbfb37fdbd730881403196edba8d"
SRC_URI[sha256sum] = "90f61e739f1942f88046f94780350450766a8deb153a9d9fe0002ed093c904f9"

S = "${WORKDIR}/pstk-${PV}"

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: Adellica/meta-chicken

license_type: permissive

repo_name: Adellica/meta-chicken

branch_name: refs/heads/master

extension: bb


text:
DESCRIPTION = "PSM Firmware"
SUMMARY = "PSM firmware for versal devices"

LICENSE = "CLOSED"

PROVIDES = "virtual/psm-firmware"

INHERIT_DEFAULT_DEPENDS = "1"

COMPATIBLE_MACHINE = "^$"
COMPATIBLE_MACHINE:versal = ".*"

# Since we're just copying, we can run any config
COMPATIBLE_HOST = ".*"

PACKAGE_ARCH = "${MACHINE_ARCH}"

# Default expects the user to provide the psm-firmware in the deploy
# directory, named "psm-firmware-${MACHINE}.elf" and "psm-firmware-${MACHINE}.bin"
# A machine, multiconfig, or local.conf should override this
PSM_DEPENDS ??= ""
PSM_MCDEPENDS ??= ""
PSM_DEPLOY_DIR ??= "${DEPLOY_DIR_IMAGE}"
PSM_FIRMWARE_DEPLOY_DIR[vardepsexclude] += "TOPDIR"
PSM_FIRMWARE_IMAGE_NAME ??= "psm-firmware-${MACHINE}"

# Default is for the multilib case (without the extension .elf/.bin)
PSM_FILE ??= "${PSM_FIRMWARE_DEPLOY_DIR}/${PSM_FIRMWARE_IMAGE_NAME}"
PSM_FILE[vardepsexclude] = "PSM_FIRMWARE_DEPLOY_DIR"

do_fetch[depends] += "${PSM_DEPENDS}"
do_fetch[mcdepends] += "${PSM_MCDEPENDS}"

inherit deploy

do_install() {
    if [ ! -e ${PSM_FILE}.elf ]; then
        echo "Unable to find PSM_FILE (${PSM_FILE}.elf)"
        exit 1
    fi

    install -Dm 0644 ${PSM_FILE}.elf ${D}/boot/${PN}.elf
}

# If the item is already in OUR deploy_image_dir, nothing to deploy!
SHOULD_DEPLOY = "${@'false' if (d.getVar('PSM_FILE')).startswith(d.getVar('DEPLOY_DIR_IMAGE')) else 'true'}"
do_deploy() {
    # If the item is already in OUR deploy_image_dir, nothing to deploy!
    if ${SHOULD_DEPLOY}; then
        install -Dm 0644 ${PSM_FILE}.elf ${DEPLOYDIR}/${PSM_FIRMWARE_IMAGE_NAME}.elf
        install -Dm 0644 ${PSM_FILE}.bin ${DEPLOYDIR}/${PSM_FIRMWARE_IMAGE_NAME}.bin
    fi
}

addtask deploy before do_build after do_install

INSANE_SKIP:${PN} = "arch"
INSANE_SKIP:${PN}-dbg = "arch"

# Disable buildpaths QA check warnings.
INSANE_SKIP:${PN} += "buildpaths"

SYSROOT_DIRS += "/boot"
FILES:${PN} = "/boot/${PN}.elf"

def check_psm_vars(d):
    # If both are blank, the user MUST pass in the path to the firmware!
    if not d.getVar('PSM_DEPENDS') and not d.getVar('PSM_MCDEPENDS'):
        # Don't cache this, as the items on disk can change!
        d.setVar('BB_DONT_CACHE', '1')

        msg = ""
        fail = False
        if not os.path.exists(d.getVar('PSM_FILE') + ".elf"):
            msg = msg + "The expected file %s.elf is not available.  " % d.getVar('PSM_FILE')
            fail = True
        if not os.path.exists(d.getVar('PSM_FILE') + ".bin"):
            msg = msg + "The expected file %s.bin is not available.  " % d.getVar('PSM_FILE')
            fail = True

        if fail:
            if not d.getVar('WITHIN_EXT_SDK'):
                raise bb.parse.SkipRecipe("%s\nSee the meta-xilinx-core README." % msg)
        else:
            # We found the file, so be sure to track it
            d.setVar('SRC_URI', 'file://${PSM_FILE}.elf file://${PSM_FILE}.bin')
            d.setVarFlag('do_install', 'file-checksums', '${PSM_FILE}.elf:True')
            d.setVarFlag('do_deploy', 'file-checksums', '${PSM_FILE}.elf:True ${PSM_FILE}.bin:True')

python() {
    # Need to allow bbappends to change the check
    check_psm_vars(d)
}

license: MIT

repository: Xilinx/meta-xilinx

repo_name: Xilinx/meta-xilinx

gha_license_id: MIT

gha_language: C


text:
package binstream

import (
	"io"
	"os"

	"github.com/edsrzf/mmap-go"
)

// ChunkSize is the default chunk size we use to read from files.
const ChunkSize = 1024

// FileStream represents an in-memory binary stream.
type FileStream struct {
	sType StreamType
	info  os.FileInfo
	f     *os.File
	bs    *ByteStream
}

// Assert interface implementation checks
var _ Stream = (*FileStream)(nil)

// NewFileStream creates a new binary stream from a memory mapped file).
func NewFileStream(filename string) (*FileStream, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	info, err := f.Stat()
	if err != nil {
		f.Close()
		return nil, err
	}
	// Memory map the file insead of using read/write.
	data, err := mmap.Map(f, mmap.RDONLY, 0)
	if err != nil {
		f.Close()
		return nil, err
	}
	bs, err := NewByteStream(data)
	if err != nil {
		f.Close()
		return nil, err
	}
	return &FileStream{
		sType: FILE,
		info:  info,
		f:     f,
		bs:    bs,
	}, nil
}

// Len returns the current binary stream size.
func (fs *FileStream) Len() int {
	return fs.bs.Len()
}

// Pos returns the current position within the binary stream.
func (fs *FileStream) Pos() int {
	return fs.bs.pos
}

// Read len(b) bytes from the underlying stream.
func (fs *FileStream) Read(b []byte) (n int, err error) {
	return fs.bs.Read(b)
}

// ReadAt len(b) bytes from the underlying stream at a given offset.
func (fs *FileStream) ReadAt(b []byte, off int64) (n int, err error) {
	return fs.bs.ReadAt(b, off)
}

// Seek moves the stream iterator position to offset starting from whence.
func (fs *FileStream) Seek(off int64, whence int) (n int64, err error) {
	return fs.bs.Seek(off, whence)
}

// ReadUint8 reads a 1 byte little endian unsigned integer.
func (fs *FileStream) ReadUint8(off int64) (uint8, error) {
	return fs.bs.ReadUint8(off)
}

// ReadUint16 reads a 2 byte little endian unsigned integer.
func (fs *FileStream) ReadUint16(off int64) (uint16, error) {
	return fs.bs.ReadUint16(off)
}

// ReadUint32 reads a 4 byte little endian unsigned integer.
func (fs *FileStream) ReadUint32(off int64) (uint32, error) {
	return fs.bs.ReadUint32(off)
}

// ReadUint64 reads a 8 byte little endian unsigned integer.
func (fs *FileStream) ReadUint64(off int64) (uint64, error) {

	return fs.bs.ReadUint64(off)
}

// IsEOF checks if we reached the end of the bytestream.
func (fs *FileStream) IsEOF() bool {
	// a bytestream wraps the bytereader interface
	// the Len method returns the number of unread bytes
	// in the underlying stream.
	n, err := fs.f.Read(nil)
	if n == 0 || err == io.EOF {
		return true
	}
	return false
}

// Close underlying filestream.
func (fs *FileStream) Close() error {
	return fs.f.Close()
}

repository: saferwall/binstream

repo_name: saferwall/binstream

branch_name: refs/heads/main

extension: go


text:
SUMMARY = "Simple Qt5 Quick application"
SECTION = "examples"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
PV = "0.1+git${SRCPV}"

DEPENDS += "qttools-native qtbase qtdeclarative qtquickcontrols2"

SRCREV = "${AUTOREV}"
SRC_URI = "git://github.com/dliess/FilterDraw.git"

S = "${WORKDIR}/git"

inherit cmake
EXTRA_OECMAKE += "-DOE_QMAKE_PATH_EXTERNAL_HOST_BINS=${STAGING_DIR_NATIVE}/${bindir}"

do_install() {
      install -d ${D}${bindir}
      install -m 0755 FilterDraw ${D}${bindir}
}


text:
package mssql

import (
	"context"
	"fmt"
	"math/rand"
	"strings"
	"testing"
	"time"

	"github.com/go-xorm/xorm"
	"github.com/grafana/grafana/pkg/components/securejsondata"
	"github.com/grafana/grafana/pkg/components/simplejson"
	"github.com/grafana/grafana/pkg/models"
	"github.com/grafana/grafana/pkg/services/sqlstore/sqlutil"
	"github.com/grafana/grafana/pkg/tsdb"
	"github.com/grafana/grafana/pkg/tsdb/sqleng"
	. "github.com/smartystreets/goconvey/convey"
)

// To run this test, remove the Skip from SkipConvey
// The tests require a MSSQL db named grafanatest and a user/password grafana/Password!
// Use the docker/blocks/mssql_tests/docker-compose.yaml to spin up a
// preconfigured MSSQL server suitable for running these tests.
// There is also a datasource and dashboard provisioned by devenv scripts that you can
// use to verify that the generated data are vizualized as expected, see
// devenv/README.md for setup instructions.
// If needed, change the variable below to the IP address of the database.
var serverIP = "localhost"

func TestMSSQL(t *testing.T) {
	SkipConvey("MSSQL", t, func() {
		x := InitMSSQLTestDB(t)

		origXormEngine := sqleng.NewXormEngine
		sqleng.NewXormEngine = func(d, c string) (*xorm.Engine, error) {
			return x, nil
		}

		origInterpolate := sqleng.Interpolate
		sqleng.Interpolate = func(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) {
			return sql, nil
		}

		endpoint, err := newMssqlQueryEndpoint(&models.DataSource{
			JsonData:       simplejson.New(),
			SecureJsonData: securejsondata.SecureJsonData{},
		})
		So(err, ShouldBeNil)

		sess := x.NewSession()
		fromStart := time.Date(2018, 3, 15, 13, 0, 0, 0, time.UTC).In(time.Local)

		Reset(func() {
			sess.Close()
			sqleng.NewXormEngine = origXormEngine
			sqleng.Interpolate = origInterpolate
		})

		Convey("Given a table with different native data types", func() {
			sql := `
					IF OBJECT_ID('dbo.[mssql_types]', 'U') IS NOT NULL
						DROP TABLE dbo.[mssql_types]

					CREATE TABLE [mssql_types] (
						c_bit bit,

						c_tinyint tinyint,
						c_smallint smallint,
						c_int int,
						c_bigint bigint,

						c_money money,
						c_smallmoney smallmoney,
						c_numeric numeric(10,5),
						c_real real,
						c_decimal decimal(10,2),
						c_float float,

						c_char char(10),
						c_varchar varchar(10),
						c_text text,

						c_nchar nchar(12),
						c_nvarchar nvarchar(12),
						c_ntext ntext,

						c_datetime datetime,
						c_datetime2 datetime2,
						c_smalldatetime smalldatetime,
						c_date date,
						c_time time,
						c_datetimeoffset datetimeoffset
					)
				`

			_, err := sess.Exec(sql)
			So(err, ShouldBeNil)

			dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
			dtFormat := "2006-01-02 15:04:05.999999999"
			d := dt.Format(dtFormat)
			dt2 := time.Date(2018, 3, 14, 21, 20, 6, 8896406e2, time.UTC)
			dt2Format := "2006-01-02 15:04:05.999999999 -07:00"
			d2 := dt2.Format(dt2Format)

			sql = fmt.Sprintf(`
				INSERT INTO [mssql_types]
				SELECT
		    1, 5, 20020, 980300, 1420070400, '$20000.15', '£2.15', 12345.12,
		    1.11, 2.22, 3.33,
					'char10', 'varchar10', 'text',
					N'☺nchar12☺', N'☺nvarchar12☺', N'☺text☺',
					CAST('%s' AS DATETIME), CAST('%s' AS DATETIME2), CAST('%s' AS SMALLDATETIME), CAST('%s' AS DATE), CAST('%s' AS TIME), SWITCHOFFSET(CAST('%s' AS DATETIMEOFFSET), '-07:00')
		`, d, d2, d, d, d, d2)

			_, err = sess.Exec(sql)
			So(err, ShouldBeNil)

			Convey("When doing a table query should map MSSQL column types to Go types", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT * FROM mssql_types",
								"format": "table",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				queryResult := resp.Results["A"]
				So(err, ShouldBeNil)

				column := queryResult.Tables[0].Rows[0]

				So(column[0].(bool), ShouldEqual, true)

				So(column[1].(int64), ShouldEqual, 5)
				So(column[2].(int64), ShouldEqual, 20020)
				So(column[3].(int64), ShouldEqual, 980300)
				So(column[4].(int64), ShouldEqual, 1420070400)

				So(column[5].(float64), ShouldEqual, 20000.15)
				So(column[6].(float64), ShouldEqual, 2.15)
				So(column[7].(float64), ShouldEqual, 12345.12)
				So(column[8].(float64), ShouldEqual, 1.1100000143051147)
				So(column[9].(float64), ShouldEqual, 2.22)
				So(column[10].(float64), ShouldEqual, 3.33)

				So(column[11].(string), ShouldEqual, "char10    ")
				So(column[12].(string), ShouldEqual, "varchar10")
				So(column[13].(string), ShouldEqual, "text")

				So(column[14].(string), ShouldEqual, "☺nchar12☺   ")
				So(column[15].(string), ShouldEqual, "☺nvarchar12☺")
				So(column[16].(string), ShouldEqual, "☺text☺")

				So(column[17].(time.Time), ShouldEqual, dt)
				So(column[18].(time.Time), ShouldEqual, dt2)
				So(column[19].(time.Time), ShouldEqual, dt.Truncate(time.Minute))
				So(column[20].(time.Time), ShouldEqual, dt.Truncate(24*time.Hour))
				So(column[21].(time.Time), ShouldEqual, time.Date(1, 1, 1, dt.Hour(), dt.Minute(), dt.Second(), dt.Nanosecond(), time.UTC))
				So(column[22].(time.Time), ShouldEqual, dt2.In(time.FixedZone("UTC-7", int(-7*60*60))))
			})
		})

		Convey("Given a table with metrics that lacks data for some series ", func() {
			sql := `
					IF OBJECT_ID('dbo.[metric]', 'U') IS NOT NULL
						DROP TABLE dbo.[metric]

					CREATE TABLE [metric] (
						time datetime,
						value int
					)
				`

			_, err := sess.Exec(sql)
			So(err, ShouldBeNil)

			type metric struct {
				Time  time.Time
				Value int64
			}

			series := []*metric{}
			firstRange := genTimeRangeByInterval(fromStart, 10*time.Minute, 10*time.Second)
			secondRange := genTimeRangeByInterval(fromStart.Add(20*time.Minute), 10*time.Minute, 10*time.Second)

			for _, t := range firstRange {
				series = append(series, &metric{
					Time:  t,
					Value: 15,
				})
			}

			for _, t := range secondRange {
				series = append(series, &metric{
					Time:  t,
					Value: 20,
				})
			}

			_, err = sess.InsertMulti(series)
			So(err, ShouldBeNil)

			Convey("When doing a metric query using timeGroup", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT $__timeGroup(time, '5m') AS time, avg(value) as value FROM metric GROUP BY $__timeGroup(time, '5m') ORDER BY 1",
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				points := queryResult.Series[0].Points
				// without fill this should result in 4 buckets
				So(len(points), ShouldEqual, 4)

				dt := fromStart

				for i := 0; i < 2; i++ {
					aValue := points[i][0].Float64
					aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
					So(aValue, ShouldEqual, 15)
					So(aTime, ShouldEqual, dt)
					dt = dt.Add(5 * time.Minute)
				}

				// adjust for 10 minute gap between first and second set of points
				dt = dt.Add(10 * time.Minute)
				for i := 2; i < 4; i++ {
					aValue := points[i][0].Float64
					aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
					So(aValue, ShouldEqual, 20)
					So(aTime, ShouldEqual, dt)
					dt = dt.Add(5 * time.Minute)
				}
			})

			Convey("When doing a metric query using timeGroup with NULL fill enabled", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT $__timeGroup(time, '5m', NULL) AS time, avg(value) as value FROM metric GROUP BY $__timeGroup(time, '5m') ORDER BY 1",
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
					TimeRange: &tsdb.TimeRange{
						From: fmt.Sprintf("%v", fromStart.Unix()*1000),
						To:   fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				points := queryResult.Series[0].Points
				So(len(points), ShouldEqual, 7)

				dt := fromStart

				for i := 0; i < 2; i++ {
					aValue := points[i][0].Float64
					aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
					So(aValue, ShouldEqual, 15)
					So(aTime, ShouldEqual, dt)
					dt = dt.Add(5 * time.Minute)
				}

				// check for NULL values inserted by fill
				So(points[2][0].Valid, ShouldBeFalse)
				So(points[3][0].Valid, ShouldBeFalse)

				// adjust for 10 minute gap between first and second set of points
				dt = dt.Add(10 * time.Minute)
				for i := 4; i < 6; i++ {
					aValue := points[i][0].Float64
					aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
					So(aValue, ShouldEqual, 20)
					So(aTime, ShouldEqual, dt)
					dt = dt.Add(5 * time.Minute)
				}

				So(points[6][0].Valid, ShouldBeFalse)

			})

			Convey("When doing a metric query using timeGroup and $__interval", func() {
				mockInterpolate := sqleng.Interpolate
				sqleng.Interpolate = origInterpolate

				Reset(func() {
					sqleng.Interpolate = mockInterpolate
				})

				Convey("Should replace $__interval", func() {
					query := &tsdb.TsdbQuery{
						Queries: []*tsdb.Query{
							{
								DataSource: &models.DataSource{},
								Model: simplejson.NewFromAny(map[string]interface{}{
									"rawSql": "SELECT $__timeGroup(time, $__interval) AS time, avg(value) as value FROM metric GROUP BY $__timeGroup(time, $__interval) ORDER BY 1",
									"format": "time_series",
								}),
								RefId: "A",
							},
						},
						TimeRange: &tsdb.TimeRange{
							From: fmt.Sprintf("%v", fromStart.Unix()*1000),
							To:   fmt.Sprintf("%v", fromStart.Add(30*time.Minute).Unix()*1000),
						},
					}

					resp, err := endpoint.Query(context.Background(), nil, query)
					So(err, ShouldBeNil)
					queryResult := resp.Results["A"]
					So(queryResult.Error, ShouldBeNil)
					So(queryResult.Meta.Get("sql").MustString(), ShouldEqual, "SELECT FLOOR(DATEDIFF(second, '1970-01-01', time)/60)*60 AS time, avg(value) as value FROM metric GROUP BY FLOOR(DATEDIFF(second, '1970-01-01', time)/60)*60 ORDER BY 1")
				})
			})

			Convey("When doing a metric query using timeGroup with float fill enabled", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT $__timeGroup(time, '5m', 1.5) AS time, avg(value) as value FROM metric GROUP BY $__timeGroup(time, '5m') ORDER BY 1",
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
					TimeRange: &tsdb.TimeRange{
						From: fmt.Sprintf("%v", fromStart.Unix()*1000),
						To:   fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				points := queryResult.Series[0].Points
				So(points[3][0].Float64, ShouldEqual, 1.5)
			})
		})

		Convey("Given a table with metrics having multiple values and measurements", func() {
			type metric_values struct {
				Time                time.Time
				TimeInt64           int64    `xorm:"bigint 'timeInt64' not null"`
				TimeInt64Nullable   *int64   `xorm:"bigint 'timeInt64Nullable' null"`
				TimeFloat64         float64  `xorm:"float 'timeFloat64' not null"`
				TimeFloat64Nullable *float64 `xorm:"float 'timeFloat64Nullable' null"`
				TimeInt32           int32    `xorm:"int(11) 'timeInt32' not null"`
				TimeInt32Nullable   *int32   `xorm:"int(11) 'timeInt32Nullable' null"`
				TimeFloat32         float32  `xorm:"float(11) 'timeFloat32' not null"`
				TimeFloat32Nullable *float32 `xorm:"float(11) 'timeFloat32Nullable' null"`
				Measurement         string
				ValueOne            int64 `xorm:"integer 'valueOne'"`
				ValueTwo            int64 `xorm:"integer 'valueTwo'"`
			}

			if exist, err := sess.IsTableExist(metric_values{}); err != nil || exist {
				So(err, ShouldBeNil)
				err = sess.DropTable(metric_values{})
				So(err, ShouldBeNil)
			}
			err := sess.CreateTable(metric_values{})
			So(err, ShouldBeNil)

			rand.Seed(time.Now().Unix())
			rnd := func(min, max int64) int64 {
				return rand.Int63n(max-min) + min
			}

			var tInitial time.Time

			series := []*metric_values{}
			for i, t := range genTimeRangeByInterval(fromStart.Add(-30*time.Minute), 90*time.Minute, 5*time.Minute) {
				if i == 0 {
					tInitial = t
				}
				tSeconds := t.Unix()
				tSecondsInt32 := int32(tSeconds)
				tSecondsFloat32 := float32(tSeconds)
				tMilliseconds := tSeconds * 1e3
				tMillisecondsFloat := float64(tMilliseconds)
				first := metric_values{
					Time:                t,
					TimeInt64:           tMilliseconds,
					TimeInt64Nullable:   &(tMilliseconds),
					TimeFloat64:         tMillisecondsFloat,
					TimeFloat64Nullable: &tMillisecondsFloat,
					TimeInt32:           tSecondsInt32,
					TimeInt32Nullable:   &tSecondsInt32,
					TimeFloat32:         tSecondsFloat32,
					TimeFloat32Nullable: &tSecondsFloat32,
					Measurement:         "Metric A",
					ValueOne:            rnd(0, 100),
					ValueTwo:            rnd(0, 100),
				}
				second := first
				second.Measurement = "Metric B"
				second.ValueOne = rnd(0, 100)
				second.ValueTwo = rnd(0, 100)

				series = append(series, &first)
				series = append(series, &second)
			}

			_, err = sess.InsertMulti(series)
			So(err, ShouldBeNil)

			Convey("When doing a metric query using epoch (int64) as time column and value column (int64) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeInt64 as time, timeInt64 FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
			})

			Convey("When doing a metric query using epoch (int64 nullable) as time column and value column (int64 nullable) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeInt64Nullable as time, timeInt64Nullable FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
			})

			Convey("When doing a metric query using epoch (float64) as time column and value column (float64) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeFloat64 as time, timeFloat64 FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
			})

			Convey("When doing a metric query using epoch (float64 nullable) as time column and value column (float64 nullable) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeFloat64Nullable as time, timeFloat64Nullable FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
			})

			Convey("When doing a metric query using epoch (int32) as time column and value column (int32) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeInt32 as time, timeInt32 FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
			})

			Convey("When doing a metric query using epoch (int32 nullable) as time column and value column (int32 nullable) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeInt32Nullable as time, timeInt32Nullable FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
			})

			Convey("When doing a metric query using epoch (float32) as time column and value column (float32) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeFloat32 as time, timeFloat32 FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(float32(tInitial.Unix()))*1e3)
			})

			Convey("When doing a metric query using epoch (float32 nullable) as time column and value column (float32 nullable) should return metric with time in milliseconds", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT TOP 1 timeFloat32Nullable as time, timeFloat32Nullable FROM metric_values ORDER BY time`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 1)
				So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(float32(tInitial.Unix()))*1e3)
			})

			Convey("When doing a metric query grouping by time and select metric column should return correct series", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT $__timeEpoch(time), measurement + ' - value one' as metric, valueOne FROM metric_values ORDER BY 1",
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 2)
				So(queryResult.Series[0].Name, ShouldEqual, "Metric A - value one")
				So(queryResult.Series[1].Name, ShouldEqual, "Metric B - value one")
			})

			Convey("When doing a metric query grouping by time should return correct series", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT $__timeEpoch(time), valueOne, valueTwo FROM metric_values ORDER BY 1",
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 2)
				So(queryResult.Series[0].Name, ShouldEqual, "valueOne")
				So(queryResult.Series[1].Name, ShouldEqual, "valueTwo")
			})

			Convey("When doing a metric query with metric column and multiple value columns", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT $__timeEpoch(time), measurement, valueOne, valueTwo FROM metric_values ORDER BY 1",
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)

				So(len(queryResult.Series), ShouldEqual, 4)
				So(queryResult.Series[0].Name, ShouldEqual, "Metric A valueOne")
				So(queryResult.Series[1].Name, ShouldEqual, "Metric A valueTwo")
				So(queryResult.Series[2].Name, ShouldEqual, "Metric B valueOne")
				So(queryResult.Series[3].Name, ShouldEqual, "Metric B valueTwo")
			})

			Convey("When doing a query with timeFrom,timeTo,unixEpochFrom,unixEpochTo macros", func() {
				sqleng.Interpolate = origInterpolate
				query := &tsdb.TsdbQuery{
					TimeRange: tsdb.NewFakeTimeRange("5m", "now", fromStart),
					Queries: []*tsdb.Query{
						{
							DataSource: &models.DataSource{JsonData: simplejson.New()},
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT time FROM metric_values WHERE time > $__timeFrom() OR time < $__timeFrom() OR 1 < $__unixEpochFrom() OR $__unixEpochTo() > 1 ORDER BY 1`,
								"format": "time_series",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)
				So(queryResult.Meta.Get("sql").MustString(), ShouldEqual, "SELECT time FROM metric_values WHERE time > '2018-03-15T12:55:00Z' OR time < '2018-03-15T12:55:00Z' OR 1 < 1521118500 OR 1521118800 > 1 ORDER BY 1")

			})

			Convey("Given a stored procedure that takes @from and @to in epoch time", func() {
				sql := `
						IF object_id('sp_test_epoch') IS NOT NULL
							DROP PROCEDURE sp_test_epoch
					`

				_, err := sess.Exec(sql)
				So(err, ShouldBeNil)

				sql = `
						CREATE PROCEDURE sp_test_epoch(
							@from 		int,
							@to 			int,
							@interval nvarchar(50) = '5m',
							@metric 	nvarchar(200) = 'ALL'
						)	AS
						BEGIN
							DECLARE @dInterval int
							SELECT @dInterval = 300

							IF @interval = '10m'
								SELECT @dInterval = 600

							SELECT
								CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval as time,
								measurement as metric,
								avg(valueOne) as valueOne,
								avg(valueTwo) as valueTwo
							FROM
								metric_values
							WHERE
								time BETWEEN DATEADD(s, @from, '1970-01-01') AND DATEADD(s, @to, '1970-01-01') AND
								(@metric = 'ALL' OR measurement = @metric)
							GROUP BY
								CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval,
								measurement
							ORDER BY 1
						END
					`

				_, err = sess.Exec(sql)
				So(err, ShouldBeNil)

				Convey("When doing a metric query using stored procedure should return correct result", func() {
					sqleng.Interpolate = origInterpolate
					query := &tsdb.TsdbQuery{
						Queries: []*tsdb.Query{
							{
								DataSource: &models.DataSource{JsonData: simplejson.New()},
								Model: simplejson.NewFromAny(map[string]interface{}{
									"rawSql": `DECLARE
											@from int = $__unixEpochFrom(),
											@to int = $__unixEpochTo()

											EXEC dbo.sp_test_epoch @from, @to`,
									"format": "time_series",
								}),
								RefId: "A",
							},
						},
						TimeRange: &tsdb.TimeRange{
							From: "1521117000000",
							To:   "1521122100000",
						},
					}

					resp, err := endpoint.Query(context.Background(), nil, query)
					queryResult := resp.Results["A"]
					So(err, ShouldBeNil)
					So(queryResult.Error, ShouldBeNil)

					So(len(queryResult.Series), ShouldEqual, 4)
					So(queryResult.Series[0].Name, ShouldEqual, "Metric A valueOne")
					So(queryResult.Series[1].Name, ShouldEqual, "Metric A valueTwo")
					So(queryResult.Series[2].Name, ShouldEqual, "Metric B valueOne")
					So(queryResult.Series[3].Name, ShouldEqual, "Metric B valueTwo")
				})
			})

			Convey("Given a stored procedure that takes @from and @to in datetime", func() {
				sql := `
						IF object_id('sp_test_datetime') IS NOT NULL
							DROP PROCEDURE sp_test_datetime
					`

				_, err := sess.Exec(sql)
				So(err, ShouldBeNil)

				sql = `
						CREATE PROCEDURE sp_test_datetime(
							@from 		datetime,
							@to 			datetime,
							@interval nvarchar(50) = '5m',
							@metric 	nvarchar(200) = 'ALL'
						)	AS
						BEGIN
							DECLARE @dInterval int
							SELECT @dInterval = 300

							IF @interval = '10m'
								SELECT @dInterval = 600

							SELECT
								CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval as time,
								measurement as metric,
								avg(valueOne) as valueOne,
								avg(valueTwo) as valueTwo
							FROM
								metric_values
							WHERE
								time BETWEEN @from AND @to AND
								(@metric = 'ALL' OR measurement = @metric)
							GROUP BY
								CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval,
								measurement
							ORDER BY 1
						END
					`

				_, err = sess.Exec(sql)
				So(err, ShouldBeNil)

				Convey("When doing a metric query using stored procedure should return correct result", func() {
					sqleng.Interpolate = origInterpolate
					query := &tsdb.TsdbQuery{
						Queries: []*tsdb.Query{
							{
								DataSource: &models.DataSource{JsonData: simplejson.New()},
								Model: simplejson.NewFromAny(map[string]interface{}{
									"rawSql": `DECLARE
											@from int = $__unixEpochFrom(),
											@to int = $__unixEpochTo()

											EXEC dbo.sp_test_epoch @from, @to`,
									"format": "time_series",
								}),
								RefId: "A",
							},
						},
						TimeRange: &tsdb.TimeRange{
							From: "1521117000000",
							To:   "1521122100000",
						},
					}

					resp, err := endpoint.Query(context.Background(), nil, query)
					queryResult := resp.Results["A"]
					So(err, ShouldBeNil)
					So(queryResult.Error, ShouldBeNil)

					So(len(queryResult.Series), ShouldEqual, 4)
					So(queryResult.Series[0].Name, ShouldEqual, "Metric A valueOne")
					So(queryResult.Series[1].Name, ShouldEqual, "Metric A valueTwo")
					So(queryResult.Series[2].Name, ShouldEqual, "Metric B valueOne")
					So(queryResult.Series[3].Name, ShouldEqual, "Metric B valueTwo")
				})
			})
		})

		Convey("Given a table with event data", func() {
			sql := `
				IF OBJECT_ID('dbo.[event]', 'U') IS NOT NULL
					DROP TABLE dbo.[event]

				CREATE TABLE [event] (
					time_sec int,
					description nvarchar(100),
					tags nvarchar(100),
				)
			`

			_, err := sess.Exec(sql)
			So(err, ShouldBeNil)

			type event struct {
				TimeSec     int64
				Description string
				Tags        string
			}

			events := []*event{}
			for _, t := range genTimeRangeByInterval(fromStart.Add(-20*time.Minute), 60*time.Minute, 25*time.Minute) {
				events = append(events, &event{
					TimeSec:     t.Unix(),
					Description: "Someone deployed something",
					Tags:        "deploy",
				})
				events = append(events, &event{
					TimeSec:     t.Add(5 * time.Minute).Unix(),
					Description: "New support ticket registered",
					Tags:        "ticket",
				})
			}

			for _, e := range events {
				sql = fmt.Sprintf(`
					INSERT [event] (time_sec, description, tags)
					VALUES(%d, '%s', '%s')
				`, e.TimeSec, e.Description, e.Tags)

				_, err = sess.Exec(sql)
				So(err, ShouldBeNil)
			}

			Convey("When doing an annotation query of deploy events should return expected result", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT time_sec as time, description as [text], tags FROM [event] WHERE $__unixEpochFilter(time_sec) AND tags='deploy' ORDER BY 1 ASC",
								"format": "table",
							}),
							RefId: "Deploys",
						},
					},
					TimeRange: &tsdb.TimeRange{
						From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
						To:   fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				queryResult := resp.Results["Deploys"]
				So(err, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
			})

			Convey("When doing an annotation query of ticket events should return expected result", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": "SELECT time_sec as time, description as [text], tags FROM [event] WHERE $__unixEpochFilter(time_sec) AND tags='ticket' ORDER BY 1 ASC",
								"format": "table",
							}),
							RefId: "Tickets",
						},
					},
					TimeRange: &tsdb.TimeRange{
						From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
						To:   fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				queryResult := resp.Results["Tickets"]
				So(err, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
			})

			Convey("When doing an annotation query with a time column in datetime format", func() {
				dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
				dtFormat := "2006-01-02 15:04:05.999999999"

				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": fmt.Sprintf(`SELECT
									CAST('%s' AS DATETIME) as time,
									'message' as text,
									'tag1,tag2' as tags
								`, dt.Format(dtFormat)),
								"format": "table",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
				columns := queryResult.Tables[0].Rows[0]

				//Should be in milliseconds
				So(columns[0].(float64), ShouldEqual, float64(dt.UnixNano()/1e6))
			})

			Convey("When doing an annotation query with a time column in epoch second format should return ms", func() {
				dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)

				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": fmt.Sprintf(`SELECT
									 %d as time,
									'message' as text,
									'tag1,tag2' as tags
								`, dt.Unix()),
								"format": "table",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
				columns := queryResult.Tables[0].Rows[0]

				//Should be in milliseconds
				So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
			})

			Convey("When doing an annotation query with a time column in epoch second format (int) should return ms", func() {
				dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)

				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": fmt.Sprintf(`SELECT
									 cast(%d as int) as time,
									'message' as text,
									'tag1,tag2' as tags
								`, dt.Unix()),
								"format": "table",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
				columns := queryResult.Tables[0].Rows[0]

				//Should be in milliseconds
				So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
			})

			Convey("When doing an annotation query with a time column in epoch millisecond format should return ms", func() {
				dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)

				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": fmt.Sprintf(`SELECT
									 %d as time,
									'message' as text,
									'tag1,tag2' as tags
								`, dt.Unix()*1000),
								"format": "table",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
				columns := queryResult.Tables[0].Rows[0]

				//Should be in milliseconds
				So(columns[0].(float64), ShouldEqual, float64(dt.Unix()*1000))
			})

			Convey("When doing an annotation query with a time column holding a bigint null value should return nil", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT
									 cast(null as bigint) as time,
									'message' as text,
									'tag1,tag2' as tags
								`,
								"format": "table",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
				columns := queryResult.Tables[0].Rows[0]

				//Should be in milliseconds
				So(columns[0], ShouldBeNil)
			})

			Convey("When doing an annotation query with a time column holding a datetime null value should return nil", func() {
				query := &tsdb.TsdbQuery{
					Queries: []*tsdb.Query{
						{
							Model: simplejson.NewFromAny(map[string]interface{}{
								"rawSql": `SELECT
									 cast(null as datetime) as time,
									'message' as text,
									'tag1,tag2' as tags
								`,
								"format": "table",
							}),
							RefId: "A",
						},
					},
				}

				resp, err := endpoint.Query(context.Background(), nil, query)
				So(err, ShouldBeNil)
				queryResult := resp.Results["A"]
				So(queryResult.Error, ShouldBeNil)
				So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
				columns := queryResult.Tables[0].Rows[0]

				//Should be in milliseconds
				So(columns[0], ShouldBeNil)
			})
		})
	})
}

func InitMSSQLTestDB(t *testing.T) *xorm.Engine {
	x, err := xorm.NewEngine(sqlutil.TestDB_Mssql.DriverName, strings.Replace(sqlutil.TestDB_Mssql.ConnStr, "localhost", serverIP, 1))
	if err != nil {
		t.Fatalf("Failed to init mssql db %v", err)
	}

	x.DatabaseTZ = time.UTC
	x.TZLocation = time.UTC

	// x.ShowSQL()

	return x
}

func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
	durationSec := int64(duration.Seconds())
	intervalSec := int64(interval.Seconds())
	timeRange := []time.Time{}

	for i := int64(0); i < durationSec; i += intervalSec {
		timeRange = append(timeRange, from)
		from = from.Add(time.Duration(int64(time.Second) * intervalSec))
	}

	return timeRange
}

gha_language: TypeScript


text:
inherit bug-java-library

PR = "r1"

SRC_URI = "file://osgi.jar.donotunpack"

S = "${WORKDIR}"

JARFILENAME = "osgi.jar"

do_removebinaries() {
   mv ${WORKDIR}/osgi.jar.donotunpack ${WORKDIR}/osgi.jar
}

PACKAGES = ""

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
DESCRIPTION = "RapidJSON is a JSON parser and generator for C++. It was inspired by RapidXml."

HOMEPAGE = "https://github.com/miloyip/rapidjson"

LICENSE = "MIT"

LIC_FILES_CHKSUM = "file://license.txt;md5=cd8fb916014db94987ec260fd415a90d"

SRC_URI = "git://github.com/miloyip/rapidjson.git;branch=master"

SRCREV="bb84ff2ffe289bf7ac305d2d95172ec58fb63797"

PR="r1"

PV = "0.0.0+gitr${SRCREV}"

S="${WORKDIR}/git"

inherit cmake

EXTRA_OECMAKE = "-DRAPIDJSON_BUILD_TESTS=OFF"

FILES_${PN}-dev += "${libdir}/cmake"

ALLOW_EMPTY_${PN} = "1"

repository: sbarasco/meta-table

repo_name: sbarasco/meta-table


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

package configprovider

import (
	"context"
	"fmt"
	"strings"

	"github.com/spf13/cast"
	"go.opentelemetry.io/collector/config"
	"go.opentelemetry.io/collector/config/configparser"
	"go.opentelemetry.io/collector/config/experimental/configsource"
)

const (
	configSourcesKey = "config_sources"
)

// Private error types to help with testability.
type (
	errInvalidTypeAndNameKey struct{ error }
	errUnknownType           struct{ error }
	errUnmarshalError        struct{ error }
	errDuplicateName         struct{ error }
)

// Load reads the configuration for ConfigSource objects from the given parser and returns a map
// from the full name of config sources to the respective ConfigSettings.
func Load(ctx context.Context, v *configparser.Parser, factories Factories) (map[string]ConfigSettings, error) {
	processedParser, err := processParser(ctx, v)
	if err != nil {
		return nil, err
	}

	cfgSrcSettings, err := loadSettings(cast.ToStringMap(processedParser.Get(configSourcesKey)), factories)
	if err != nil {
		return nil, err
	}

	return cfgSrcSettings, nil
}

// processParser prepares a configparser.Parser to be used to load config source settings.
func processParser(ctx context.Context, v *configparser.Parser) (*configparser.Parser, error) {
	// Use a manager to resolve environment variables with a syntax consistent with
	// the config source usage.
	manager := newManager(make(map[string]configsource.ConfigSource))
	defer func() {
		_ = manager.Close(ctx)
	}()

	processedParser := configparser.NewParser()
	for _, key := range v.AllKeys() {
		if !strings.HasPrefix(key, configSourcesKey) {
			// In Load we only care about config sources, ignore everything else.
			continue
		}

		value, err := manager.expandStringValues(ctx, v.Get(key))
		if err != nil {
			return nil, err
		}
		processedParser.Set(key, value)
	}

	return processedParser, nil
}

func loadSettings(css map[string]interface{}, factories Factories) (map[string]ConfigSettings, error) {
	// Prepare resulting map.
	cfgSrcToSettings := make(map[string]ConfigSettings)

	// Iterate over extensions and create a config for each.
	for key, value := range css {
		settingsParser := configparser.NewParserFromStringMap(cast.ToStringMap(value))

		// Decode the key into type and fullName components.
		componentID, err := config.NewIDFromString(key)
		if err != nil {
			return nil, &errInvalidTypeAndNameKey{fmt.Errorf("invalid %s type and name key %q: %v", configSourcesKey, key, err)}
		}
		typeStr := componentID.Type()
		fullName := componentID.String()

		// Find the factory based on "type" that we read from config source.
		factory := factories[typeStr]
		if factory == nil {
			return nil, &errUnknownType{fmt.Errorf("unknown %s type %q for %s", configSourcesKey, typeStr, fullName)}
		}

		// Create the default config.
		cfgSrcSettings := factory.CreateDefaultConfig()
		cfgSrcSettings.SetName(fullName)

		// Now that the default settings struct is created we can Unmarshal into it
		// and it will apply user-defined config on top of the default.
		if err := settingsParser.UnmarshalExact(&cfgSrcSettings); err != nil {
			return nil, &errUnmarshalError{fmt.Errorf("error reading %s configuration for %s: %v", configSourcesKey, fullName, err)}
		}

		if cfgSrcToSettings[fullName] != nil {
			return nil, &errDuplicateName{fmt.Errorf("duplicate %s name %s", configSourcesKey, fullName)}
		}

		cfgSrcToSettings[fullName] = cfgSrcSettings
	}

	return cfgSrcToSettings, nil
}

repository: splunk/splunk-otel-collector

repo_name: splunk/splunk-otel-collector


text:
package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"

	"github.com/koding/kite/config"
	"github.com/koding/kite/kontrol"
	"github.com/koding/multiconfig"
)

type Kontrol struct {
	Ip          string
	Port        int
	TLSCertFile string
	TLSKeyFile  string
	RegisterUrl string

	Initial    bool
	Username   string
	KontrolURL string

	PublicKeyFile  string `required:"true"`
	PrivateKeyFile string `required:"true"`

	Machines []string
	Version  string

	Postgres struct {
		Host     string `default:"localhost"`
		Port     int    `default:"5432"`
		Username string `required:"true"`
		Password string
		DBName   string `required:"true" `
	}
}

var (
	// Kite server options
	ip          = flag.String("ip", "0.0.0.0", "")
	port        = flag.Int("port", 4000, "")
	tlsCertFile = flag.String("tls-cert", "", "TLS certificate file")
	tlsKeyFile  = flag.String("tls-key", "", "TLS key file")
	registerURL = flag.String("register-url", "", "Change self register URL")

	// For self register and initial first key on a machine
	initial    = flag.Bool("init", false, "create a new kite.key")
	username   = flag.String("username", "", "")
	kontrolURL = flag.String("kontrol-url", "", "")

	// For signing/validating tokens
	publicKeyFile  = flag.String("public-key", "", "Public RSA key")
	privateKeyFile = flag.String("private-key", "", "Private RSA key")

	// etcd instance options
	machines = flag.String("machines", "", "comma seperated peer addresses")

	version = flag.String("version", "0.0.1", "version of kontrol")
)

func main() {
	conf := new(Kontrol)

	multiconfig.New().MustLoad(conf)

	publicKey, err := ioutil.ReadFile(conf.PublicKeyFile)
	if err != nil {
		log.Fatalf("cannot read public key file: %s", err.Error())
	}

	privateKey, err := ioutil.ReadFile(conf.PrivateKeyFile)
	if err != nil {
		log.Fatalf("cannot read private key file: %s", err.Error())
	}

	if conf.Initial {
		initialKey(publicKey, privateKey)
		os.Exit(0)
	}

	kiteConf := config.MustGet()
	kiteConf.IP = conf.Ip
	kiteConf.Port = conf.Port

	k := kontrol.New(kiteConf, conf.Version, string(publicKey), string(privateKey))

	if conf.TLSCertFile != "" || conf.TLSKeyFile != "" {
		cert, err := tls.LoadX509KeyPair(conf.TLSCertFile, conf.TLSKeyFile)
		if err != nil {
			log.Fatalf("cannot load TLS certificate: %s", err.Error())
		}

		k.Kite.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
	}

	if conf.RegisterUrl != "" {
		k.RegisterURL = conf.RegisterUrl
	}

	switch os.Getenv("KONTROL_STORAGE") {
	case "etcd":
		k.SetStorage(kontrol.NewEtcd(conf.Machines, k.Kite.Log))
	case "postgres":
		postgresConf := &kontrol.PostgresConfig{
			Host:     conf.Postgres.Host,
			Port:     conf.Postgres.Port,
			Username: conf.Postgres.Username,
			Password: conf.Postgres.Password,
			DBName:   conf.Postgres.DBName,
		}

		k.SetStorage(kontrol.NewPostgres(postgresConf, k.Kite.Log))
	}

	k.Run()
}

func initialKey(publicKey, privateKey []byte) {
	conf := config.New()

	if *username == "" {
		log.Fatalln("empty username")
	}
	conf.Username = *username

	_, err := url.Parse(*kontrolURL)
	if err != nil {
		log.Fatalln("cannot parse kontrol URL")
	}

	conf.KontrolURL = *kontrolURL

	k := kontrol.New(conf, *version, string(publicKey), string(privateKey))
	err = k.InitializeSelf()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("kite.key is written to ~/.kite/kite.key. You can see it with:\n\tkite showkey")
}

repository: cihangir/kite

repo_name: cihangir/kite


text:
package main

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
	"sync"

	"github.com/PuerkitoBio/goquery"
	"github.com/nektro/go-util/types"
	"github.com/nektro/go-util/util"
	"github.com/nektro/go-util/vflag"
	"github.com/schollz/progressbar/v3"
)

var (
	sites []string
	expor []string
	wg    = new(sync.WaitGroup)
	sem   = types.NewSemaphore(6)
)

func main() {
	vflag.StringArrayVar(&sites, "site", []string{}, "")
	vflag.Parse()

	dir1 := "./data"
	os.Mkdir(dir1, os.ModePerm)
	logg, _ := os.Create(dir1 + "/errors.log")
	for _, item := range sites {
		urlO, err := url.Parse(item)
		util.DieOnError(err)
		dir2 := dir1 + "/" + urlO.Host

		last := ""
		l := 0
		j := 0
		bar := progressbar.Default(int64(1), urlO.Host)

		var doc *goquery.Document

		for {
			i := 0
			u1 := item + "?title=Special:AllPages&from=" + last
			fetchDoc(http.MethodGet, u1, "#bodyContent a", "#WikiaPage a").Each(func(_ int, el *goquery.Selection) {
				h, _ := el.Attr("href")
				if h[0] == '#' {
					return
				}
				if strings.Contains(h, "Special:AllPages") {
					return
				}
				if strings.HasPrefix(h, "https://") || strings.HasPrefix(h, "http://") {
					return
				}
				if l > 0 && i == 0 {
					i++
					return
				}
				h = strings.TrimPrefix(h, "/wiki")
				h = strings.TrimPrefix(h, "/index.php")
				h = strings.TrimPrefix(h, "/")
				last = h
				i++
				j++
				bar.ChangeMax(j)
				//
				u2 := item + "?title=Special:Export&action=submit&history=1&pages=" + h
				go func() {
					wg.Add(1)
					sem.Add()
					defer sem.Done()
					defer bar.Add(1)
					defer wg.Done()

					req, _ := http.NewRequest(http.MethodGet, u2, nil)
					req.Header.Add("user-agent", "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0")
					req.Header.Add("connection", "close")
					res, _ := http.DefaultClient.Do(req)
					bys, _ := ioutil.ReadAll(res.Body)

					d, _ := goquery.NewDocumentFromReader(bytes.NewReader(bys))
					if doc == nil {
						doc = d
						return
					}
					ns := d.Find("page").Nodes
					if len(ns) > 0 {
						doc.Find("siteinfo").AppendNodes(ns[0])
					} else {
						fmt.Fprintln(logg, h)
					}
				}()
			})
			if l == 0 {
				l = i
			}
			if i < l {
				break
			}
		}
		wg.Wait()
		bar.Add(1)

		f, _ := os.Create(dir2 + ".xml.gz")
		w := gzip.NewWriter(f)
		s, _ := doc.Find("mediawiki").Parent().Html()
		fmt.Fprintln(w, s)
	}
	wg.Wait()
}

func fetchDoc(method, urlS string, selctor ...string) *goquery.Selection {
	req, _ := http.NewRequest(method, urlS, nil)
	res, _ := http.DefaultClient.Do(req)
	doc, _ := goquery.NewDocumentFromResponse(res)
	for _, item := range selctor {
		s := doc.Find(item)
		if s.Size() > 0 {
			return s
		}
	}
	return nil
}

repository: nektro/mediawiki-dl

repo_name: nektro/mediawiki-dl


text:
@article{2020:Schreiner:etal:LDC,
        Author = {Scheiner, Sylvia L.R. and Lane Schwartz and Hunt, Benjamin and Emily Chen},
        Title = {Multidirectional leveraging for computational morphology and language documentation and revitalization},
        Journal = {Language Documentation \& Conservation},
        Month = {January},
        Year = {2020},
        Volume = {14},
        Pages = {69--86},
        Publisher = {University of Hawaii Press},
        Url = {http://hdl.handle.net/10125/24917}
}

extension: bib


text:
file(REMOVE_RECURSE
  "CMakeFiles/GerenciadorFinaceiro.dir/main.c.obj"
  "CMakeFiles/GerenciadorFinaceiro.dir/Contas.c.obj"
  "GerenciadorFinaceiro.pdb"
  "GerenciadorFinaceiro.exe"
  "GerenciadorFinaceiro.exe.manifest"
  "libGerenciadorFinaceiro.dll.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang C)
  include(CMakeFiles/GerenciadorFinaceiro.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

repository: RondineleG/Univali

repo_name: RondineleG/Univali

extension: cmake


text:
package main

import (
	"fmt"

	"github.com/wdevore/RangerGo/api"
	"github.com/wdevore/RangerGo/engine"
)

var ranger api.IEngine

// This example just runs to basic scenes and then exits.
// Each scene pauses for a few seconds.

func init() {
	world := engine.NewWorld("RangerGo", 1.5, "..")

	ranger = engine.New(world)

	splash := newBasicSplashScene("Splash", nil)
	splash.Build(world)

	boot := newBasicBootScene("Boot", splash)

	ranger.PushStart(boot)
}

func main() {
	fmt.Println("Minimal")

	ranger.Configure()

	ranger.Start()

	ranger.End()
}

repository: wdevore/RangerGo

repo_name: wdevore/RangerGo


text:
package command

import "github.com/spf13/cobra"

type ServerOptions struct {
	// Http bind `:3000`
	BindHTTP string

	// rpc bind `:3001`
	BindRPC string

	// HTTP endpoint
	HTTPEndpoint string

	// Binaries directory
	BinDir string

	// Storage init
	//
	//   <storage-type>:option=...,option=...
	//   block:root=data,split=2,max-files=32,pool=32
	//
	Storage string
}

type ServerCmd struct {
}

func (c *ServerCmd) Init(cc *cobra.Command) {
	cc.Use = "server"
	cc.Short = "bar server"
}

func (c *ServerCmd) Run(args ...string) (err error) {
	return
}

repository: akaspin/bar

repo_name: akaspin/bar


text:
package strings_test

import (
	"golibs/cmd/strings"
	"reflect"
	"testing"
)

func TestGetSimilarValue(t *testing.T) {
	type args struct {
		source string
		target string
		option strings.Options
	}
	tests := []struct {
		name string
		args args
		want float64
	}{
		{
			name: "Equals",
			args: args{
				source: "carcasa",
				target: "carcasa",
				option: strings.DefaultOptions,
			},
			want: 1,
		},
		{
			name: "Test_1",
			args: args{
				source: "carcasa",
				target: "carroza",
				option: strings.DefaultOptions,
			},
			want: 0.5714285714285714,
		},
		{
			name: "Test_2",
			args: args{
				source: "carcasa",
				target: "carcas",
				option: strings.DefaultOptions,
			},
			want: 0.8571428571428572,
		},
		{
			name: "Test_3",
			args: args{
				source: "carcasa",
				target: "karcaza",
				option: strings.Options{
					InsCost: 1.25,
					DelCost: 1,
					SubCost: 1.5,
				},
			},
			want: 0.5714285714285714,
		},
		{
			name: "Test_3",
			args: args{
				source: "carcasa",
				target: "karcaza",
				option: strings.Options{
					InsCost: 1.25,
					DelCost: 1,
					SubCost: 0.5,
				},
			},
			want: 0.8571428571428572,
		},
		{
			name: "Test_4",
			args: args{
				source: "Reynier Gonzalez",
				target: "reyNier Gonzalez",
				option: strings.Options{
					InsCost: 1.25,
					DelCost: 1,
					SubCost: 1.5,
				},
			},
			want: 1,
		},
		{
			name: "Test_5",
			args: args{
				source: "Reynier Gonzalez",
				target: "reyNier González",
				option: strings.DefaultOptions,
			},
			want: 1,
		},
		{
			name: "Test_6",
			args: args{
				source: "Gonzalez Reynier",
				target: "reyNier González",
				option: strings.Options{
					InsCost: 1.25,
					DelCost: 1,
					SubCost: 1.5,
				},
			},
			want: -0.050000000000000044,
		},
		{
			name: "Test_7",
			args: args{
				source: "Asheville",
				target: "Arizona",
				option: strings.DefaultOptions,
			},
			want: 0.11111111111111116,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := strings.GetLevenshteinSimilarity(tt.args.source, tt.args.target, tt.args.option); got != tt.want {
				t.Errorf("GetLevenshteinSimilarity() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestJaroWinklerDistance(t *testing.T) {
	type args struct {
		source string
		target string
	}
	tests := []struct {
		name string
		args args
		want float64
	}{
		{
			name: "Equals",
			args: args{
				source: "carcasa",
				target: "carcasa",
			},
			want: 1,
		},
		{
			name: "Test_1",
			args: args{
				source: "carcasa",
				target: "carroza",
			},
			want: 0.8,
		},
		{
			name: "Test_2",
			args: args{
				source: "carcasa",
				target: "carcas",
			},
			want: 0.9714285714285714,
		},
		{
			name: "Test_3",
			args: args{
				source: "carcasa",
				target: "karcaza",
			},
			want: 0.8095238095238096,
		},
		{
			name: "Test_4",
			args: args{
				source: "Reynier Gonzalez",
				target: "reyNier Gonzalez",
			},
			want: 1,
		},
		{
			name: "Test_5",
			args: args{
				source: "Reynier Gonzalez",
				target: "reyNier González",
			},
			want: 1,
		},
		{
			name: "Test_6",
			args: args{
				source: "Gonzalez Reynier",
				target: "reyNier González",
			},
			want: 0.5253968253968254,
		},
		{
			name: "Test_7",
			args: args{
				source: "Asheville",
				target: "Arizona",
			},
			want: 0.5026455026455027,
		},
		{
			name: "Test_8",
			args: args{
				source: "González Reynier",
				target: "Reynier González Cruz",
			},
			want: 0.7742690058479532,
		},
		{
			name: "Test_9",
			args: args{
				source: "González Cruz Reynier",
				target: "Reynier González Cruz",
			},
			want: 0.7489035087719298,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := strings.GetJaroWinklerSimilarity(tt.args.source, tt.args.target); got != tt.want {
				t.Errorf("GetJaroWinklerSimilarity() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestCompareNames(t *testing.T) {
	type args struct {
		fullName       string
		secondFullName string
	}
	tests := []struct {
		name string
		args args
		want strings.Match
	}{
		{
			name: "Test_1",
			args: args{
				fullName:       "Reynier Gonzalez Cruz",
				secondFullName: "Reynier González Cruz",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 1,
					JaroWinkler: 1,
					Media:       1,
				},
			},
		},
		{
			name: "Test_2",
			args: args{
				fullName:       "Reynier Gonzalez Cruz",
				secondFullName: "González Cruz Reynier",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 0.26315789473684215,
					JaroWinkler: 0.7489035087719298,
					Media:       0.5060307017543859,
				},
			},
		},
		{
			name: "Test_3",
			args: args{
				fullName:       "Reynier Gonzalez Cruz",
				secondFullName: "González Reynier    ",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 0.26315789473684215,
					JaroWinkler: 0.7742690058479532,
					Media:       0.5187134502923977,
				},
			},
		},
		{
			name: "Test_4",
			args: args{
				fullName:       "Arelys RIVERO CASTRO",
				secondFullName: "Reynier González Cruz",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 0.26315789473684215,
					JaroWinkler: 0.5939571150097466,
					Media:       0.42855750487329436,
				},
			},
		},
		{
			name: "Test_5",
			args: args{
				fullName:       "Arelys RIVERO CASTRO",
				secondFullName: "Arelys RIVERO",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 0.6666666666666667,
					JaroWinkler: 0.9333333333333333,
					Media:       0.8,
				},
			},
		},
		{
			name: "Test_6",
			args: args{
				fullName:       "MARTHA",
				secondFullName: "MARHTA",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 0.6666666666666667,
					JaroWinkler: 0.9611111111111111,
					Media:       0.8138888888888889,
				},
			},
		},
		{
			name: "Test_7",
			args: args{
				fullName:       "MARTHA Mesa",
				secondFullName: "MARHTA Mesa",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 0.8,
					JaroWinkler: 0.9766666666666667,
					Media:       0.8883333333333334,
				},
			},
		},
		{
			name: "Test_8",
			args: args{
				fullName:       "MARTHA Mesa Silva",
				secondFullName: "MARTA Mesa",
			},
			want: strings.Match{
				Percentage: strings.Distribution{
					Levenshtein: 0.6,
					JaroWinkler: 0.92,
					Media:       0.76,
				},
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := strings.GetSimilarity(tt.args.fullName, tt.args.secondFullName); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("GetSimilarity() = %v, want %v", got, tt.want)
			}
		})
	}
}

gha_language: Go


text:
// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/nathanhack/sibyl/ent/predicate"
	"github.com/nathanhack/sibyl/ent/traderecord"
)

// TradeRecordDelete is the builder for deleting a TradeRecord entity.
type TradeRecordDelete struct {
	config
	hooks    []Hook
	mutation *TradeRecordMutation
}

// Where appends a list predicates to the TradeRecordDelete builder.
func (trd *TradeRecordDelete) Where(ps ...predicate.TradeRecord) *TradeRecordDelete {
	trd.mutation.Where(ps...)
	return trd
}

// Exec executes the deletion query and returns how many vertices were deleted.
func (trd *TradeRecordDelete) Exec(ctx context.Context) (int, error) {
	return withHooks[int, TradeRecordMutation](ctx, trd.sqlExec, trd.mutation, trd.hooks)
}

// ExecX is like Exec, but panics if an error occurs.
func (trd *TradeRecordDelete) ExecX(ctx context.Context) int {
	n, err := trd.Exec(ctx)
	if err != nil {
		panic(err)
	}
	return n
}

func (trd *TradeRecordDelete) sqlExec(ctx context.Context) (int, error) {
	_spec := &sqlgraph.DeleteSpec{
		Node: &sqlgraph.NodeSpec{
			Table: traderecord.Table,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeInt,
				Column: traderecord.FieldID,
			},
		},
	}
	if ps := trd.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	affected, err := sqlgraph.DeleteNodes(ctx, trd.driver, _spec)
	if err != nil && sqlgraph.IsConstraintError(err) {
		err = &ConstraintError{msg: err.Error(), wrap: err}
	}
	trd.mutation.done = true
	return affected, err
}

// TradeRecordDeleteOne is the builder for deleting a single TradeRecord entity.
type TradeRecordDeleteOne struct {
	trd *TradeRecordDelete
}

// Exec executes the deletion query.
func (trdo *TradeRecordDeleteOne) Exec(ctx context.Context) error {
	n, err := trdo.trd.Exec(ctx)
	switch {
	case err != nil:
		return err
	case n == 0:
		return &NotFoundError{traderecord.Label}
	default:
		return nil
	}
}

// ExecX is like Exec, but panics if an error occurs.
func (trdo *TradeRecordDeleteOne) ExecX(ctx context.Context) {
	trdo.trd.ExecX(ctx)
}

repository: nathanhack/sibyl

repo_name: nathanhack/sibyl


text:
package core

import "context"

type NoOpTextEncrypt struct{}

func NewNoOpTextEncrypt() *NoOpTextEncrypt {
	return &NoOpTextEncrypt{}
}

func (m NoOpTextEncrypt) DecryptText(_ context.Context, cypherText string) (text string, err error) {
	return cypherText, nil
}

func (NoOpTextEncrypt) EncryptText(_ context.Context, text string) (cypherText string, err error) {
	return text, nil
}

repository: identityOrg/cerberus

repo_name: identityOrg/cerberus


text:
SUMMARY = "Phosphor Systemd targets"
DESCRIPTION = "Provides well known Systemd synchronization points for OpenBMC."
HOMEPAGE = "http://github.com/openbmc"
PR = "r1"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${COREBASE}/meta/files/common-licenses/Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

inherit allarch obmc-phosphor-systemd

SRC_URI += "\
    file://obmc-mapper.target \
"

SYSTEMD_SERVICE:${PN} += " \
    obmc-mapper.target \
"

repository: Intel-BMC/openbmc

repo_name: Intel-BMC/openbmc

gha_license_id: NOASSERTION

gha_language: Python


text:
//
// Creates a binary `gostem` that stems an input file.
//
package main

import (
	"bufio"
	"flag"
	"fmt"
	"github.com/kljensen/snowball"
	"io"
	"log"
	"os"
	"strings"
)

func main() {

	var language *string = flag.String("l", "english", "Language")
	var infile *string = flag.String("i", "", "Input file for stemming")
	flag.Parse()

	f, err := os.Open(*infile)
	if err != nil {
		log.Fatal(err)
	}

	bf := bufio.NewReader(f)

	for {
		line, isPrefix, err := bf.ReadLine()

		if err == io.EOF {
			break
		}

		if err != nil {
			log.Fatal(err)
		}

		if isPrefix {
			log.Fatal("Error: Unexpected long line reading", f.Name())
		}

		word := strings.TrimSpace(string(line))
		stemmed, err := snowball.Stem(word, *language, true)
		if err != nil {
			log.Println(err)
			break
		}
		fmt.Println(stemmed)
	}
}

repository: kljensen/snowball

repo_name: kljensen/snowball


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

// gateway_main is a REST gateway for the emulator grpc server. The emulator grpc server needs
// to be implemented in C++ due to its heavy dependence on ZetaSQL. To make it easy to use, we
// run the grpc server C++ binary as a subprocess of the REST gateway.
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"path"
	"path/filepath"

	"cloud_spanner_emulator/gateway"
)

var (
	// Networking related flags.
	hostname = flag.String("hostname", "localhost", "Hostname for the emulator servers.")
	grpcPort = flag.Int("grpc_port", 9010, "Port on which to run the emulator grpc server.")
	httpPort = flag.Int("http_port", 9020, "Port on which to run the emulator http server.")

	// Subprocess related flags.
	grpcBinary = flag.String("grpc_binary", "emulator_main", "Location of the grpc binary.")

	// Logging related flags.
	copyEmulatorStdout = flag.Bool("copy_emulator_stdout", false,
		"If true, the gateway will copy the emulator's stdout to its stdout.")
	copyEmulatorStderr = flag.Bool("copy_emulator_stderr", true,
		"If true, the gateway will copy the emulator's stderr to its stderr.")
	logRequests = flag.Bool("log_requests", false,
		"If true, gRPC requests and responses will be logged to stdout.")

	// Emulator specific flags.
	enableFaultInjection = flag.Bool("enable_fault_injection", false,
		"If true, the emulator will inject faults at runtime (e.g. randomly abort commit "+
			"requests to allow testing application abort-retry behavior).")
	disableQueryNullFilteredIndexCheck = flag.Bool("disable_query_null_filtered_index_check", false,
		"If true, then queries that use NULL_FILTERED indexes will be answered.")
)

// resolveGRPCBinary figures out the full path to the grpc binary from the --grpc_binary flag.
func resolveGRPCBinary() string {
	retval := *grpcBinary

	// Early-exit if we were given the full path (else we assume we were only given the filename).
	if path.IsAbs(retval) {
		return retval
	}

	// Get the location of this executable's directory.
	gwPath, err := os.Executable()
	if err != nil {
		log.Fatal(err)
	}
	gwDir := filepath.Dir(gwPath)

	// Check if the grpc binary is in the same directory as the gateway binary (this happens in the
	// release package) else check if the grpc binary is in the parent directory of the gateway
	// binary (this happens when using bazel run).
	retval = filepath.Join(gwDir, *grpcBinary)
	_, err = os.Stat(retval)
	if os.IsNotExist(err) {
		retval = filepath.Join(filepath.Dir(gwDir), *grpcBinary)
	}
	_, err = os.Stat(retval)
	if os.IsNotExist(err) {
		log.Fatal(err)
	}

	return retval
}

func main() {
	flag.Parse()
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	// Start the gateway http server. This will run the emulator grpc server as a subprocess and
	// proxy http/json requests into grpc requests.
	gwopts := gateway.Options{
		GatewayAddress:                     fmt.Sprintf("%s:%d", *hostname, *httpPort),
		FrontendBinary:                     resolveGRPCBinary(),
		FrontendAddress:                    fmt.Sprintf("%s:%d", *hostname, *grpcPort),
		CopyEmulatorStdout:                 *copyEmulatorStdout,
		CopyEmulatorStderr:                 *copyEmulatorStderr,
		LogRequests:                        *logRequests,
		EnableFaultInjection:               *enableFaultInjection,
		DisableQueryNullFilteredIndexCheck: *disableQueryNullFilteredIndexCheck,
	}
	gw := gateway.New(gwopts)
	gw.Run()
}


text:
DESCRIPTION = "libebml is a C++ libary to parse EBML files"
HOMEPAGE = "http://www.matroska.org/"
SECTION = "libs"
PRIORITY = "optional"

LICENSE="LGPL-2.1"

SRC_URI = "http://www.bunkus.org/videotools/mkvtoolnix/sources/${PN}-${PV}.tar.bz2"

do_compile() {
	oe_runmake -C make/linux
}

do_install() {
	oe_runmake -C make/linux install includedir="${STAGING_INCDIR}/ebml" libdir="${STAGING_LIBDIR}"
}


text:
@article{RN2077,
 author = {Collier, Jackie L and Rest, Joshua S},
 issn = {1059-1524},
 journal = {Molecular biology of the cell},
 number = {11},
 pages = {1245-1248},
 title = {Swimming, gliding, and rolling toward the mainstream: cell biology of marine protists},
 type = {Journal Article},
 volume = {30},
 year = {2019}
}


text:
DESCRIPTION = "ADSP Driver for Linux"
LICENSE = "GPLv2 & MIT"

LIC_FILES_CHKSUM = " \
    file://COPYING;md5=55979d94ccbb973fdea772250e0c54d6 \
    file://MIT-COPYING;md5=f932f6ad0feea4f97b6e8316e172070e \
"

inherit module features_check

REQUIRED_DISTRO_FEATURES = "adsp"

FILESEXTRAPATHS_prepend := "${THISDIR}/xtensa-hifi:"

SRC_URI = "file://RTM8RC0000ZNA2DS00JFL3E.tar.gz"

S = "${WORKDIR}/RTM8RC0000ZNA2DS00JFL3E"

# Define the extra config for using module.bbclass to build ADSP driver
EXTRA_OEMAKE_append = " KDIR=${STAGING_KERNEL_DIR}"

# Build ADSP kernel module without suffix
KERNEL_MODULE_PACKAGE_SUFFIX = ""

# Enable build target for E3 board
do_configure_prepend_r8a77990(){
    sed -i 's|-DTARGET_BOARD_E3=0|-DTARGET_BOARD_E3=1|g' ${S}/Kbuild
}

do_install_append(){
    # Create install directories
    install -d ${D}/${includedir}
    install -d ${D}/${includedir}/sys/xt-shmem

    # Install shared header files
    install -m 644 ${S}/include/*.h ${D}/${includedir}/
    install -m 644 ${S}/include/sys/xt-shmem/*.h ${D}/${includedir}/sys/xt-shmem/
}

# The ADSP driver need adsp firmware for running
RDEPENDS_${PN}_append = " adsp-fw-module"

repository: renesas-rcar/meta-renesas

repo_name: renesas-rcar/meta-renesas

branch_name: refs/heads/dunfell

gha_language: BitBake


text:
SUMMARY = "Tools for TPM2."
DESCRIPTION = "tpm2-tools"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://doc/LICENSE;md5=a846608d090aa64494c45fc147cc12e3"
SECTION = "tpm"

DEPENDS = "tpm2-abrmd tpm2-tss openssl curl autoconf-archive"

SRC_URI = "https://github.com/tpm2-software/${BPN}/releases/download/${PV}/${BPN}-${PV}.tar.gz"

SRC_URI[sha256sum] = "c0b402f6a7b3456e8eb2445211e2d41c46c7e769e05fe4d8909ff64119f7a630"

inherit autotools pkgconfig bash-completion

do_configure:prepend() {
    # do not extract the version number from git
    sed -i -e 's/m4_esyscmd_s(\[git describe --tags --always --dirty\])/${PV}/' ${S}/configure.ac
}

# need tss-esys
RDEPENDS:${PN} = "libtss2 tpm2-abrmd"

repository: balena-os/meta-balena

repo_name: balena-os/meta-balena


text:
DESCRIPTION = "Red, the Rascal editor, is the web-based editor that is built into every Rascal, a small computer for art and science"
HOMEPAGE = "http://rascalmicro.com"
LICENSE = "GPLv3"
SRCNAME = "red"
PR = "r0"

S = "${WORKDIR}/git"

SRCREV = "${AUTOREV}"
SRC_URI = "git://github.com/rascalmicro/red.git;protocol=git;branch=master"

FILES_${PN} = "/var"

do_configure () {
}

do_compile () {
}

do_install () {
	install -d ${D}/var/www
	install -d ${D}/var/www/editor
	cp -r ${S}/* ${D}/var/www/editor/
}