text:
SUMMARY = "Paho MQTT - CPP libraries for the MQTT and MQTT-SN protocols"
DESCRIPTION = "Client implementation of open and standard messaging protocols for Machine-to-Machine (M2M) and Internet of Things (IoT)."
HOMEPAGE = "http://www.eclipse.org/paho/"
SECTION = "console/network"
LICENSE = "EPL-1.0 | EDL-1.0"

PR = "r1"

LIC_FILES_CHKSUM = " \
        file://edl-v10;md5=3adfcc70f5aeb7a44f3f9b495aa1fbf3 \
        file://epl-v10;md5=659c8e92a40b6df1d9e3dccf5ae45a08 \
        file://notice.html;md5=a00d6f9ab542be7babc2d8b80d5d2a4c \
        file://about.html;md5=dcde438d73cf42393da9d40fabc0c9bc \
"

SRC_URI = "git://github.com/eclipse/paho.mqtt.cpp;protocol=http"

SRCREV = "16573488fa699ac94d920024736974a2206b794b"

DEPENDS = "openssl paho-mqtt-c"
RDEPENDS_${PN} = "paho-mqtt-c"

inherit cmake

S = "${WORKDIR}/git"

TARGET_CC_ARCH += "${LDFLAGS}"

repository: algebratech/meta-algebra

repo_name: algebratech/meta-algebra


text:
@article{Debnath2020SocialNLP,
author = {Debnath, Alok and Nikhil, Wouter and Shrivastava, Manish and Varma, Vasudeva and Augenstein, Isabelle},
journal={In Proceedings of the 8th International Workshop on
Natural Language Processing for Social Media (SocialNLP) at TheWebConf 2020},
title = {{Semantic Textual Similarity of Sentences with Emojis}},
year = 2020
}

license: MIT

repository: copenlu/academic-kickstart

license_type: permissive

repo_name: copenlu/academic-kickstart

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: TeX

extension: bib


text:
if(CMAKE_COMPILER_IS_GNUCXX)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -Wall -Wpedantic -Wextra")
    if(UNIX)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic")
    endif()
    set(CMAKE_CXX_FLAGS_DEBUG "-g")
    set(CMAKE_CXX_FLAGS_RELEASE "-O2")
    set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
    set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os")
endif()

if(CMAKE_COMPILER_IS_GNUCC)
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11 -Wall -Wpedantic -Wextra")
    if(UNIX)
        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -rdynamic")
    endif()
    set(CMAKE_C_FLAGS_DEBUG "-g")
    set(CMAKE_C_FLAGS_RELEASE "-O2")
    set(CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
    set(CMAKE_C_FLAGS_MINSIZEREL "-Os")
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUCC)
    set(linker_flags "-Wl,--no-as-needed") # for bunsan::factory plugins
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${linker_flags}")
    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${linker_flags}")
    set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${linker_flags}")
endif()

# Note: defined as empty string by default.
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: Debug, Release, RelWithDebInfo and MinSizeRel." FORCE)
endif()

set(BUILD_SHARED_LIBS ON CACHE BOOL "Build shared libraries")

add_definitions(-DBOOST_ALL_NO_LIB)
if(BUILD_SHARED_LIBS)
    add_definitions(-DBOOST_ALL_DYN_LINK)
    set(Boost_USE_STATIC_LIBS OFF)
else()
    set(Boost_USE_STATIC_LIBS ON)
endif()
set(Boost_USE_MULTITHREADED ON)

set(ENABLE_TESTS ON CACHE BOOL "Do you want to enable testing?")

repository: bunsanorg/cmake

repo_name: bunsanorg/cmake

extension: cmake


text:
DESCRIPTION = "Parallelism library for C++ - runtime files \
    TBB is a library that helps you leverage multi-core processor \
    performance without having to be a threading expert. It represents a \
    higher-level, task-based parallelism that abstracts platform details \
    and threading mechanism for performance and scalability."
HOMEPAGE = "https://software.intel.com/en-us/tbb"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=86d3f3a95c324c9479bd8986968f4327"
BRANCH = "tbb_2020"
SRCREV = "eca91f16d7490a8abfdee652dadf457ec820cc37"
SRC_URI = "git://github.com/oneapi-src/oneTBB.git;protocol=https;branch=${BRANCH} \
           file://cross-compile.patch \
           file://0001-mallinfo-is-glibc-specific-API-mark-it-so.patch \
           file://GLIBC-PREREQ-is-not-defined-on-musl.patch \
           file://tbb.pc \
           file://improve-reproducibility.patch \
"

S = "${WORKDIR}/git"
PE = "1"

COMPILER ?= "gcc"
COMPILER_toolchain-clang = "clang"

do_compile() {
    oe_runmake compiler=${COMPILER} arch=${HOST_ARCH}
}

do_install() {
    install -d ${D}${includedir} ${D}${libdir}
    rm ${S}/include/tbb/index.html -f
    cp -R --no-dereference --preserve=mode,links -v ${S}/include/tbb ${D}${includedir}
    for f in ${B}/build/linux_*_release/lib*.so*
    do
        install -Dm 0755 $f ${D}${libdir}/
    done
    install -Dm 0644 ${WORKDIR}/tbb.pc ${D}${libdir}/pkgconfig/tbb.pc
}

# fails with thumb enabled:
# | arm-oe-linux-gnueabi-g++  -march=armv7-a -mthumb -mthumb-interwork -mfloat-abi=softfp -mfpu=neon -mtune=cortex-a9 -mcpu=cortex-a9 -D__ARM__ -D__LINUX_ARM_ARCH__=7 -funwind-tables -mvectorize-with-neon-quad -rdynamic --sysroot=/OE/sysroots/m14tv -c -MMD -DTBB_USE_DEBUG  -g -O0 -DUSE_PTHREAD -fPIC -D__TBB_BUILD=1 -Wall -Wno-parentheses -Wno-non-virtual-dtor -O2 -pipe -g -feliminate-unused-debug-types -fpermissive -fvisibility-inlines-hidden   -I../../src -I../../src/rml/include -I../../include ../../src/tbb/concurrent_queue.cpp
# | {standard input}: Assembler messages:
# | {standard input}:250: Error: thumb conditional instruction should be in IT block -- `strexeq r2,r3,[r4]'
# ...
# | make[1]: *** [concurrent_queue.o] Error 1
ARM_INSTRUCTION_SET = "arm"

repository: iipeace/meta-openembedded

repo_name: iipeace/meta-openembedded

extension: bb


text:
@article{Richardson2008,
author = {Richardson, James W and Outlaw, Joe L},
journal = {WIT Transactions on Information and Communication},
number = {1},
pages = {213--224},
title = {{Ranking risky alternatives: innovations in subjective utility analysis}},
volume = {39},
year = {2008}
}

@article{Hardaker2004,
author = {Hardaker, J. Brian and Richardson, James W. and Lien, Gudbrand and Schumann, Keith D.},
doi = {10.1111/j.1467-8489.2004.00239.x},
issn = {1364-985X},
journal = {The Australian Journal of Agricultural and Resource Economics},
keywords = {SERF,certainty equivalente,premium risk},
mendeley-groups = {Risk Analysis},
mendeley-tags = {SERF,certainty equivalente,premium risk},
month = {jun},
number = {2},
pages = {253--270},
publisher = {John Wiley {\&} Sons, Ltd (10.1111)},
title = {{Stochastic efficiency analysis with risk aversion bounds: a simplified approach}},
url = {http://doi.wiley.com/10.1111/j.1467-8489.2004.00239.x},
volume = {48},
year = {2004}
}

@conference{sotocaro2019,
place={Atlante, GA},
title={Evaluating Pest Management Strategies: A Robust Method and Its Application to Strawberry Disease Management},
publisher={Paper presented at AAEA annual meeting 2019, Atlanta, GA, 21-23 July.},
author={Soto-Caro, Ariel and Wu, Feng and Guan, Zhengfei},
year={2019}
}

repository: ArielSotoCaro/ceRtainty

repo_name: ArielSotoCaro/ceRtainty


text:
package me

// GENERATED SDK for me API

// Languages a nichandle can choose
type LanguageEnum string

var (
	LanguageEnumPT_PT LanguageEnum = "pt_PT"
	LanguageEnumPL_PL LanguageEnum = "pl_PL"
	LanguageEnumNL_NL LanguageEnum = "nl_NL"
	LanguageEnumLT_LT LanguageEnum = "lt_LT"
	LanguageEnumIT_IT LanguageEnum = "it_IT"
	LanguageEnumFR_TN LanguageEnum = "fr_TN"
	LanguageEnumFR_SN LanguageEnum = "fr_SN"
	LanguageEnumFR_MA LanguageEnum = "fr_MA"
	LanguageEnumFR_FR LanguageEnum = "fr_FR"
	LanguageEnumFR_CA LanguageEnum = "fr_CA"
	LanguageEnumFI_FI LanguageEnum = "fi_FI"
	LanguageEnumES_ES LanguageEnum = "es_ES"
	LanguageEnumEN_US LanguageEnum = "en_US"
	LanguageEnumEN_IE LanguageEnum = "en_IE"
	LanguageEnumEN_GB LanguageEnum = "en_GB"
	LanguageEnumEN_CA LanguageEnum = "en_CA"
	LanguageEnumEN_AU LanguageEnum = "en_AU"
	LanguageEnumDE_DE LanguageEnum = "de_DE"
	LanguageEnumCS_CZ LanguageEnum = "cs_CZ"
)

extension: go


text:
file(REMOVE_RECURSE
  "CMakeFiles/string_libcxx_nonmembers_oplt_pointer_string.dir/libcxx/basic_string/string.nonmembers/string_oplt/pointer_string.pass.cpp.o"
  "string_libcxx_nonmembers_oplt_pointer_string.pdb"
  "string_libcxx_nonmembers_oplt_pointer_string"
)

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

repository: urcs-sync/Montage

repo_name: urcs-sync/Montage

gha_license_id: NOASSERTION


text:
package main

import "testing"

func TestPart1(t *testing.T) {
	cases := []struct {
		in   []string
		want int
	}{
		{[]string{"abcdef", "bababc", "abbcde", "abcccd", "aabcdd", "abcdee", "ababab"}, 12},
	}

	for _, c := range cases {
		got := Part1(c.in)
		if got != c.want {
			t.Errorf("Part1(%v) == %v, want %v", c.in, got, c.want)
		}
	}
}

func TestPart2(t *testing.T) {
	cases := []struct {
		in   []string
		want string
	}{
		{[]string{
			"abcde",
			"fghij",
			"klmno",
			"pqrst",
			"fguij",
			"axcye",
			"wvxyz",
		}, "fgij"},
	}

	for _, c := range cases {
		got := Part2(c.in)
		if got != c.want {
			t.Errorf("Part1(%v) == %v, want %v", c.in, got, c.want)
		}
	}
}

repository: bolshchikov/adventofcode-solutions

repo_name: bolshchikov/adventofcode-solutions


text:
if(CPACK_GENERATOR MATCHES "NSIS")
  set (CPACK_NSIS_MENU_LINKS
    "bin/tomviz.exe" "tomviz")

  set(CPACK_NSIS_MODIFY_PATH OFF)

  set (CPACK_NSIS_MUI_ICON "@CMAKE_CURRENT_LIST_DIR@/InstallerIcon.ico")

  if (64bit_build)
    set(CPACK_NSIS_INSTALL_ROOT "$PROGRAMFILES64")
  endif()
elseif(CPACK_GENERATOR MATCHES "WIX")
  set(CPACK_WIX_UPGRADE_GUID "9A0AD927-232D-48BF-BA01-65FA9FA56662")

  set(CPACK_WIX_PROPERTY_ARPURLINFOABOUT "https://tomviz.org")

  # Do we have an email address setup?
  set(CPACK_WIX_PROPERTY_ARPCONTACT "tomviz@tomviz.org")

  set(CPACK_WIX_PROPERTY_ARPCOMMENTS
    "tomviz is a cross platform, open source application for the processing, visualization, and analysis of 3D tomography data."
    )

  set(CPACK_WIX_PRODUCT_ICON
    "@CMAKE_CURRENT_LIST_DIR@/InstallerIcon.ico"
    )

  set(CPACK_WIX_UI_BANNER
    "@CMAKE_CURRENT_LIST_DIR@/ui_banner.jpg"
    )

  set(CPACK_WIX_UI_DIALOG
    "@CMAKE_CURRENT_LIST_DIR@/ui_dialog.jpg"
    )

  set(CPACK_WIX_TEMPLATE "@CMAKE_CURRENT_LIST_DIR@/WIX.template.in"
    )

  set(CPACK_RESOURCE_FILE_LICENSE
    "@CMAKE_CURRENT_BINARY_DIR@/LICENSE.txt")

  # Reset CPACK_PACKAGE_VERSION to deal with WiX restriction.
  set(CPACK_PACKAGE_VERSION
    "@tomviz_version_major@.@tomviz_version_minor@")
  # WIX installers require at most a 4 component version number, where
  # each component is an integer between 0 and 65534 inclusive
  set(patch "@tomviz_version_patch@")
  if(patch MATCHES "^[0-9]+$" AND patch LESS 65535)
    set(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}.${patch}")
  endif()
endif()

repository: OpenChemistry/tomviz-superbuild

repo_name: OpenChemistry/tomviz-superbuild

gha_language: Shell

extension: in


text:
package utils

import (
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestVerifyIP(t *testing.T) {
	IPs := "127.0.0.1:9876"
	err := VerifyIP(IPs)
	assert.Nil(t, err)

	IPs = "12.24.123.243:10911"
	err = VerifyIP(IPs)
	assert.Nil(t, err)

	IPs = "xa2.0.0.1:9876"
	err = VerifyIP(IPs)
	assert.Equal(t, "IP addr error", err.Error())

	IPs = "333.0.0.1:9876"
	err = VerifyIP(IPs)
	assert.Equal(t, "IP addr error", err.Error())

	IPs = "127.0.0.1:9876;12.24.123.243:10911"
	err = VerifyIP(IPs)
	assert.Equal(t, "multiple IP addr does not support", err.Error())
}


text:
package main

import (
	"archive/tar"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/anuvu/octoci/pool"
	"github.com/klauspost/pgzip"
	"github.com/openSUSE/umoci"
	"github.com/openSUSE/umoci/oci/casext"
	"github.com/opencontainers/go-digest"
	ispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
	"github.com/urfave/cli"
)

var (
	version = ""
)

func main() {
	app := cli.NewApp()
	app.Name = "octoci"
	app.Usage = "octoci octopus merges rootfses into an OCI image"
	app.Version = version
	app.Commands = []cli.Command{buildCmd}

	if err := app.Run(os.Args); err != nil {
		fmt.Fprintf(os.Stderr, "error: %+v", err)
		os.Exit(1)
	}
}

var buildCmd = cli.Command{
	Name:   "build",
	Usage:  "builds an octoci image",
	Action: doBuild,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "oci-dir",
			Usage: "the output OCI dir to use",
			Value: "oci",
		},
		cli.StringFlag{
			Name:  "tag",
			Usage: "the output tag to write",
			Value: "octoci",
		},
		cli.IntFlag{
			Name:  "dirs-per-blob",
			Usage: "the number of directories to combine into one layer",
			Value: 1,
		},
		cli.BoolFlag{
			Name:   "serialize",
			Usage:  "serialize the builds (i.e. don't do them in parallel)",
			Hidden: true,
		},
		cli.Uint64Flag{
			Name:  "max-layer-size",
			Usage: "don't build layers bigger than size N (bytes)",
		},
	},
	ArgsUsage: `[base-image] [rootfses]

[base-image] is a skopeo compatible URL for the base image.

[rootfses] is a \n separated list of directories to octomerge.`,
}

var otherFailure = fmt.Errorf("got other failure")

func doBuild(ctx *cli.Context) error {
	if len(ctx.Args()) != 2 {
		return fmt.Errorf("wrong number of arguments")
	}

	baseImage := ctx.Args()[0]
	rootfsesFile := ctx.Args()[1]

	rootfsesFileRaw, err := ioutil.ReadFile(rootfsesFile)
	if err != nil {
		return err
	}

	rootfses := strings.Split(strings.TrimSpace(string(rootfsesFileRaw)), "\n")

	output, err := exec.Command(
		"skopeo",
		"--insecure-policy",
		"copy",
		"--src-tls-verify=false",
		baseImage,
		fmt.Sprintf("oci:%s:%s", ctx.String("oci-dir"), ctx.String("tag")),
	).CombinedOutput()
	if err != nil {
		return fmt.Errorf("image import failed: %s: %s", err, string(output))
	}

	oci, err := umoci.OpenLayout(ctx.String("oci-dir"))
	if err != nil {
		return err
	}
	// Let's GC: if there were any errors and we put some blobs, we don't
	// want to leave those around. Or, if this was a repeat build and
	// generated new blobs, we don't want to leave the old ones around
	// either.
	defer oci.GC(context.Background())
	defer oci.Close()

	tasks := []rootfsProcessor{}
	procs := runtime.NumCPU()
	if ctx.Bool("serialize") {
		procs = 1
	}
	tp := pool.New(procs)

	for i, rootfs := range rootfses {
		if i%ctx.Int("dirs-per-blob") == 0 {
			tasks = append(tasks, rootfsProcessor{
				oci:          oci,
				rootfses:     []string{},
				maxLayerSize: ctx.Uint64("max-layer-size"),
			})
		}
		rootfs, err = filepath.Abs(rootfs)
		if err != nil {
			return err
		}
		tasks[len(tasks)-1].rootfses = append(tasks[len(tasks)-1].rootfses, rootfs)
	}

	for i, _ := range tasks {
		tp.Add((&tasks[i]).addBlob)
	}

	fmt.Println("done adding jobs")
	tp.DoneAddingJobs()

	err = tp.Run()
	if err != nil {
		return err
	}

	descriptorPaths, err := oci.ResolveReference(context.Background(), ctx.String("tag"))
	if err != nil {
		return err
	}

	if len(descriptorPaths) != 1 {
		return errors.Errorf("bad tag: %s", ctx.String("tag"))
	}

	manifestBlob, err := oci.FromDescriptor(context.Background(), descriptorPaths[0].Descriptor())
	if err != nil {
		return err
	}

	manifest, ok := manifestBlob.Data.(ispec.Manifest)
	if !ok {
		return errors.Errorf("bad manifest data type %T", manifestBlob.Data)
	}

	configBlob, err := oci.FromDescriptor(context.Background(), manifest.Config)
	if err != nil {
		return err
	}

	config, ok := configBlob.Data.(ispec.Image)
	if !ok {
		return errors.Errorf("bad config data type %T", manifestBlob.Data)
	}

	for _, task := range tasks {
		config.RootFS.DiffIDs = append(config.RootFS.DiffIDs, task.diffID...)
		manifest.Layers = append(manifest.Layers, task.layerDesc...)
	}

	digest, size, err := oci.PutBlobJSON(context.Background(), config)
	if err != nil {
		return err
	}

	manifest.Config = ispec.Descriptor{
		MediaType: ispec.MediaTypeImageConfig,
		Digest:    digest,
		Size:      size,
	}

	digest, size, err = oci.PutBlobJSON(context.Background(), manifest)
	if err != nil {
		return err
	}

	err = oci.UpdateReference(context.Background(), ctx.String("tag"), ispec.Descriptor{
		MediaType: ispec.MediaTypeImageManifest,
		Digest:    digest,
		Size:      size,
	})
	if err != nil {
		return err
	}

	return nil
}

type writeCounter struct {
	written uint64
}

func (wc *writeCounter) Write(p []byte) (n int, err error) {
	n = len(p)
	wc.written += uint64(n)
	return n, nil
}

type rootfsProcessor struct {
	oci          casext.Engine
	maxLayerSize uint64
	rootfses     []string
	diffID       []digest.Digest
	layerDesc    []ispec.Descriptor
}

func (rp *rootfsProcessor) addBlob(ctx context.Context) error {
	ch := make(chan struct {
		Reader io.ReadCloser
		DiffID digest.Digester
	}, 1)

	go func() {
		reader, writer := io.Pipe()
		defer writer.Close()
		compressedCounter := &writeCounter{}
		bothCompressed := io.MultiWriter(compressedCounter, writer)

		gzw := pgzip.NewWriter(bothCompressed)
		gzw.SetConcurrency(250000, 2*runtime.NumCPU())
		defer gzw.Close()

		diffID := digest.SHA256.Digester()
		ch <- struct {
			Reader io.ReadCloser
			DiffID digest.Digester
		}{
			reader,
			diffID,
		}
		defer func() {
			close(ch)
		}()

		uncompressedCounter := &writeCounter{}

		tw := tar.NewWriter(io.MultiWriter(uncompressedCounter, gzw, diffID.Hash()))
		defer tw.Close()

		for _, rootfs := range rp.rootfses {
			handler := func(path string, info os.FileInfo, err error) error {
				select {
				case <-ctx.Done():
					return pool.ThreadPoolCancelled
				default:
				}

				if err != nil {
					return err
				}

				/* don't import an empty path */
				if path == rootfs {
					return nil
				}

				var link string
				if info.Mode()&os.ModeSymlink != 0 {
					link, err = os.Readlink(path)
					if err != nil {
						return err
					}
				}

				hdr, err := tar.FileInfoHeader(info, link)
				if err != nil {
					return err
				}

				if rp.maxLayerSize > 0 && uncompressedCounter.written > 0 {
					// Let's use a bad heuristic: assume
					// our compression ratio will be
					// relatively constant, let's not add
					// this file to the archive if it'll
					// get us within 5% of the max layer
					// size. We'll waste some space, but
					// c'est la vie. However, if we're
					// going to try this heuristic, we need
					// to make sure the data is all written
					// first, so let's do a flush.
					if err := gzw.Flush(); err != nil {
						return err
					}
					ratio := float64(compressedCounter.written) / float64(uncompressedCounter.written)
					if float64(compressedCounter.written)+ratio*(1000+float64(info.Size())) > float64(rp.maxLayerSize)-float64(rp.maxLayerSize)*0.05 {

						tw.Close()
						gzw.Close()
						writer.Close()
						reader, writer = io.Pipe()
						uncompressedCounter.written = 0
						compressedCounter.written = 0

						bothCompressed = io.MultiWriter(compressedCounter, writer)

						gzw = pgzip.NewWriter(bothCompressed)
						gzw.SetConcurrency(250000, 2*runtime.NumCPU())

						diffID = digest.SHA256.Digester()
						tw = tar.NewWriter(io.MultiWriter(uncompressedCounter, gzw, diffID.Hash()))
						ch <- struct {
							Reader io.ReadCloser
							DiffID digest.Digester
						}{
							reader,
							diffID,
						}
					}
				}

				hdr.Name = path[len(rootfs):]
				err = tw.WriteHeader(hdr)
				if err != nil {
					return err
				}

				if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA {
					f, err := os.Open(path)
					if err != nil {
						return err
					}
					defer f.Close()

					n, err := io.Copy(tw, f)
					if err != nil {
						return err
					}

					if n != hdr.Size {
						return fmt.Errorf("Huh? bad size for %s", path)
					}
				}

				return nil
			}

			fmt.Println("importing rootfs", rootfs)
			err := filepath.Walk(rootfs, handler)
			if err != nil {
				writer.CloseWithError(err)
			}
		}

		tw.Close()
		gzw.Close()
		writer.Close()
	}()

	for {
		layer, ok := <-ch
		if !ok {
			break
		}

		reader := layer.Reader
		diffID := layer.DiffID

		digest, size, err := rp.oci.PutBlob(context.Background(), reader)
		reader.Close()
		if err != nil {
			return err
		}

		rp.layerDesc = append(rp.layerDesc, ispec.Descriptor{
			MediaType: ispec.MediaTypeImageLayerGzip,
			Size:      size,
			Digest:    digest,
		})
		rp.diffID = append(rp.diffID, diffID.Digest())
	}

	return nil
}

repository: anuvu/octoci

repo_name: anuvu/octoci

gha_language: Go


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	sdm630 "github.com/gonium/gosdm630"
	"gopkg.in/urfave/cli.v1"
)

// Copied from
// https://github.com/jcuga/golongpoll/blob/master/events.go:
type lpEvent struct {
	// Timestamp is milliseconds since epoch to match javascrits Date.getTime()
	Timestamp int64  `json:"timestamp"`
	Category  string `json:"category"`
	// NOTE: Data can be anything that is able to passed to json.Marshal()
	Data sdm630.QuerySnip `json:"data"`
}

// eventResponse is the json response that carries longpoll events.
type eventResponse struct {
	Events *[]lpEvent `json:"events"`
}

func main() {
	var sdmURL string
	var sdmTimeout int
	var verbose bool
	var mqttTopic string
	var mqttBroker string
	var mqttPassword string
	var mqttUser string
	var mqttClientID string
	var mqttQos int
	var mqttCleanses bool
	var mqttRate int
	var mqttRateMap map[string]int64
	mqttRateMap = make(map[string]int64)

	app := cli.NewApp()
	app.Name = "sdm630_mqtt"
	app.Usage = "SDM630 mqtt"
	app.Version = sdm630.RELEASEVERSION
	app.HideVersion = true
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "url, u",
			Value: "localhost:8080",
			Usage: "the URL of the server we should connect to",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &sdmURL,
		},
		cli.IntFlag{
			Name:  "timeout",
			Value: 45,
			Usage: "timeout value in seconds",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &sdmTimeout,
		},
		cli.BoolFlag{
			Name:  "verbose, v",
			Usage: "print verbose messages",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &verbose,
		},
		cli.IntFlag{
			Name:  "rate, r",
			Value: 0,
			Usage: "MQTT: The maximum update rate Default=0=unlimited (after a push we will ignore more data from same device and channel for this time)",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttRate,
		},
		cli.StringFlag{
			Name:  "topic, t",
			Value: "gosdm630/",
			Usage: "MQTT: The topic name to/from which to publish/subscribe",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttTopic,
		},
		cli.StringFlag{
			Name:  "broker, b",
			Value: "",
			Usage: "MQTT: The broker URI. ex: tcp://10.10.1.1:1883",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttBroker,
		},
		cli.StringFlag{
			Name:  "password",
			Value: "",
			Usage: "MQTT: The password (optional)",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttPassword,
		},
		cli.StringFlag{
			Name:  "user",
			Value: "",
			Usage: "MQTT: The User (optional)",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttUser,
		},
		cli.StringFlag{
			Name:  "id, i",
			Value: "gosdm630",
			Usage: "MQTT: The ClientID (optional)",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttClientID,
		},
		cli.BoolFlag{
			Name:  "clean,´c",
			Usage: "MQTT: Set Clean Session (default false)",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttCleanses,
		},
		cli.IntFlag{
			Name:  "qos, q",
			Value: 0,
			Usage: "MQTT: The Quality of Service 0,1,2 (default 0)",
			//			FilePath:    "~/.sdm630_mqtt.conf",
			Destination: &mqttQos,
		},
	}
	app.Action = func(c *cli.Context) {
		endpointURL := fmt.Sprintf("http://%s/firehose?timeout=%d&category=meterupdate", sdmURL, sdmTimeout)
		if verbose {
			log.Printf("Client startup - will connect to %s", endpointURL)
		}
		client := &http.Client{
			Timeout: time.Duration(sdmTimeout) * time.Second,
			Transport: &http.Transport{
				// 0 means: no limit.
				MaxIdleConns:        0,
				MaxIdleConnsPerHost: 0,
				IdleConnTimeout:     0,
				Dial: (&net.Dialer{
					Timeout:   30 * time.Second,
					KeepAlive: time.Minute,
				}).Dial,
				TLSHandshakeTimeout: 10 * time.Second,
				DisableKeepAlives:   false,
			},
		}

		mqttOpts := MQTT.NewClientOptions()
		mqttOpts.AddBroker(mqttBroker)
		mqttOpts.SetClientID(mqttClientID)
		mqttOpts.SetUsername(mqttUser)
		mqttOpts.SetPassword(mqttPassword)
		mqttOpts.SetCleanSession(mqttCleanses)
		topic := fmt.Sprintf("%s/connected", mqttTopic)
		message := fmt.Sprintf("0")
		mqttOpts.SetWill(topic, message, byte(mqttQos), true)

		if verbose {
			log.Println("Connecting to mqtt:")
			log.Printf("\tbroker:    %s\n", mqttBroker)
			log.Printf("\tclientid:  %s\n", mqttClientID)
			log.Printf("\tuser:      %s\n", mqttUser)
			if mqttPassword != "" {
				log.Printf("\tpassword:  ****\n")
			}
			log.Printf("\ttopic:     %s\n", mqttTopic)
			log.Printf("\tqos:       %d\n", mqttQos)
			log.Printf("\tcleansess: %v\n", mqttCleanses)
		}

		mqttClient := MQTT.NewClient(mqttOpts)
		if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
			log.Fatal("Error connecting to mqtt: ", token.Error())
			panic(token.Error())
		}
		if verbose {
			log.Println("Connected to mqtt")
		}
		topic = fmt.Sprintf("%s/connected", mqttTopic)
		message = fmt.Sprintf("1")
		token := mqttClient.Publish(topic, byte(mqttQos), true, message)
		if verbose {
			log.Printf("MQTT push %s, Message: %s", topic, message)
		}
		if token.Wait() && token.Error() != nil {
			log.Fatal("Error connecting to mqtt: ", token.Error())
			panic(token.Error())
		}

		resp, err := client.Get(endpointURL)
		if err != nil {
			log.Fatal("Failed to read from endpoint: ", err.Error())
		} else {
			if verbose {
				log.Println("Connected to firehose")
			}
			topic = fmt.Sprintf("%s/connected", mqttTopic)
			message = fmt.Sprintf("2")
			token = mqttClient.Publish(topic, byte(mqttQos), true, message)
			if verbose {
				log.Printf("MQTT push %s, Message: %s", topic, message)
			}
			if token.Wait() && token.Error() != nil {
				log.Fatal("Error connecting to mqtt: ", token.Error())
				panic(token.Error())
			}
		}

		for {
			rawevents, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				log.Fatal("Failed to process message: ", err.Error())
			} else {
				// handle the events.
				var events eventResponse
				err := json.Unmarshal(rawevents, &events)
				if err != nil {
					log.Fatal("Failed to decode JSON events: ", err.Error())
				}
				for _, event := range *events.Events {
					snip := event.Data
					if verbose {
						log.Printf("Device %d: Data: %s, Value: %.3f W, Desc: %s", snip.DeviceId, snip.IEC61850, snip.Value, snip.Description)
					}
					topic = fmt.Sprintf("%s/status/%d/%s", mqttTopic, snip.DeviceId, snip.IEC61850)

					t := mqttRateMap[topic]
					now := time.Now()
					if mqttRate == 0 || now.Unix() > t {
						message = fmt.Sprintf("%.3f", snip.Value)
						token = mqttClient.Publish(topic, byte(mqttQos), true, message)
						if verbose {
							log.Printf("MQTT: push %s, Message: %s", topic, message)
						}
						if token.Wait() && token.Error() != nil {
							log.Fatal("Error connecting to mqtt: ", token.Error())
							panic(token.Error())
						}
						mqttRateMap[topic] = now.Unix() + int64(mqttRate)
					} else {
						if verbose {
							log.Printf("Skiped push %s, Message: %s, Rate to high", topic, message)
						}
					}
				}
			}
			if resp.Body != nil {
				resp.Body.Close()
			}

			resp, err = client.Get(endpointURL)
			if err != nil {
				log.Fatal("Failed to read from endpoint: ", err.Error())
				topic = fmt.Sprintf("%s/connected", mqttTopic)
				message = fmt.Sprintf("1")
				token = mqttClient.Publish(topic, byte(mqttQos), true, message)
				if verbose {
					log.Printf("MQTT push %s, Message: %s", topic, message)
				}
				if token.Wait() && token.Error() != nil {
					log.Fatal("Error connecting to mqtt: ", token.Error())
					panic(token.Error())
				}
			}
		}
	}
	app.Run(os.Args)
}


text:
@article{RN3646,
 author = {Techamahasaranont, Jessada and Shrestha, Sangam and Babel, Mukand S and Shrestha, Rajendra P and Jourdain, Damien},
 issn = {1866-6280},
 journal = {Environmental Earth Sciences},
 number = {12},
 pages = {430},
 title = {Spatial and temporal variation in the trends of hydrological response of forested watersheds in Thailand},
 type = {Journal Article},
 volume = {76},
 year = {2017}
}


text:
SECTION = "devel/chicken"
DESCRIPTION = "Resource w/ Timeout"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://timed-resource.meta;md5=656963758ba49ab56c7be6be3764ee7f"
DEPENDS_append_class-cross = " chicken-egg-setup-helper-cross chicken-egg-record-variants-cross chicken-egg-check-errors-cross chicken-egg-thread-utils-cross chicken-egg-synch-cross"
DEPENDS_append_class-crosssdk = " chicken-egg-setup-helper-crosssdk chicken-egg-record-variants-crosssdk chicken-egg-check-errors-crosssdk chicken-egg-thread-utils-crosssdk chicken-egg-synch-crosssdk"
DEPENDS_append_class-nativesdk = " nativesdk-chicken-egg-setup-helper nativesdk-chicken-egg-record-variants nativesdk-chicken-egg-check-errors nativesdk-chicken-egg-thread-utils nativesdk-chicken-egg-synch chicken-egg-setup-helper-crosssdk chicken-egg-record-variants-crosssdk chicken-egg-check-errors-crosssdk chicken-egg-thread-utils-crosssdk chicken-egg-synch-crosssdk"
DEPENDS = " chicken-egg-setup-helper chicken-egg-record-variants chicken-egg-check-errors chicken-egg-thread-utils chicken-egg-synch chicken-egg-setup-helper-cross chicken-egg-record-variants-cross chicken-egg-check-errors-cross chicken-egg-thread-utils-cross chicken-egg-synch-cross"
RDEPENDS_${PN} = " chicken-egg-setup-helper chicken-egg-record-variants chicken-egg-check-errors chicken-egg-thread-utils chicken-egg-synch"

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

SRC_URI[md5sum] = "07b421311cc58609480c05fb3b532552"
SRC_URI[sha256sum] = "c108eb5506e66ff359e8e50d299acd29520d4fcabfdf419608e708f6e090864e"

S = "${WORKDIR}/timed-resource-${PV}"

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
// Weichao Qiu @ 2017
#include "ObjectHandler.h"

#include <fstream>
#include <iostream>

#include "Runtime/Engine/Classes/Engine/World.h"
#include "Runtime/CoreUObject/Public/UObject/UObjectGlobals.h"
#include "Runtime/CoreUObject/Public/UObject/Package.h"

#include "UnrealcvServer.h"
#include "Controller/ActorController.h"
#include "VertexSensor.h"
#include "Utils/StrFormatter.h"
#include "Utils/UObjectUtils.h"
#include "VisionBPLib.h"
#include "CubeActor.h"
#include "CommandInterface.h"
#include "Engine.h"
#include "Engine/Light.h"

// TODO: not implemented by UnrealCV author?
FExecStatus GetObjectMobility(const TArray<FString>& Args);

AStickerTextActor* FObjectHandler::GetStickerTextActor_I_th(int32 Index)
{
	TArray<AActor*> FoundActors;
	UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStickerTextActor::StaticClass(), FoundActors);
	if (FoundActors.Num() <= Index)
	{
		return nullptr;
	}
	return Cast<AStickerTextActor>(FoundActors[Index]);
}

ACameraWanderActor* FObjectHandler::GetCameraActor(int32 Index)
{
	TArray<AActor*> FoundActors;
	UGameplayStatics::GetAllActorsOfClass(GetWorld(), ACameraWanderActor::StaticClass(), FoundActors);
	if (FoundActors.Num() <= Index)
	{
		return nullptr;
	}
	return Cast<ACameraWanderActor>(FoundActors[Index]);
}

AEnvJitterActor* FObjectHandler::GetEnvController()
{
	TArray<AActor*> FoundActors;
	UGameplayStatics::GetAllActorsOfClass(GetWorld(), AEnvJitterActor::StaticClass(), FoundActors);
	if (FoundActors.Num() <= 0)
	{
		return nullptr;
	}
	return Cast<AEnvJitterActor>(FoundActors[0]);
}

void FObjectHandler::RegisterCommands()
{
	CommandDispatcher->BindCommand(
		"vget /objects",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetObjectList),
		"Get the name of all objects"
	);

	CommandDispatcher->BindCommand(
		"vset /objects/spawn_cube",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SpawnBox),
		"Spawn a box in the scene for debugging purpose."
	);

	CommandDispatcher->BindCommand(
		"vset /objects/spawn_cube [str]",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SpawnBox),
		"Spawn a box in the scene for debugging purpose, with optional argument name."
	);

	CommandDispatcher->BindCommand(
		"vset /objects/spawn [str]",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::Spawn),
		"Spawn an object with UClassName as the argument."
	);

	CommandDispatcher->BindCommand(
		"vget /object/[str]/location",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetLocation),
		"Get object location [x, y, z]"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/location [float] [float] [float]",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetLocation),
		"Set object location [x, y, z]"
	);

	CommandDispatcher->BindCommand(
		"vget /object/[str]/rotation",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetRotation),
		"Get object rotation [pitch, yaw, roll]"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/rotation [float] [float] [float]",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetRotation),
		"Set object rotation [pitch, yaw, roll]"
	);

	CommandDispatcher->BindCommand(
		"vget /object/[str]/vertex_location",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetObjectVertexLocation),
		"Get vertex location"
	);

	CommandDispatcher->BindCommand(
		"vget /object/[str]/color",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetAnnotationColor),
		"Get the labeling color of an object (used in object instance mask)"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/color [uint] [uint] [uint]",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetAnnotationColor),
		"Set the labeling color of an object [r, g, b]"
	);

	CommandDispatcher->BindCommand(
		"vget /object/[str]/mobility",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetMobility),
		"Is the object static or movable?"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/show",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetShow),
		"Show object"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/hide",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetHide),
		"Hide object"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/destroy",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::Destroy),
		"Destroy object"
	);

	CommandDispatcher->BindCommand(
		"vget /object/[str]/uclass_name",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetUClassName),
		"Get the UClass name for filtering objects"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/name [str]",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetName),
		"Set the name of the object"
	);

	// UnrealText Command
	// CommandDispatcher->BindCommand(TEXT("vget /object/stickertext/coor [uint] [float] [float] [float] [float] [float] [float] [float] [float]"),
	// 	FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetStickerTextCoordinates),
	// 	"Set the four coordinates (screen space) of an AStickerTextActor instance, and return the coordinates after adjustment");

	CommandDispatcher->BindCommand(TEXT("vset /object/stickertext/aspect [uint] [float]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetStickerTextMesh),
		"adjust the mesh to new aspect ratio; non-positive value for no adjustment");

	CommandDispatcher->BindCommand(TEXT("vset /object/stickertext/load [uint] [str]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::OrderTextToLoad),
		"order the text actor to load from a given text img file; be careful that the file name should not contain any spaces");

	CommandDispatcher->BindCommand(TEXT("vset /object/stickertext/glow [uint] [float] [float] [float]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetStickerTextGlowing),
		"Set the glowing parameters, in the order of R/G/B, range >1 for glowing; remember to limit the norm size, a suitable size is 200~500; ");

	CommandDispatcher->BindCommand(TEXT("vget /object/stickertext/getlocation [uint]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetStickerTextCoordinates),
		"return the coordinates in screen space");

	CommandDispatcher->BindCommand(TEXT("vget /object/cameramoverangefrom [float] [float]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetCameraMoveRange),
		"calculate how far the camera can go straight");

	CommandDispatcher->BindCommand(TEXT("vget /object/LoadTextAttr [str]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::LoadTextAttr),
		"LoadTextAttr");

	CommandDispatcher->BindCommand(TEXT("vget /object/GetAdjusted [uint] [str]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetAdjusted),
		"GetAdjusted");

	CommandDispatcher->BindCommand(TEXT("vget /object/LoadTextImages [str]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::LoadTextImages),
		"LoadTextImages");

	// by default, str = default, use the camera wander actor
	CommandDispatcher->BindCommand(TEXT("vget /object/walk [str]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::MoveCamera),
		"MoveCamera");

	// by default, str = default, use the camera wander actor
	CommandDispatcher->BindCommand(TEXT("vget /object/env [str]"),
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::EnvJitter),
		"EnvJitter");

#if WITH_EDITOR
	CommandDispatcher->BindCommand(
		"vget /object/[str]/label",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::GetActorLabel),
		"Get actor label"
	);

	CommandDispatcher->BindCommand(
		"vset /object/[str]/label [str]",
		FDispatcherDelegate::CreateRaw(this, &FObjectHandler::SetActorLabel),
		"Set actor label"
	);
#endif
}

AActor* GetActor(const TArray<FString>& Args)
{
	FString ActorId = Args[0];
	AActor* Actor = GetActorById(FUnrealcvServer::Get().GetWorld(), ActorId);
	return Actor;
}

FExecStatus FObjectHandler::GetObjectList(const TArray<FString>& Args)
{
	TArray<AActor*> ActorList;
	UVisionBPLib::GetActorList(ActorList);

	FString StrActorList;
	for (AActor* Actor : ActorList)
	{
		StrActorList += FString::Printf(TEXT("%s "), *Actor->GetName());
	}
	return FExecStatus::OK(StrActorList);
}

FExecStatus FObjectHandler::GetLocation(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");

	FActorController Controller(Actor);
	FVector Location = Controller.GetLocation();

	FStrFormatter Ar;
	Ar << Location;

	return FExecStatus::OK(Ar.ToString());
}

/** There is no guarantee this will always succeed, for example, hitting a wall */
FExecStatus FObjectHandler::SetLocation(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");
	FActorController Controller(Actor);

	// TODO: Check whether this object is movable
	float X = FCString::Atof(*Args[1]), Y = FCString::Atof(*Args[2]), Z = FCString::Atof(*Args[3]);
	FVector NewLocation = FVector(X, Y, Z);
	Controller.SetLocation(NewLocation);

	return FExecStatus::OK();
}

FExecStatus FObjectHandler::GetRotation(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");

	FActorController Controller(Actor);
	FRotator Rotation = Controller.GetRotation();

	FStrFormatter Ar;
	Ar << Rotation;

	return FExecStatus::OK(Ar.ToString());
}

FExecStatus FObjectHandler::SetRotation(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");
	FActorController Controller(Actor);

	// TODO: Check whether this object is movable
	float Pitch = FCString::Atof(*Args[1]), Yaw = FCString::Atof(*Args[2]), Roll = FCString::Atof(*Args[3]);
	FRotator Rotator = FRotator(Pitch, Yaw, Roll);
	Controller.SetRotation(Rotator);

	return FExecStatus::OK();
}

FExecStatus FObjectHandler::GetAnnotationColor(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");
	FActorController Controller(Actor);

	FColor AnnotationColor;
	Controller.GetAnnotationColor(AnnotationColor);
	return FExecStatus::OK(AnnotationColor.ToString());
}

FExecStatus FObjectHandler::SetAnnotationColor(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");
	FActorController Controller(Actor);

	// ObjectName, R, G, B, A = 255
	// The color format is RGBA
	uint32 R = FCString::Atoi(*Args[1]), G = FCString::Atoi(*Args[2]), B = FCString::Atoi(*Args[3]), A = 255; // A = FCString::Atoi(*Args[4]);
	FColor AnnotationColor(R, G, B, A);

	Controller.SetAnnotationColor(AnnotationColor);
	return FExecStatus::OK();
}

FExecStatus FObjectHandler::GetMobility(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");
	FActorController Controller(Actor);

	FString MobilityName = "";
	EComponentMobility::Type Mobility = Controller.GetMobility();
	switch (Mobility)
	{
		case EComponentMobility::Type::Movable: MobilityName = "Movable"; break;
		case EComponentMobility::Type::Static: MobilityName = "Static"; break;
		case EComponentMobility::Type::Stationary: MobilityName = "Stationary"; break;
		default: MobilityName = "Unknown";
	}
	return FExecStatus::OK(MobilityName);
}

FExecStatus FObjectHandler::SetShow(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");

	FActorController Controller(Actor);
	Controller.Show();
	return FExecStatus::OK();
}

FExecStatus FObjectHandler::SetHide(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");

	FActorController Controller(Actor);
	Controller.Hide();
	return FExecStatus::OK();
}

FExecStatus FObjectHandler::GetObjectVertexLocation(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	FVertexSensor VertexSensor(Actor);
	TArray<FVector> VertexArray = VertexSensor.GetVertexArray();

	// Serialize it to json?
	FString Str = "";
	for (auto Vertex : VertexArray)
	{
		FString VertexLocation = FString::Printf(
			TEXT("%.5f     %.5f     %.5f"),
			Vertex.X, Vertex.Y, Vertex.Z);
		Str += VertexLocation + "\n";
	}

	return FExecStatus::OK(Str);
}

/** A debug utility function to create StaticBox through python API */
FExecStatus FObjectHandler::SpawnBox(const TArray<FString>& Args)
{
	FString ObjectName;
	if (Args.Num() == 1) { ObjectName = Args[0]; }

	UWorld* GameWorld = FUnrealcvServer::Get().GetWorld();
	AActor* Actor = GameWorld->SpawnActor(ACubeActor::StaticClass());

	return FExecStatus::OK();
}

FExecStatus FObjectHandler::Spawn(const TArray<FString>& Args)
{
	FString UClassName;
	if (Args.Num() == 1) { UClassName = Args[0]; }
	// Lookup UClass with a string
	UClass*	Class = FindObject<UClass>(ANY_PACKAGE, *UClassName);

	if (!IsValid(Class))
	{
		return FExecStatus::Error(FString::Printf(TEXT("Can not find a class with name '%s'"), *UClassName));
	}

	UWorld* GameWorld = FUnrealcvServer::Get().GetWorld();
	AActor* Actor = GameWorld->SpawnActor(Class);
	if (IsValid(Actor))
	{
		return FExecStatus::OK(Actor->GetName());
	}
	else
	{
		return FExecStatus::Error("Failed to spawn actor");
	}
}

FExecStatus FObjectHandler::Destroy(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");

	Actor->Destroy();
	return FExecStatus::OK();
}

FExecStatus FObjectHandler::GetUClassName(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");

	FString UClassName = Actor->StaticClass()->GetName();
	return FExecStatus::OK(UClassName);
}

/** Get component names of the object */
FExecStatus FObjectHandler::GetComponents(const TArray<FString>& Args)
{
	return FExecStatus::OK();
}

FExecStatus FObjectHandler::SetName(const TArray<FString>& Args)
{
	if (Args.Num() != 2)
	{
		return FExecStatus::InvalidArgument;
	}
	AActor* Actor = GetActor(Args);
	if (!Actor) return FExecStatus::Error("Can not find object");

	FString NewName = Args[1];
	// Check whether the object name already exists, otherwise it will crash in
	// File:/home/qiuwch/UnrealEngine/Engine/Source/Runtime/CoreUObject/Private/UObject/Obj.cpp] [Line: 198]

	UObject* NameScopeOuter = ANY_PACKAGE;
	UObject* ExistingObject = StaticFindObject(/*Class=*/ NULL, NameScopeOuter, *NewName, true);
	if (IsValid(ExistingObject))
	{
		if (ExistingObject == Actor)
		{
			return FExecStatus::OK("The name has already been set");
		}
		else if (ExistingObject)
		{
			return FExecStatus::Error("Renaming an object on top of an existing object is not allowed");
		}
	}
	else
	{
		ICommandInterface* CmdActor = Cast<ICommandInterface>(Actor);
		if (CmdActor) CmdActor->UnbindCommands();
		Actor->Rename(*NewName);
		if (CmdActor) CmdActor->BindCommands();
		return FExecStatus::OK();
	}
	return FExecStatus::OK();
}

// UnrealText Command

// FExecStatus FObjectHandler::SetStickerTextCoordinates(const TArray<FString>& Args)
// {
// 	if (Args.Num() == 9)
// 	{
// 		AStickerTextActor* TextInstance = GetStickerTextActor_I_th(FCString::Atoi(*Args[0]));
// 		if (TextInstance == nullptr)
// 		{
// 			return FExecStatus::Error(FString::Printf(TEXT("SetStickerTextCoordinates: instance index out of range!")));
// 		}
// 		// actual code
// 		FVector2D Point_UL, Point_UR, Point_BR, Point_BL;
// 		TextInstance->Handle_SetTextPositionFromScreen(FCString::Atof(*Args[1]), FCString::Atof(*Args[2]), FCString::Atof(*Args[3]), FCString::Atof(*Args[4]), FCString::Atof(*Args[5]), FCString::Atof(*Args[6]), FCString::Atof(*Args[7]), FCString::Atof(*Args[8]), Point_UL, Point_UR, Point_BR, Point_BL);
// 		return FExecStatus::OK(FString::Printf(TEXT("Location after adjustment: %.3f %.3f %.3f %.3f %.3f %.3f %.3f %.3f"), Point_UL[0], Point_UL[1], Point_UR[0], Point_UR[1], Point_BR[0], Point_BR[1], Point_BL[0], Point_BL[1]));

// 	}
// 	return FExecStatus::Error(FString::Printf(TEXT("SetStickerTextCoordinates: Absent args!")));
// }

FExecStatus FObjectHandler::SetStickerTextMesh(const TArray<FString>& Args)
{
	if (Args.Num() == 2)
	{
		AStickerTextActor* TextInstance = GetStickerTextActor_I_th(FCString::Atoi(*Args[0]));
		if (TextInstance == nullptr)
		{
			return FExecStatus::Error(FString::Printf(TEXT("SetStickerTextMesh: instance index out of range!")));
		}
		// actual code
		TextInstance->Handle_ResizeAndGenerateMesh(FCString::Atof(*Args[1]));
		return FExecStatus::OK();

	}
	return FExecStatus::Error(FString::Printf(TEXT("SetStickerTextMesh: Absent args!")));
}

FExecStatus FObjectHandler::OrderTextToLoad(const TArray<FString>& Args)
{
	if (Args.Num() == 2)
	{
		AStickerTextActor* TextInstance = GetStickerTextActor_I_th(FCString::Atoi(*Args[0]));
		if (TextInstance == nullptr)
		{
			return FExecStatus::Error(FString::Printf(TEXT("OrderTextToLoad: instance index out of range!")));
		}
		// actual code
		TextInstance->Handle_LoadTextFromPngPath(*Args[1]);
		return FExecStatus::OK();

	}
	return FExecStatus::Error(FString::Printf(TEXT("OrderTextToLoad: Absent args!")));
}

FExecStatus FObjectHandler::SetStickerTextGlowing(const TArray<FString>& Args)
{
	if (Args.Num() == 4)
	{
		AStickerTextActor* TextInstance = GetStickerTextActor_I_th(FCString::Atoi(*Args[0]));
		if (TextInstance == nullptr)
		{
			return FExecStatus::Error(FString::Printf(TEXT("SetStickerTextGlowing: instance index out of range!")));
		}
		// actual code
		TextInstance->EmissiveColor.R = FCString::Atof(*Args[1]);
		TextInstance->EmissiveColor.G = FCString::Atof(*Args[2]);
		TextInstance->EmissiveColor.B = FCString::Atof(*Args[3]);
		return FExecStatus::OK();

	}
	return FExecStatus::Error(FString::Printf(TEXT("SetStickerTextGlowing: Absent args!")));
}

FExecStatus FObjectHandler::GetStickerTextCoordinates(const TArray<FString>& Args)
{
	if (Args.Num() == 1)
	{
		AStickerTextActor* TextInstance = GetStickerTextActor_I_th(FCString::Atoi(*Args[0]));
		if (TextInstance == nullptr)
		{
			return FExecStatus::Error(FString::Printf(TEXT("GetStickerTextCoordinates: instance index out of range!")));
		}
		// actual code
		FVector2D Point_UL, Point_UR, Point_BR, Point_BL;
		TextInstance->Handle_GetCornerCoor(Point_UL, Point_UR, Point_BR, Point_BL);
		return FExecStatus::OK(FString::Printf(TEXT("Location after adjustment: %.3f %.3f %.3f %.3f %.3f %.3f %.3f %.3f"), Point_UL[0], Point_UL[1], Point_UR[0], Point_UR[1], Point_BR[0], Point_BR[1], Point_BL[0], Point_BL[1]));

	}
	return FExecStatus::Error(FString::Printf(TEXT("GetStickerTextCoordinates: Absent args!")));
}

FExecStatus FObjectHandler::GetCameraMoveRange(const TArray<FString>& Args)
{
	if (Args.Num() == 2)
	{
        // transform
		FVector2D Center = FVector2D(FCString::Atof(*Args[0]),
		                             FCString::Atof(*Args[1]));
		// collision
		AStickerTextActor* TextInstance = GetStickerTextActor_I_th(0);
		FVector WorldPosition = FVector(0.0f, 0.0f, 0.0f);
		FVector WorldDirection = FVector(0.0f, 0.0f, 0.0f);
		FHitResult HitResult;
		UGameplayStatics::GetPlayerController(GetWorld(), 0)->DeprojectScreenPositionToWorld(Center[0], Center[1], WorldPosition, WorldDirection);
		bool HitFlag = GetWorld()->LineTraceSingleByChannel(HitResult, WorldPosition, WorldPosition + WorldDirection * 3000.0f, ECC_Visibility, TextInstance->TraceParams);
		FVector HitPointLocation;
		if (HitFlag)
		{
			HitPointLocation = HitResult.Location;
		}
		else
		{
			HitPointLocation = WorldPosition + WorldDirection * 1000.0f;
		}

		return FExecStatus::OK(FString::Printf(TEXT("HitPointLocation: %.3f %.3f %.3f %.3f %.3f %.3f"), WorldPosition.X, WorldPosition.Y, WorldPosition.Z, HitPointLocation.X, HitPointLocation.Y, HitPointLocation.Z));

	}
	return FExecStatus::Error(FString::Printf(TEXT("GetCameraMoveRange: Absent args!")));
}

FExecStatus FObjectHandler::MoveCamera(const TArray<FString>& Args)
{
	UE_LOG(LogTemp, Warning, TEXT("Start to move"));
	if (Args.Num() == 1)
	{
        if (Args[0] == "default")
		{
			ACameraWanderActor * camera_default = GetCameraActor(0);
			UE_LOG(LogTemp, Warning, TEXT("Camera walker found"));
			camera_default->Handle_TakeOneStep();
			return FExecStatus::OK();
		}
		return FExecStatus::Error(FString::Printf(TEXT("Move Camera: wrong types!")));

	}
	return FExecStatus::Error(FString::Printf(TEXT("Move Camera: wrong args!")));
}

FExecStatus FObjectHandler::EnvJitter(const TArray<FString>& Args)
{
	UE_LOG(LogTemp, Warning, TEXT("Start to alter environment"));
	if (Args.Num() == 1)
	{
		AEnvJitterActor * env_jitter_actor = GetEnvController();
		UE_LOG(LogTemp, Warning, TEXT("Env Jitter Found"));
		env_jitter_actor->Handle_Command(Args[0]);
		return FExecStatus::OK();
	}
	return FExecStatus::Error(FString::Printf(TEXT("Move Camera: wrong args!")));
}

//LoadTextAttr
FExecStatus FObjectHandler::LoadTextAttr(const TArray<FString>& Args)
{
	UE_LOG(LogTemp, Warning, TEXT("Start to load attributes"));
	if (Args.Num() == 1)
	{
		TArray<AActor*> FoundActors;
		UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStickerTextActor::StaticClass(), FoundActors);
		std::string FileName = std::string(TCHAR_TO_UTF8(*(Args[0])));
		std::ifstream FileHandle;
		FileHandle.open(FileName);
		int32 text_num;
		FileHandle >> text_num;
		for (int32 text_id=0;text_id<text_num;text_id++)
		{
			if (FoundActors.Num() <= text_id)
			{
				break;
			}
			float UL_X, UL_Y, BR_X, BR_Y, Color_R, Color_G, Color_B, Spe, Met, Rou;
			FileHandle>>UL_X>>UL_Y>>BR_X>>BR_Y>>Color_R>>Color_G>>Color_B>>Spe>>Met>>Rou;
			UE_LOG(LogTemp, Warning, TEXT("Text %d box loaded: %f %f %f %f %f %f %f %f %f %f"), text_id, UL_X, UL_Y, BR_X, BR_Y, Color_R, Color_G, Color_B, Spe, Met, Rou);
			Cast<AStickerTextActor>(FoundActors[text_id])->Handle_SetAttr(UL_X, UL_Y, BR_X, BR_Y, Color_R, Color_G, Color_B, Spe, Met, Rou);
		}

		UE_LOG(LogTemp, Warning, TEXT("Ended loading, waiting for triangulation finishes ... "));
		FileHandle.close();
		return FExecStatus::OK();

	}
	return FExecStatus::Error(FString::Printf(TEXT("text attr load: wrong args!")));
}

FExecStatus FObjectHandler::GetAdjusted(const TArray<FString>& Args)
{
	UE_LOG(LogTemp, Warning, TEXT("Start to save adjusted locations"));
	if (Args.Num() == 2)
	{
		TArray<AActor*> FoundActors;
		UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStickerTextActor::StaticClass(), FoundActors);
		std::string outputFileName = std::string(TCHAR_TO_UTF8(*(Args[1])));
  		std::ofstream outputFileHandle;
		outputFileHandle.open(outputFileName);

		bool all_done = false;
		int32 text_num = FCString::Atoi(*Args[0]);
		while (!all_done)
		{
			all_done = true;
			for (int32 text_id=0;text_id<text_num;text_id++)
			{
				if (FoundActors.Num() <= text_id)
				{
					break;
				}
				if (Cast<AStickerTextActor>(FoundActors[text_id])->isProcessed)
				{
					// box is invalid, or the triangulation is finished
					;
				}
				else
				{
					all_done = false;
				}
			}
		}
		UE_LOG(LogTemp, Warning, TEXT("All done, ready to write adjusted box ... "));
		for (int32 text_id=0;text_id<text_num;text_id++)
		{
			if (FoundActors.Num() <= text_id)
			{
				break;
			}
			FVector2D Point_UL, Point_UR, Point_BR, Point_BL;
			Cast<AStickerTextActor>(FoundActors[text_id])->Handle_GetCornerCoor(Point_UL, Point_UR, Point_BR, Point_BL);
			if (Cast<AStickerTextActor>(FoundActors[text_id])->isBoxValid)
			{
				outputFileHandle<<1<<",";
			}
			else
			{
				outputFileHandle<<0<<","; // 0 denotes failed triangles
			}
			outputFileHandle<<(int32)Point_UL[0]<<","<<(int32)Point_UL[1]<<","
			                <<(int32)Point_UR[0]<<","<<(int32)Point_UR[1]<<","
							<<(int32)Point_BR[0]<<","<<(int32)Point_BR[1]<<","
							<<(int32)Point_BL[0]<<","<<(int32)Point_BL[1]<<std::endl;
		}
		outputFileHandle.close();
		return FExecStatus::OK();

	}
	return FExecStatus::Error(FString::Printf(TEXT("text save path: wrong args!")));
}

FExecStatus FObjectHandler::LoadTextImages(const TArray<FString>& Args)
{
	UE_LOG(LogTemp, Warning, TEXT("Start to save adjusted locations"));
	if (Args.Num() == 1)
	{
		TArray<AActor*> FoundActors;
		UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStickerTextActor::StaticClass(), FoundActors);

		std::string FileName = std::string(TCHAR_TO_UTF8(*(Args[0])));
  		std::ifstream FileHandle;
		FileHandle.open(FileName);
		int32 text_num;
		FileHandle >> text_num;
		for (int32 text_id=0;text_id<text_num;text_id++)
		{
			if (FoundActors.Num() <= text_id)
			{
				break;
			}
			std::string word_path;
			FileHandle >> word_path;
			FString WordFSTRING(word_path.c_str());
			if (Cast<AStickerTextActor>(FoundActors[text_id])->isTriangulationFinished)
			{
				Cast<AStickerTextActor>(FoundActors[text_id])->Handle_LoadTextFromPngPath(WordFSTRING);
			}
		}

		FileHandle.close();
		return FExecStatus::OK();

	}
	return FExecStatus::Error(FString::Printf(TEXT("text save path: wrong args!")));
}
// end UnrealText Command

#if WITH_EDITOR
FExecStatus FObjectHandler::SetActorLabel(const TArray<FString>& Args)
{
	FString ActorLabel;
	if (Args.Num() == 2) { ActorLabel = Args[1]; }

	AActor* Actor = GetActor(Args);
	if (!IsValid(Actor)) return FExecStatus::Error("Can not find object");

	Actor->SetActorLabel(ActorLabel);
	return FExecStatus::OK();
}

FExecStatus FObjectHandler::GetActorLabel(const TArray<FString>& Args)
{
	AActor* Actor = GetActor(Args);
	if (!IsValid(Actor)) return FExecStatus::Error("Can not find object");

	FString ActorLabel = Actor->GetActorLabel();
	return FExecStatus::OK(ActorLabel);
}
#endif

extension: cpp


text:
/*
Copyright 2020 The Kubernetes 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 secretsstore

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"sync"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"

	"sigs.k8s.io/secrets-store-csi-driver/pkg/test_utils/tmpdir"
	"sigs.k8s.io/secrets-store-csi-driver/provider/fake"
	"sigs.k8s.io/secrets-store-csi-driver/provider/v1alpha1"
)

func fakeServer(t *testing.T, path, provider string) (*fake.MockCSIProviderServer, func()) {
	t.Helper()
	serverEndpoint := fmt.Sprintf("%s/%s.sock", path, provider)
	server, err := fake.NewMocKCSIProviderServer(serverEndpoint)
	if err != nil {
		t.Fatalf("expected err to be nil, got: %+v", err)
	}

	cleanup := func() {
		server.Stop()
		os.Remove(serverEndpoint)
	}

	return server, cleanup
}

func TestMountContent(t *testing.T) {
	cases := []struct {
		name string
		// inputs
		permission string
		// mock outputs
		objectVersions map[string]string
		providerError  error
		files          []*v1alpha1.File
		// expectations
		expectedFiles map[string]os.FileMode
	}{
		{
			name:           "provider successful response (no files)",
			permission:     "420",
			objectVersions: map[string]string{"secret/secret1": "v1", "secret/secret2": "v2"},
			expectedFiles:  map[string]os.FileMode{},
		},
		{
			name:       "provider response with file",
			permission: "777",
			files: []*v1alpha1.File{
				{
					Path:     "foo",
					Mode:     0644,
					Contents: []byte("foo"),
				},
			},
			objectVersions: map[string]string{"foo": "v1"},
			expectedFiles: map[string]os.FileMode{
				"foo": 0644,
			},
		},
		{
			name:       "provider response with multiple files",
			permission: "777",
			files: []*v1alpha1.File{
				{
					Path:     "foo",
					Mode:     0644,
					Contents: []byte("foo"),
				},
				{
					Path:     "bar",
					Mode:     0777,
					Contents: []byte("bar"),
				},
			},
			objectVersions: map[string]string{"foo": "v1"},
			expectedFiles: map[string]os.FileMode{
				"foo": 0644,
				"bar": 0777,
			},
		},
	}

	for _, test := range cases {
		t.Run(test.name, func(t *testing.T) {
			socketPath := tmpdir.New(t, "", "ut")
			targetPath := tmpdir.New(t, "", "ut")

			pool := NewPluginClientBuilder(socketPath)
			defer pool.Cleanup()

			server, cleanup := fakeServer(t, socketPath, "provider1")
			defer cleanup()

			server.SetReturnError(test.providerError)
			server.SetObjects(test.objectVersions)
			server.SetFiles(test.files)
			server.Start()

			client, err := pool.Get(context.Background(), "provider1")
			if err != nil {
				t.Fatalf("expected err to be nil, got: %+v", err)
			}

			objectVersions, _, err := MountContent(context.TODO(), client, "{}", "{}", targetPath, test.permission, nil)
			if err != nil {
				t.Errorf("expected err to be nil, got: %+v", err)
			}
			if test.objectVersions != nil && !reflect.DeepEqual(test.objectVersions, objectVersions) {
				t.Errorf("expected object versions: %v, got: %+v", test.objectVersions, objectVersions)
			}

			// check that file was written
			gotFiles := make(map[string]os.FileMode)
			filepath.Walk(targetPath, func(path string, info os.FileInfo, err error) error {
				// skip mount folder
				if path == targetPath {
					return nil
				}
				rel, err := filepath.Rel(targetPath, path)
				if err != nil {
					return err
				}
				gotFiles[rel] = info.Mode()
				return nil
			})

			if diff := cmp.Diff(test.expectedFiles, gotFiles); diff != "" {
				t.Errorf("MountContent() file mismatch (-want +got):\n%s", diff)
			}
		})
	}
}

func TestMountContentError(t *testing.T) {
	cases := []struct {
		name                  string
		attributes            string
		secrets               string
		targetPath            string
		permission            string
		expectedObjectVersion map[string]string
		providerError         error
		expectedErrorCode     string
	}{
		{
			name:              "missing attributes in mount request",
			expectedErrorCode: "GRPCProviderError",
		},
		{
			name:              "missing target path in mount request",
			attributes:        "{}",
			expectedErrorCode: "GRPCProviderError",
		},
		{
			name:              "missing permission in mount request",
			attributes:        "{}",
			targetPath:        "/var/lib/kubelet/pods/d448c6a2-cda8-42e3-84fb-3cf75faa8399/volumes/kubernetes.io~csi/secrets-store-inline/mount",
			expectedErrorCode: "GRPCProviderError",
		},
		{
			name:              "provider error for mount request",
			attributes:        "{}",
			targetPath:        "/var/lib/kubelet/pods/d448c6a2-cda8-42e3-84fb-3cf75faa8399/volumes/kubernetes.io~csi/secrets-store-inline/mount",
			permission:        "0644",
			expectedErrorCode: "GRPCProviderError",
		},
		{
			name:              "missing object versions in mount response",
			attributes:        "{}",
			targetPath:        "/var/lib/kubelet/pods/d448c6a2-cda8-42e3-84fb-3cf75faa8399/volumes/kubernetes.io~csi/secrets-store-inline/mount",
			permission:        "0644",
			expectedErrorCode: "GRPCProviderError",
		},
		{
			name:              "provider error",
			attributes:        "{}",
			targetPath:        "/var/lib/kubelet/pods/d448c6a2-cda8-42e3-84fb-3cf75faa8399/volumes/kubernetes.io~csi/secrets-store-inline/mount",
			permission:        "0644",
			providerError:     errors.New("failed in provider"),
			expectedErrorCode: "GRPCProviderError",
		},
		{
			name:              "provider returns error code",
			attributes:        "{}",
			targetPath:        "/var/lib/kubelet/pods/d448c6a2-cda8-42e3-84fb-3cf75faa8399/volumes/kubernetes.io~csi/secrets-store-inline/mount",
			permission:        "420",
			secrets:           "{}",
			expectedErrorCode: "AuthenticationFailed",
		},
	}

	for _, test := range cases {
		t.Run(test.name, func(t *testing.T) {
			socketPath := tmpdir.New(t, "", "ut")

			pool := NewPluginClientBuilder(socketPath)
			defer pool.Cleanup()

			providerName := "provider1"

			server, cleanup := fakeServer(t, socketPath, providerName)
			defer cleanup()

			server.SetReturnError(test.providerError)
			server.SetObjects(test.expectedObjectVersion)
			server.SetProviderErrorCode(test.expectedErrorCode)
			server.Start()

			client, err := pool.Get(context.Background(), providerName)
			if err != nil {
				t.Fatalf("expected err to be nil, got: %+v", err)
			}

			objectVersions, errorCode, err := MountContent(context.TODO(), client, test.attributes, test.secrets, test.targetPath, test.permission, nil)
			if err == nil {
				t.Errorf("expected err to be not nil")
			}
			if errorCode != test.expectedErrorCode {
				t.Errorf("expected error code: %v, got: %+v", test.expectedErrorCode, errorCode)
			}
			if test.expectedObjectVersion != nil && !reflect.DeepEqual(test.expectedObjectVersion, objectVersions) {
				t.Errorf("expected object versions: %v, got: %+v", test.expectedObjectVersion, objectVersions)
			}
		})
	}
}

func TestPluginClientBuilder(t *testing.T) {
	path := tmpdir.New(t, "", "ut")

	cb := NewPluginClientBuilder(path)
	ctx := context.Background()

	for i := 0; i < 10; i++ {
		server, cleanup := fakeServer(t, path, fmt.Sprintf("server-%d", i))
		defer cleanup()
		server.Start()
	}

	var wg sync.WaitGroup

	for i := 0; i < 10; i++ {
		wg.Add(1)
		provider := fmt.Sprintf("server-%d", i)
		go func() {
			defer wg.Done()
			if _, err := cb.Get(ctx, provider); err != nil {
				t.Errorf("Get(%q) = %v, want nil", provider, err)
			}
		}()
	}

	wg.Wait()
}

func TestPluginClientBuilder_ConcurrentGet(t *testing.T) {
	path := tmpdir.New(t, "", "ut")

	cb := NewPluginClientBuilder(path)
	ctx := context.Background()

	provider := "server"
	server, cleanup := fakeServer(t, path, provider)
	defer cleanup()
	server.Start()

	var wg sync.WaitGroup

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if _, err := cb.Get(ctx, provider); err != nil {
				t.Errorf("Get(%q) = %v, want nil", provider, err)
			}
		}()
	}

	wg.Wait()
}

func TestPluginClientBuilderErrorNotFound(t *testing.T) {
	path := tmpdir.New(t, "", "ut")

	cb := NewPluginClientBuilder(path)
	ctx := context.Background()

	if _, err := cb.Get(ctx, "notfoundprovider"); errors.Unwrap(err) != ErrProviderNotFound {
		t.Errorf("Get(%s) = %v, want %v", "notfoundprovider", err, ErrProviderNotFound)
	}

	// check that the provider is found once server is started
	server, cleanup := fakeServer(t, path, "notfoundprovider")
	defer cleanup()
	server.Start()

	if _, err := cb.Get(ctx, "notfoundprovider"); err != nil {
		t.Errorf("Get(%s) = %v, want nil", "notfoundprovider", err)
	}
}

func TestPluginClientBuilderErrorInvalid(t *testing.T) {
	path := tmpdir.New(t, "", "ut")

	cb := NewPluginClientBuilder(path)
	ctx := context.Background()

	if _, err := cb.Get(ctx, "bad/provider/name"); errors.Unwrap(err) != ErrInvalidProvider {
		t.Errorf("Get(%s) = %v, want %v", "bad/provider/name", err, ErrInvalidProvider)
	}
}

func TestVersion(t *testing.T) {
	cases := []struct {
		name                   string
		expectedRuntimeVersion string
	}{
		{
			name:                   "provider version successful response",
			expectedRuntimeVersion: "0.0.10",
		},
	}

	for _, test := range cases {
		t.Run(test.name, func(t *testing.T) {
			socketPath := tmpdir.New(t, "", "ut")

			pool := NewPluginClientBuilder(socketPath)
			defer pool.Cleanup()

			server, cleanup := fakeServer(t, socketPath, "provider1")
			defer cleanup()

			server.Start()

			client, err := pool.Get(context.Background(), "provider1")
			if err != nil {
				t.Fatalf("expected err to be nil, got: %+v", err)
			}

			runtimeVersion, err := Version(context.TODO(), client)
			if err != nil {
				t.Errorf("expected err to be nil, got: %+v", err)
			}
			if test.expectedRuntimeVersion != runtimeVersion {
				t.Errorf("expected version: %s, got: %s", test.expectedRuntimeVersion, runtimeVersion)
			}
		})
	}
}

func TestPluginClientBuilder_HealthCheck(t *testing.T) {
	// this test asserts the read lock and unlock semantics in the
	// HealthCheck() method work as expected
	path := tmpdir.New(t, "", "ut")

	cb := NewPluginClientBuilder(path)
	ctx := context.Background()
	healthCheckInterval := 1 * time.Millisecond

	provider := "server"
	server, cleanup := fakeServer(t, path, provider)
	defer cleanup()
	server.Start()

	// run the provider healthcheck
	go cb.HealthCheck(ctx, healthCheckInterval)
	var wg sync.WaitGroup

	// try a concurrent get with the healthcheck running in the background
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if _, err := cb.Get(ctx, provider); err != nil {
				t.Errorf("Get(%q) = %v, want nil", provider, err)
			}
		}()
	}

	wg.Wait()
}

repository: demosanzx/secrets-store-csi-driver

repo_name: demosanzx/secrets-store-csi-driver


text:
package main

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
	req, _ := http.NewRequest(method, path, nil)
	w := httptest.NewRecorder()

	r.ServeHTTP(w, req)

	return w
}

func TestHelloWorld(t *testing.T) {
	body := gin.H{
		"hello": "world",
	}

	router := SetupRouter()

	w := performRequest(router, "GET", "/")

	assert.Equal(t, http.StatusOK, w.Code)

	var response map[string]string
	err := json.Unmarshal([]byte(w.Body.String()), &response)

	value, exists := response["hello"]

	assert.Nil(t, err)
	assert.True(t, exists)
	assert.Equal(t, body["hello"], value)
}

func TestPlus(t *testing.T) {
	router := SetupRouter()

	w := performRequest(router, "POST", "/plus/9/7")

	var response map[string]int
	err := json.Unmarshal([]byte(w.Body.String()), &response)

	value, exists := response["result"]

	assert.Nil(t, err)
	assert.True(t, exists)
	assert.Equal(t, value, 16)
}

func TestMultiple(t *testing.T) {
	router := SetupRouter()

	w := performRequest(router, "POST", "/multiple/9/7")

	result, _ := strconv.ParseFloat(w.Body.String(), 64)

	assert.Equal(t, result, float64(9*7))
}

func TestProfile(t *testing.T) {
	router := SetupRouter()

	w := performRequest(router, "GET", "/profile")

	var response map[string]interface{}
	err := json.Unmarshal([]byte(w.Body.String()), &response)

	status, _ := response["status"]
	data, _ := response["data"].(map[string]interface{})

	assert.Nil(t, err)
	assert.Equal(t, status, float64(200))
	assert.Equal(t, data["name"], "Surya")
	assert.Equal(t, data["role"], "Developer")
}

branch_name: refs/heads/main


text:
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/media/effects/media_effects_service_factory.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"

class MediaEffectsServiceFactoryTest : public testing::Test {
 public:
  MediaEffectsServiceFactoryTest()
      : profile_manager_(TestingBrowserProcess::GetGlobal()) {}

  void SetUp() override {
    ASSERT_TRUE(profile_manager_.SetUp());
    profile1_ = profile_manager_.CreateTestingProfile("TestProfile1");
    profile2_ = profile_manager_.CreateTestingProfile("TestProfile2");
  }

  void TearDown() override {
    profile1_ = nullptr;
    profile2_ = nullptr;
    profile_manager_.DeleteAllTestingProfiles();
  }

 protected:
  raw_ptr<TestingProfile> profile1_;
  raw_ptr<TestingProfile> profile2_;

 private:
  content::BrowserTaskEnvironment task_environment_;
  TestingProfileManager profile_manager_;
};

TEST_F(MediaEffectsServiceFactoryTest,
       GetForProfile_SameProfileReturnsSameService) {
  ASSERT_NE(profile1_, profile2_);
  EXPECT_EQ(MediaEffectsServiceFactory::GetForProfile(profile1_),
            MediaEffectsServiceFactory::GetForProfile(profile1_));
  EXPECT_EQ(MediaEffectsServiceFactory::GetForProfile(profile2_),
            MediaEffectsServiceFactory::GetForProfile(profile2_));
}

TEST_F(MediaEffectsServiceFactoryTest,
       GetForProfile_DifferentProfileReturnsDifferentService) {
  ASSERT_NE(profile1_, profile2_);
  EXPECT_NE(MediaEffectsServiceFactory::GetForProfile(profile1_),
            MediaEffectsServiceFactory::GetForProfile(profile2_));
}

TEST_F(MediaEffectsServiceFactoryTest,
       GetForProfile_IncognitoProfileReturnsDifferentService) {
  auto* incognito_profile2 =
      TestingProfile::Builder().BuildIncognito(profile2_);
  ASSERT_NE(profile2_, incognito_profile2);
  EXPECT_NE(MediaEffectsServiceFactory::GetForProfile(profile2_),
            MediaEffectsServiceFactory::GetForProfile(incognito_profile2));
}

repository: chromium/chromium

repo_name: chromium/chromium

extension: cc


text:
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package ui

import (
	"context"
	"fmt"
	"math"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/mafredri/cdp/rpcc"

	"chromiumos/tast/common/perf"
	"chromiumos/tast/ctxutil"
	"chromiumos/tast/errors"
	"chromiumos/tast/local/arc"
	"chromiumos/tast/local/arc/optin"
	uiperf "chromiumos/tast/local/bundles/cros/ui/perf"
	"chromiumos/tast/local/chrome"
	"chromiumos/tast/local/chrome/ash"
	"chromiumos/tast/local/chrome/browser"
	"chromiumos/tast/local/chrome/lacros"
	"chromiumos/tast/local/chrome/lacros/lacrosfixt"
	"chromiumos/tast/local/chrome/metrics"
	"chromiumos/tast/local/chrome/uiauto"
	"chromiumos/tast/local/chrome/uiauto/faillog"
	"chromiumos/tast/local/chrome/uiauto/lockscreen"
	"chromiumos/tast/local/chrome/uiauto/nodewith"
	"chromiumos/tast/local/chrome/uiauto/ossettings"
	"chromiumos/tast/local/chrome/uiauto/role"
	"chromiumos/tast/local/input"
	"chromiumos/tast/local/perfutil"
	"chromiumos/tast/local/session"
	"chromiumos/tast/local/ui/cujrecorder"
	"chromiumos/tast/testing"
)

type loginPerfTestParam struct {
	bt              browser.Type     // browser.{TypeAsh/TypeLacros}
	lacrosSelection lacros.Selection // lacros.{Omaha,Rootfs}
	lacrosMode      lacros.Mode      // lacros.{LacrosPrimary,LacrosSideBySide}
}

func init() {
	testing.AddTest(&testing.Test{
		Func:         LoginPerf,
		LacrosStatus: testing.LacrosVariantUnknown,
		Desc:         "Measures performance and UI smoothness of ChromeOS login",
		Contacts: []string{
			"alemate@google.com",
			"oshima@google.com",
			"chromeos-wmp@google.com",
		},
		SoftwareDeps: []string{"chrome"},
		VarDeps: []string{
			"ui.signinProfileTestExtensionManifestKey",
			"ui.gaiaPoolDefault",
		},
		// Test runs login / chrome restart 120+ times.
		Timeout: 120 * time.Minute,
		Data:    []string{"animation.html", "animation.js"},
		Params: []testing.Param{{
			Name:      "ash_chrome",
			ExtraAttr: []string{"group:cuj"},
			Val: loginPerfTestParam{
				browser.TypeAsh, lacros.NotSelected, lacros.NotSpecified,
			},
		}, {
			Name:      "lacros_chrome_root_fs_primary",
			ExtraAttr: []string{"group:cuj"},
			Val: loginPerfTestParam{
				browser.TypeLacros, lacros.Rootfs, lacros.LacrosPrimary,
			},
		}, {
			Name:      "lacros_chrome_root_fs_side_by_side",
			ExtraAttr: []string{"group:cuj"},
			Val: loginPerfTestParam{
				browser.TypeLacros, lacros.Rootfs, lacros.LacrosSideBySide,
			},
		}, {
			Name: "lacros_chrome_omaha_primary",
			// Disabled per b/246818834.
			ExtraAttr: []string{},
			Val: loginPerfTestParam{
				browser.TypeLacros, lacros.Omaha, lacros.LacrosPrimary,
			},
		}, {
			Name: "lacros_chrome_omaha_side_by_side",
			// Disabled per b/246818834.
			ExtraAttr: []string{},
			Val: loginPerfTestParam{
				browser.TypeLacros, lacros.Omaha, lacros.LacrosSideBySide,
			},
		}},
	})
}

// loginPerfStartToLoginScreen starts Chrome to the login screen.
func loginPerfStartToLoginScreen(ctx context.Context, s *testing.State, browserType browser.Type, lacrosConfig *lacrosfixt.Config, arcOpt []chrome.Option, useTabletMode bool) (cr *chrome.Chrome, retErr error) {
	// chrome.NoLogin() and chrome.KeepState() are needed to show the login
	// screen with a user pod (instead of the OOBE login screen).
	options := []chrome.Option{
		chrome.NoLogin(),
		chrome.KeepState(),
		chrome.LoadSigninProfileExtension(s.RequiredVar("ui.signinProfileTestExtensionManifestKey")),
		chrome.EnableFeatures("FullRestore"),
		chrome.EnableRestoreTabs(),
		chrome.SkipForceOnlineSignInForTesting(),
		chrome.EnableWebAppInstall(),
		chrome.HideCrashRestoreBubble(), // Ignore possible incomplete shutdown.
		// Disable whats-new page. See crbug.com/1271436.
		chrome.DisableFeatures("ChromeWhatsNewUI"),
	}
	if browserType == browser.TypeLacros {
		defaultOpts, err := lacrosConfig.Opts()
		if err != nil {
			return nil, errors.Wrap(err, "failed to get default options")
		}
		options = append(options, defaultOpts...)
	} else {
		// For Ash we need to force session restore in another way.
		options = append(options, chrome.ForceLaunchBrowser())
	}
	cr, err := chrome.New(
		ctx,
		append(options, arcOpt...)...,
	)
	if err != nil {
		return nil, errors.Wrap(err, "failed to start chrome")
	}
	defer func() {
		if retErr != nil {
			cr.Close(ctx)
		}
	}()

	tLoginConn, err := cr.SigninProfileTestAPIConn(ctx)
	if err != nil {
		return nil, errors.Wrap(err, "creating login test api connection failed")
	}
	defer faillog.DumpUITreeOnError(ctx, s.OutDir(), func() bool { return retErr != nil }, tLoginConn)

	if err = ash.SetTabletModeEnabled(ctx, tLoginConn, useTabletMode); err != nil {
		return nil, errors.Wrapf(err, "failed to set tablet mode %v", useTabletMode)
	}

	// Wait for the login screen to be ready for password entry.
	if st, err := lockscreen.WaitState(
		ctx,
		tLoginConn,
		func(st lockscreen.State) bool { return st.ReadyForPassword },
		30*time.Second); err != nil {
		return nil, errors.Wrapf(err, "failed waiting for the login screen to be ready for password entry: last state: %+v", st)
	}

	return cr, nil
}

// loginPerfDoLogin logs in and waits for animations to finish.
func loginPerfDoLogin(ctx context.Context, cr *chrome.Chrome, credentials chrome.Creds, browserType browser.Type) (retL *lacros.Lacros, lacrosConnectTime *time.Duration, retErr error) {
	outdir, ok := testing.ContextOutDir(ctx)
	if !ok {
		return nil, nil, errors.New("no output directory exists")
	}
	tLoginConn, err := cr.SigninProfileTestAPIConn(ctx)
	if err != nil {
		return nil, nil, errors.Wrap(err, "creating login test API connection failed")
	}
	defer faillog.DumpUITreeOnError(ctx, outdir, func() bool { return retErr != nil }, tLoginConn)

	// TODO(crbug/1109381): the password field isn't actually ready just yet when WaitState returns.
	// This causes it to miss some of the keyboard input, so the password will be wrong.
	// We can check in the UI for the password field to exist, which seems to be a good enough indicator that
	// the field is ready for keyboard input.
	if err := lockscreen.WaitForPasswordField(ctx, tLoginConn, credentials.User, 15*time.Second); err != nil {
		return nil, nil, errors.Wrap(err, "password text field did not appear in the ui")
	}

	kb, err := input.Keyboard(ctx)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to get keyboard")
	}
	defer kb.Close()

	if err := kb.Type(ctx, credentials.Pass+"\n"); err != nil {
		return nil, nil, errors.Wrap(err, "entering password failed")
	}

	// Check if the login was successful using the API and also by looking for the shelf in the UI.
	if st, err := lockscreen.WaitState(ctx, tLoginConn, func(st lockscreen.State) bool { return st.LoggedIn }, 30*time.Second); err != nil {
		return nil, nil, errors.Wrapf(err, "failed waiting to log in: last state: %+v", st)
	}

	if err := ash.WaitForShelf(ctx, tLoginConn, 120*time.Second); err != nil {
		return nil, nil, errors.Wrap(err, "shelf did not appear after logging in")
	}

	if browserType == browser.TypeLacros {
		tconn, err := cr.TestAPIConn(ctx)
		if err != nil {
			return nil, nil, errors.Wrap(err, "failed to connect to test api")
		}
		startTime := time.Now()
		// lacros.Connect() fails if DevTools connection file was already created, but Chrome does not accept connections.
		// Retry for 20 seconds.
		for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); {
			retL, err = lacros.Connect(ctx, tconn)
			if err == nil {
				duration := time.Since(startTime)
				lacrosConnectTime = &duration
				testing.ContextLogf(ctx, "loginPerfDoLogin: Connecting to lacros took %s", duration.Round(time.Millisecond))
				return retL, lacrosConnectTime, err
			}
			testing.ContextLog(ctx, "loginPerfDoLogin: Connect to lacros failed. Sleeping for 10 milliseconds before retry")
			if err := testing.Sleep(ctx, 10*time.Millisecond); err != nil {
				return nil, nil, errors.Wrap(err, "failed to wait for lacros-chrome test connection")
			}
		}
		return nil, nil, errors.Wrap(err, "timed out retrying connection to Lacros")
	}
	return nil, nil, nil
}

func loginPerfCreateWindows(ctx context.Context, cr *chrome.Chrome, l *lacros.Lacros, url string, n int) error {
	if l != nil {
		for i := 0; i < n; i++ {
			conn, err := l.NewConn(ctx, url, browser.WithNewWindow())
			if err != nil {
				return errors.Wrapf(err, "(%d) failed to connect to the %q restore URL", i, url)
			}
			defer conn.Close()
		}
	} else {
		tconn, err := cr.TestAPIConn(ctx)
		if err != nil {
			return errors.Wrap(err, "failed to connect to Ash test api")
		}
		if err := ash.CreateWindows(ctx, tconn, cr, url, n); err != nil {
			return errors.Wrap(err, "failed to create browser windows")
		}
	}
	return nil
}

// countVisibleWindows is a proxy to ash.CountVisibleWindows(...)
func countVisibleWindows(ctx context.Context, cr *chrome.Chrome) (int, error) {
	tconn, err := cr.TestAPIConn(ctx)
	if err != nil {
		return 0, errors.Wrap(err, "failed to connect to Ash test api")
	}
	visible, err := ash.CountVisibleWindows(ctx, tconn)
	if err != nil {
		err = errors.Wrap(err, "failed to count browser windows")
	}
	return visible, nil
}

// maxHistogramValue calculates the estimated maximum of the histogram values.
// At is an error when there are no data points.
func maxHistogramValue(h *metrics.Histogram) (float64, error) {
	if h.TotalCount() == 0 {
		return 0, errors.New("no histogram data")
	}
	var max int64 = math.MinInt64
	for _, b := range h.Buckets {
		if b.Count > 0 && max < b.Max {
			max = b.Max
		}
	}
	return float64(max), nil
}

func reportMaxHistogramValue(ctx context.Context, pv *perfutil.Values, hist *metrics.Histogram, unit, valueName string) error {
	value, err := maxHistogramValue(hist)
	if err != nil {
		return errors.Wrapf(err, "failed to get %s data", hist.Name)
	}
	pv.Append(perf.Metric{
		Name:      valueName,
		Unit:      unit,
		Direction: perf.SmallerIsBetter,
	}, value)
	return nil
}

// logout is a proxy to chrome.autotestPrivate.logout
func logout(ctx context.Context, cr *chrome.Chrome, l *lacros.Lacros) error {
	testing.ContextLog(ctx, "Sign out: started")
	tconn, err := cr.TestAPIConn(ctx)
	if err != nil {
		return errors.Wrap(err, "failed to connect to test api")
	}
	sm, err := session.NewSessionManager(ctx)
	if err != nil {
		return err
	}
	sw, err := sm.WatchSessionStateChanged(ctx, "stopped")
	if err != nil {
		return errors.Wrap(err, "failed to watch for D-Bus signals")
	}
	defer sw.Close(ctx)

	if l != nil {
		// TODO(crbug.com/1318180): at the moment for Lacros, we're not
		// getting SetUpWithNewChrome close closure because when used
		// it'd close all resources including targets and wouldn't let
		// the session to properly restore later during
		// performRegularLogin. As a short term workaround we're
		// closing Lacros resources using CloseResources fn instead,
		// though ideally we want to use SetUpWithNewChrome close
		// closure when it's properly implemented.
		l.CloseResources(ctx)
	}

	if err := tconn.Call(ctx, nil, "chrome.autotestPrivate.logout"); err != nil {
		if errors.Is(err, rpcc.ErrConnClosing) {
			testing.ContextLog(ctx, "WARNING: chrome.autotestPrivate.logout failed with: ", err)
		} else {
			return errors.Wrap(err, "failed to run chrome.autotestPrivate.logout()")
		}
	}

	select {
	case <-sw.Signals:
		testing.ContextLog(ctx, "Got SessionStateChanged signal")
	case <-ctx.Done():
		return errors.Wrap(ctx.Err(), "didn't get SessionStateChanged signal")
	}
	testing.ContextLog(ctx, "Sign out: done")
	return nil
}

// setAlwaysRestoreSettings opens OS settings and sets the 'Always restore' setting. In order to
// avoid possible noise when collecting the browser login time performance at restoring time, this
// function also makes sure to close the OS settings app before returning.
func setAlwaysRestoreSettings(ctx context.Context, tconn *chrome.TestConn) error {
	settings, err := ossettings.LaunchAtPage(ctx, tconn, nodewith.Name("Apps").Role(role.Link))
	if err != nil {
		return errors.Wrap(err, "failed to launch apps settings page")
	}

	if err := uiauto.Combine(`set "Always restore" Settings`,
		uiauto.New(tconn).LeftClick(nodewith.Name("Restore apps on startup").Role(role.ComboBoxSelect)),
		uiauto.New(tconn).LeftClick(nodewith.Name("Always restore").Role(role.ListBoxOption)))(ctx); err != nil {
		return err
	}
	if err := settings.Close(ctx); err != nil {
		return err
	}

	// TODO(crbug.com/1314785)
	// According to the PRD of Full Restore go/chrome-os-full-restore-dd,
	// it uses a throttle of 2.5s to save the app launching and window
	// state information to the backend. Therefore, sleep 3 seconds here.
	return testing.Sleep(ctx, 3*time.Second)
}

// initializeLoginPerfTest initializes user session state that will be restored
// in subsequent test runs.
func initializeLoginPerfTest(ctx context.Context, browserType browser.Type, lacrosConfig *lacrosfixt.Config, loginPool string) (chrome.Creds, error) {
	options := []chrome.Option{
		chrome.GAIALoginPool(loginPool),
		chrome.EnableRestoreTabs(),
		chrome.SkipForceOnlineSignInForTesting(),
		chrome.EnableWebAppInstall(),
		// Disable whats-new page. See crbug.com/1271436.
		chrome.DisableFeatures("ChromeWhatsNewUI"),
	}
	// Only enable arc if it's supported.
	if arc.Supported() {
		// We enable ARC initially to fully initialize it.
		options = append(options, chrome.ARCSupported())
	}
	if browserType == browser.TypeLacros {
		defaultOpts, err := lacrosConfig.Opts()
		if err != nil {
			return chrome.Creds{}, errors.Wrap(err, "failed to get default options")
		}
		options = append(options, defaultOpts...)
	}
	cr, err := chrome.New(ctx, options...)
	if err != nil {
		return chrome.Creds{}, errors.Wrap(err, "chrome login failed")
	}
	defer cr.Close(ctx)

	creds := cr.Creds()

	testing.ContextLog(ctx, "Opting into Play Store")
	tconn, err := cr.TestAPIConn(ctx)
	if err != nil {
		return chrome.Creds{}, errors.Wrap(err, "failed to connect to test api")
	}
	if arc.Supported() {
		if err := optin.Perform(ctx, cr, tconn); err != nil {
			return chrome.Creds{}, errors.Wrap(err, "failed to optin to Play Store")
		}
		testing.ContextLog(ctx, "Optin finished")
	} else {
		testing.ContextLog(ctx, "ARC++ is not supported. Running test without ARC")
	}

	var l *lacros.Lacros
	if browserType == browser.TypeLacros {
		var err error
		l, err = lacros.Launch(ctx, tconn)
		if err != nil {
			return chrome.Creds{}, errors.Wrap(err, "failed to launch lacros-chrome")
		}
	}

	// Wait for ARC++ aps to download and initialize.
	if arc.Supported() {
		testing.ContextLog(ctx, "Initialize: let session fully initialize. Sleeping for 400 seconds... ")
		if err := testing.Sleep(ctx, 400*time.Second); err != nil {
			return chrome.Creds{}, errors.Wrap(err, "failed to wait for arc to initialize")
		}
	} else {
		testing.ContextLog(ctx, "Initialiize: let session fully initialize. Sleeping for 100 seconds... ")
		if err := testing.Sleep(ctx, 100*time.Second); err != nil {
			return chrome.Creds{}, errors.Wrap(err, "failed to wait for session to initialize")
		}
	}
	if err := setAlwaysRestoreSettings(ctx, tconn); err != nil {
		return chrome.Creds{}, errors.Wrap(err, "failed to adjust always restore settings")
	}
	return creds, logout(ctx, cr, l)
}

func LoginPerf(ctx context.Context, s *testing.State) {
	param := s.Param().(loginPerfTestParam)
	lacrosCfg := lacrosfixt.NewConfig(
		lacrosfixt.Selection(param.lacrosSelection),
		lacrosfixt.Mode(param.lacrosMode))

	// Log in and log out to create a user pod on the login screen.
	creds, err := initializeLoginPerfTest(ctx, param.bt, lacrosCfg, s.RequiredVar("ui.gaiaPoolDefault"))
	if err != nil {
		s.Fatal("Failed to initialize test: ", err)
	}

	r := perfutil.NewRunner(nil)
	// Use 3 runs instead of 10, to reduce tests time.
	r.Runs = 3
	// Run an http server to serve the test contents for accessing from the chrome browsers.
	server := httptest.NewServer(http.FileServer(s.DataFileSystem()))
	defer server.Close()

	url := server.URL + "/animation.html"

	const (
		noarc        = "noarc"
		arcenabled   = "arcenabled"
		arcsupported = "arcsupported"
	)
	arcmodes := []string{noarc}
	if arc.Supported() {
		arcmodes = append(arcmodes, arcenabled, arcsupported)
	}

	currentWindows := 0
	// Run the login flow for various situations.
	// - change the number of browser windows, 2 or 8
	// - the window system status; clamshell mode or tablet mode.
	for _, windows := range []int{2, 8} {
		for _, arcMode := range arcmodes {
			var arcOpt []chrome.Option
			switch arcMode {
			case noarc:
			case arcenabled:
				arcOpt = []chrome.Option{chrome.ARCEnabled()}
			case arcsupported:
				arcOpt = []chrome.Option{chrome.ARCSupported()}
			default:
				s.Fatal("Unknown arcMode value=", arcMode)
			}
			s.Log("Starting test: '"+arcMode+"' for ", windows, " windows")

			if currentWindows != windows {
				s.Log("CREATE NEW WINDOWS: Sign in to create new windows")
				// Log in and log out to create a user pod on the login screen and required number of windows in session.
				err := func() error {
					// We do not need ARC to create Chrome windows.
					cr, err := loginPerfStartToLoginScreen(ctx, s, param.bt, lacrosCfg, []chrome.Option{} /*arcOpt*/, false /*useTabletMode*/)
					if err != nil {
						return err
					}
					defer cr.Close(ctx)

					l, _, err := loginPerfDoLogin(ctx, cr, creds, param.bt)
					if err != nil {
						return err
					}
					// Wait for windows to be restored
					var visible int
					if err := testing.Poll(ctx, func(ctx context.Context) error {
						var err error
						if visible, err = countVisibleWindows(ctx, cr); err != nil {
							return testing.PollBreak(err)
						}
						if visible != currentWindows && visible != currentWindows+1 {
							return errors.Errorf("unexpected number of visible windows: expected %d, found %d", currentWindows, visible)
						}
						return nil
					}, &testing.PollOptions{Timeout: 10 * time.Second, Interval: 10 * time.Millisecond}); err != nil {
						return errors.Wrap(err, "failed to check number of existing windows before creating new ones")
					}
					s.Logf("Before creating windows: visible=%d", visible)
					if err := loginPerfCreateWindows(ctx, cr, l, url, windows-currentWindows); err != nil {
						return err
					}
					s.Log("Sign out: sleep for 20 seconds to let session settle")
					testing.Sleep(ctx, 20*time.Second)
					return logout(ctx, cr, l)
				}()
				if err != nil {
					s.Fatal("Failed to create new browser windows: ", err)
				}
				currentWindows = windows
			}

			for _, inTabletMode := range []bool{false, true} {
				var suffix string
				if inTabletMode {
					suffix = ".TabletMode"
				} else {
					suffix = ".ClamshellMode"
				}

				// |cr| and |l| are shared between multiple
				// runs, because Chrome connection must to be
				// closed only after histograms are stored.
				var cr *chrome.Chrome
				var l *lacros.Lacros

				heuristicsHistograms := []string{
					"Ash.LoginAnimation.Smoothness" + suffix,
					"Ash.LoginAnimation.Jank" + suffix,
					"Ash.LoginAnimation.Duration" + suffix,
				}
				const (
					ensureWorkVisibleHistogram       = "GPU.EnsureWorkVisibleDuration"
					ensureWorkVisibleLowResHistogram = "GPU.EnsureWorkVisibleDurationLowRes"
					allBrowserWindowsCreated         = "Ash.LoginSessionRestore.AllBrowserWindowsCreated"
					allBrowserWindowsShown           = "Ash.LoginSessionRestore.AllBrowserWindowsShown"
					allBrowserWindowsPresented       = "Ash.LoginSessionRestore.AllBrowserWindowsPresented"
					allShelfIconsLoaded              = "Ash.LoginSessionRestore.AllShelfIconsLoaded"
					shelfLoginAnimationEnd           = "Ash.LoginSessionRestore.ShelfLoginAnimationEnd"
					ashTastBootTimeLogin2            = "Ash.Tast.BootTime.Login2"
				)

				allHistograms := []string{
					ensureWorkVisibleHistogram,
					ensureWorkVisibleLowResHistogram,
					allBrowserWindowsCreated,
					allBrowserWindowsShown,
					allBrowserWindowsPresented,
					allShelfIconsLoaded,
					shelfLoginAnimationEnd,
					ashTastBootTimeLogin2,
				}
				allHistograms = append(allHistograms, heuristicsHistograms...)

				testName := fmt.Sprintf("%s%s.%s.%dwindows", s.TestName(), suffix, arcMode, currentWindows)
				s.Logf("Starting test: %q", testName)
				if err := r.RunMultiple(ctx, testName,
					uiperf.Run(s, func(ctx context.Context, name string) ([]*metrics.Histogram, error) {
						var err error
						cr, err = loginPerfStartToLoginScreen(ctx, s, param.bt, lacrosCfg, arcOpt, inTabletMode)
						if err != nil {
							return nil, errors.Wrap(err, "failed to start to login screen")
						}
						tLoginConn, err := cr.SigninProfileTestAPIConn(ctx)
						if err != nil {
							return nil, errors.Wrap(err, "creating login test api connection failed")
						}
						// Shorten context a bit to allow for cleanup.
						closeCtx := ctx
						ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second)
						defer cancel()
						// Initialize CUJ recording.
						cujRecorder, err := cujrecorder.NewRecorderWithTestConn(ctx, tLoginConn, cr, tLoginConn, nil, cujrecorder.RecorderOptions{})
						if err != nil {
							s.Fatal("Failed to create a CUJ recorder: ", err)
						}
						defer cujRecorder.Close(closeCtx)
						// TODO(b/237400719): support lacros
						for _, metricConfig := range [][]cujrecorder.MetricConfig{cujrecorder.AshCommonMetricConfigs(), cujrecorder.BrowserCommonMetricConfigs(), cujrecorder.AnyChromeCommonMetricConfigs()} {
							if err := cujRecorder.AddCollectedMetrics(tLoginConn, browser.TypeAsh, metricConfig...); err != nil {
								s.Fatal("Failed to add recorded metrics: ", err)
							}
						}

						var lacrosConnectTime *time.Duration

						// The actual test function
						testFunc := func(ctx context.Context) error {
							var err error
							l, lacrosConnectTime, err = loginPerfDoLogin(ctx, cr, creds, param.bt)
							if err != nil {
								return errors.Wrap(err, "failed to log in")
							}
							tconn, err := cr.TestAPIConn(ctx)
							if err != nil {
								return errors.Wrap(err, "failed to connect to test api")
							}
							if err = ash.ForEachWindow(ctx, tconn, func(w *ash.Window) error {
								return ash.WaitWindowFinishAnimating(ctx, tconn, w.ID)
							}); err != nil {
								return errors.Wrap(err, "failed to wait")
							}
							return nil
						}

						var histograms []*metrics.Histogram
						// CUJ TPS metrics recording wrapper
						cujFunc := func(ctx context.Context) error {
							var err error
							histograms, err = metrics.RunAndWaitAll(
								ctx,
								tLoginConn,
								4*time.Minute,
								testFunc,
								allHistograms...,
							)
							if err != nil {
								return err
							}
							visible := 0
							if visible, err = countVisibleWindows(ctx, cr); err != nil {
								return err
							}
							if visible != currentWindows && visible != currentWindows+1 {
								err = errors.Errorf("unexpected number of visible windows: expected %d, found %d", currentWindows, visible)
							}
							return err
						}
						if err := cujRecorder.Run(ctx, cujFunc); err != nil {
							return nil, errors.Wrap(err, "failed to run the test scenario")
						}
						tpsValues := perf.NewValues()
						if err := cujRecorder.Record(ctx, tpsValues); err != nil {
							return nil, errors.Wrap(err, "failed to collect the data from the recorder")
						}
						if lacrosConnectTime != nil {
							tpsValues.Set(perf.Metric{
								Name:      "Ash.Tast.LacrosConnectTime",
								Unit:      "millisecond",
								Direction: perf.SmallerIsBetter,
							}, float64(lacrosConnectTime.Milliseconds()))
						}
						r.Values().MergeWithSuffix(fmt.Sprintf("%s.%s.%dwindows", suffix, arcMode, currentWindows), tpsValues.GetValues())
						return histograms, err
					}),
					func(ctx context.Context, pv *perfutil.Values, hists []*metrics.Histogram) error {
						defer cr.Close(ctx)

						heuristicsHistogramsMap := make(map[string]bool, len(allHistograms))
						for _, v := range heuristicsHistograms {
							heuristicsHistogramsMap[v] = true
						}
						storeHeuristicsHistograms := perfutil.StoreAllWithHeuristics(fmt.Sprintf("%s.%dwindows", arcMode, currentWindows))
						for _, hist := range hists {
							if heuristicsHistogramsMap[hist.Name] {
								storeHeuristicsHistograms(ctx, pv, []*metrics.Histogram{hist})
								continue
							}
							valueName := fmt.Sprintf("%s%s.%s.%dwindows", hist.Name, suffix, arcMode, currentWindows)
							switch hist.Name {
							case ensureWorkVisibleHistogram:
								reportMaxHistogramValue(ctx, pv, hist, "microsecond", valueName)
							case allBrowserWindowsCreated,
								allBrowserWindowsPresented,
								allBrowserWindowsShown,
								allShelfIconsLoaded,
								ashTastBootTimeLogin2,
								ensureWorkVisibleLowResHistogram,
								shelfLoginAnimationEnd:

								reportMaxHistogramValue(ctx, pv, hist, "millisecond", valueName)
							default:
								return errors.Errorf("unknown histogram %q", hist.Name)
							}
						}
						return logout(ctx, cr, l)
					},
				); err != nil {
					s.Fatalf("Failed to run test scenario %s: %s", testName, err)
				}
			}
		}
	}
	if err := r.Values().Save(ctx, s.OutDir()); err != nil {
		s.Error("Failed saving perf data: ", err)
	}
}


text:
SUMMARY = "Rockchip WIFI/BT firmware files"
SECTION = "kernel"

LICENSE = "LICENSE.rockchip"
LIC_FILES_CHKSUM = "file://${DEALCOREBASE}/licenses/LICENSE.rockchip;md5=d63890e209bf038f44e708bbb13e4ed9"

SRC_URI = "git://${EXTRA}/rkwifibt;protocol=file;usehead=1"
SRCREV = "${AUTOREV}"
S = "${WORKDIR}/git"

inherit allarch deploy

do_install() {
	install -d ${D}/system/etc/firmware/
	install -m 0644 ${S}/firmware/broadcom/all/*/* \
		-t ${D}/system/etc/firmware/
	install -d ${D}/lib/firmware/rtlbt/
	install -m 0644 ${S}/realtek/RTL*/* -t ${D}/lib/firmware/rtlbt/
}

PACKAGES =+ " \
	${PN}-ap6181-wifi \
	${PN}-ap6212a1-wifi \
	${PN}-ap6212a1-bt \
	${PN}-ap6236-wifi \
	${PN}-ap6236-bt \
	${PN}-ap6255-wifi \
	${PN}-ap6255-bt \
	${PN}-ap6354-wifi \
	${PN}-ap6354-bt \
	${PN}-ap6356-wifi \
	${PN}-ap6356-bt \
	${PN}-ap6398s-wifi \
	${PN}-ap6398s-bt \
	${PN}-rtl8723ds-bt \
"

FILES_${PN}-ap6181-wifi = " \
	system/etc/firmware/fw_bcm40181a2_apsta.bin \
	system/etc/firmware/fw_bcm40181a2.bin \
	system/etc/firmware/nvram_ap6181.txt \
"

FILES_${PN}-ap6212a1-wifi = " \
	system/etc/firmware/fw_bcm43438a1_apsta.bin \
	system/etc/firmware/fw_bcm43438a1.bin \
	system/etc/firmware/nvram_ap6212a.txt \
"
FILES_${PN}-ap6212a1-bt = " \
	system/etc/firmware/BCM43430A1.hcd \
"

FILES_${PN}-ap6236-wifi = " \
	system/etc/firmware/fw_bcm43436b0_apsta.bin \
	system/etc/firmware/fw_bcm43436b0.bin \
	system/etc/firmware/nvram_ap6236.txt \
"
FILES_${PN}-ap6236-bt = " \
	system/etc/firmware/BCM43430B0.hcd \
"

FILES_${PN}-ap6255-wifi = " \
	system/etc/firmware/fw_bcm43455c0_ag.bin \
	system/etc/firmware/nvram_ap6255.txt \
"
FILES_${PN}-ap6255-bt = " \
	system/etc/firmware/BCM4345C0_ap.hcd \
	system/etc/firmware/BCM4345C0.hcd \
"

FILES_${PN}-ap6354-wifi = " \
	system/etc/firmware/fw_bcm4354a1_ag.bin \
	system/etc/firmware/nvram_ap6354.txt \
"
FILES_${PN}-ap6354-bt = " \
	system/etc/firmware/BCM4350C0.hcd \
"

FILES_${PN}-ap6356-wifi = " \
	system/etc/firmware/fw_bcm4356a2_ag.bin \
	system/etc/firmware/nvram_ap6356.txt \
	system/etc/firmware/nvram_ap6356s.txt \
"
FILES_${PN}-ap6356-bt = " \
	system/etc/firmware/BCM4354A2.hcd \
"

FILES_${PN}-ap6398s-wifi = " \
	system/etc/firmware/fw_bcm4359c0_ag.bin \
	system/etc/firmware/fw_bcm4359c0_ag_mfg.bin \
	system/etc/firmware/nvram_ap6398s.txt \
"
FILES_${PN}-ap6398s-bt = " \
	system/etc/firmware/BCM4359C0.hcd \
"

FILES_${PN}-rtl8723ds-bt = " \
	lib/firmware/rtlbt/rtl8723d_config \
	lib/firmware/rtlbt/rtl8723d_fw \
"

FILES_${PN} = "*"

# Make it depend on all of the split-out packages.
python () {
    pn = d.getVar('PN')
    firmware_pkgs = oe.utils.packages_filter_out_system(d)
    d.appendVar('RDEPENDS_' + pn, ' ' + ' '.join(firmware_pkgs))
}

INSANE_SKIP_${PN} += "arch"

repository: ponmadasamy/meta-dealcore

repo_name: ponmadasamy/meta-dealcore