text:
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
  "ASM"
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_ASM
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux_mips64.S" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_linux_mips64.S.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux_x86_64.S" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_linux_x86_64.S.o"
  )
set(CMAKE_ASM_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS_ASM
  "HAVE_RPC_XDR_H=1"
  "HAVE_TIRPC_RPC_XDR_H=0"
  "LLVM_BUILD_GLOBAL_ISEL"
  "_GNU_SOURCE"
  "__STDC_CONSTANT_MACROS"
  "__STDC_FORMAT_MACROS"
  "__STDC_LIMIT_MACROS"
  )

# The include file search paths:
set(CMAKE_ASM_TARGET_INCLUDE_PATH
  "projects/compiler-rt/lib/sanitizer_common"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common"
  "include"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/include"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/.."
  )
set(CMAKE_DEPENDS_CHECK_CXX
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_allocator.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_common.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_common.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector1.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_deadlock_detector1.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector2.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_deadlock_detector2.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_errno.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_errno.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_flag_parser.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_flags.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_flags.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_libc.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_libc.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_libignore.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_libignore.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_linux.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux_s390.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_linux_s390.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_mac.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_mac.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_persistent_allocator.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_linux.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_platform_limits_linux.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_platform_limits_posix.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_posix.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_posix.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_printf.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_printf.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_common.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_procmaps_common.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_freebsd.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_procmaps_freebsd.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_procmaps_linux.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_procmaps_mac.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_stackdepot.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_stackdepot.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_stacktrace.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_printer.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_stacktrace_printer.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_stoptheworld_mac.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_suppressions.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_symbolizer.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libbacktrace.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_symbolizer_libbacktrace.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_mac.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_symbolizer_mac.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_win.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_symbolizer_win.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_termination.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_termination.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_thread_registry.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_thread_registry.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_tls_get_addr.cc.o"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_win.cc" "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/llvmbuild/projects/compiler-rt/lib/sanitizer_common/CMakeFiles/RTSanitizerCommon.x86_64.dir/sanitizer_win.cc.o"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS_CXX
  "HAVE_RPC_XDR_H=1"
  "HAVE_TIRPC_RPC_XDR_H=0"
  "LLVM_BUILD_GLOBAL_ISEL"
  "_GNU_SOURCE"
  "__STDC_CONSTANT_MACROS"
  "__STDC_FORMAT_MACROS"
  "__STDC_LIMIT_MACROS"
  )

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  "projects/compiler-rt/lib/sanitizer_common"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common"
  "include"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/include"
  "/home/vitowu/Documents/CourseMaterials/CourseMaterials/2018-2019_Term2/CS143-Compilers/testCompiler/llvm/projects/compiler-rt/lib/sanitizer_common/.."
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")

extension: cmake


text:
package cmdhelper

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/jedib0t/go-pretty/table"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/thoas/go-funk"
)

const DefaultGroupName = ""
const globalGroupName = "Global"

type group struct {
	name  string
	flags []string
}

type CmdHelper struct {
	root  *cobra.Command
	group []*group
}

// NewCmdHelper creates an instance of CmdHelper
func NewCmdHelper(root *cobra.Command) *CmdHelper {
	return &CmdHelper{root: root, group: []*group{}}
}

// getFlagGroup returns the group of a flag
func (c *CmdHelper) getFlagGroup(flagName string) *group {
	for _, g := range c.group {
		if funk.ContainsString(g.flags, flagName) {
			return g
		}
	}
	return nil
}

func (c *CmdHelper) findGroup(name string) *group {
	for _, g := range c.group {
		if g.name == name {
			return g
		}
	}
	return nil
}

func (c *CmdHelper) addToGroup(groupName, flagName string) {
	grp := c.findGroup(groupName)
	if grp == nil {
		c.group = append(c.group, &group{name: groupName, flags: []string{flagName}})
		return
	}
	grp.flags = append(grp.flags, flagName)
	grp.flags = funk.UniqString(grp.flags)
}

// Grp register a flag to a group
func (c *CmdHelper) Grp(name, flagName string) *cobra.Command {
	c.addToGroup(name, flagName)
	return c.root
}

// Render generates a help message
func (c *CmdHelper) Render() *bytes.Buffer {

	out := bytes.NewBuffer(nil)

	// Command Description
	if c.root.Long != "" {
		out.WriteString(fmt.Sprintf("%s\n\n", c.root.Long))
	} else {
		out.WriteString(fmt.Sprintf("%s\n\n", c.root.Short))
	}

	// Command (and sub-command) Usage
	render(out, func(t table.Writer) {
		out.WriteString(fmt.Sprintf("Usage:\n"))
		t.SetColumnConfigs([]table.ColumnConfig{{Number: 1, WidthMin: 1}})
		var usages = []string{c.root.Use}
		for _, cmd := range c.root.Commands() {
			if !funk.ContainsString(usages, cmd.Use) {
				usages = append(usages, cmd.Use)
			}
		}
		for _, usage := range usages {
			var row []interface{}
			funk.ConvertSlice(strings.Split(usage, " "), &row)
			t.AppendRow(row)
		}
	})

	// Available Sub-commands
	render(out, func(t table.Writer) {
		out.WriteString(fmt.Sprintf("\nAvailable Commands:\n"))
		t.SetColumnConfigs([]table.ColumnConfig{{Number: 1, WidthMin: 8}})
		for _, cmd := range c.root.Commands() {
			var row = []interface{}{cmd.Name(), cmd.Short}
			t.AppendRow(row)
		}
	})

	// Add flags with no group to the default group
	c.root.Flags().VisitAll(func(flag *pflag.Flag) {
		if c.getFlagGroup(flag.Name) == nil {
			c.addToGroup(DefaultGroupName, flag.Name)
		}
	})

	c.root.PersistentFlags().VisitAll(func(flag *pflag.Flag) {
		if c.getFlagGroup(flag.Name) == nil {
			c.addToGroup(globalGroupName, flag.Name)
		}
	})

	// Flags
	for _, group := range c.group {
		title := group.name + " "
		if group.name == DefaultGroupName {
			title = ""
		}

		out.WriteString(fmt.Sprintf("\n%sFlags:\n", title))
		render(out, func(t table.Writer) {
			var flags []*pflag.Flag
			for _, flagName := range group.flags {
				fs := c.root.Flags()
				if group.name == globalGroupName {
					fs = c.root.PersistentFlags()
				}
				if flag := fs.Lookup(flagName); flag != nil {
					flags = append(flags, flag)
				}
			}

			t.SetColumnConfigs([]table.ColumnConfig{{Number: 1, WidthMin: 28}})
			for _, flag := range flags {
				var short = "   "
				if flag.Shorthand != "" {
					short = "-" + flag.Shorthand + ","
				}
				defTxt := ""
				if flag.DefValue != "" {
					defTxt = fmt.Sprintf("(default: \"%s\")", flag.DefValue)
				}
				rowTxt := fmt.Sprintf("%s --%s %s", short, flag.Name, flag.Value.Type())
				var row = []interface{}{rowTxt, fmt.Sprintf("%s %s", flag.Usage, defTxt)}
				t.AppendRow(row)
			}
		})
	}

	out.WriteString(fmt.Sprintf("\nUse \"%s --help\" for more information about a command.", c.root.Use))

	return out
}

func render(out *bytes.Buffer, f func(t table.Writer)) {
	t := table.NewWriter()
	t.SetOutputMirror(out)
	t.Style().Options.DrawBorder = false
	t.Style().Options.SeparateColumns = false
	t.Style().Box.PaddingLeft = "  "
	f(t)
	t.Render()
}

repository: furkanefe-oss/kit

license_type: permissive

repo_name: furkanefe-oss/kit

branch_name: refs/heads/master

extension: go


text:
package main

import (
	"flag"
	"log"
	"net/http"
)

var (
	webBindAddr   string
	webDir        string
	redirBindAddr string
	redirURL      string
	pingURL       string
	allowFrom     IPNetList
)

func startRedirector() {
	s := &http.Server{
		Addr:    redirBindAddr,
		Handler: http.RedirectHandler(redirURL, http.StatusTemporaryRedirect),
	}
	log.Fatal(s.ListenAndServe())
}

func main() {
	var err error

	flag.StringVar(&webBindAddr, "web-bind", ":8080", "web bind address")
	flag.StringVar(&webDir, "web-root", "static", "web root directory")
	flag.StringVar(&redirBindAddr, "redir-bind", "", "redirector bind address")
	flag.StringVar(&redirURL, "redir-url", "", "redirector target URL")
	flag.StringVar(&pingURL, "ping-url", "", "ping API URL")
	allowFromStr := flag.String("allow-from", "", "limit permitted IPs")
	flag.Parse()

	err = allowFrom.ParseArg(*allowFromStr)
	if err != nil {
		log.Fatal(err)
	}

	if redirBindAddr != "" && redirURL != "" {
		go startRedirector()
	}

	http.HandleFunc("/ping.php", pingHandler)
	http.HandleFunc("/empty.php", emptyHandler)
	http.HandleFunc("/garbage.php", garbageHandler)

	fs := http.FileServer(http.Dir(webDir))
	http.Handle("/", fs)

	log.Fatal(http.ListenAndServe(webBindAddr, allowNetworkWrapper(http.DefaultServeMux)))
}

license: MIT

repository: andre-luiz-dos-santos/speedtest-go

repo_name: andre-luiz-dos-santos/speedtest-go


text:
/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2012 Sam Lantinga

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Sam Lantinga
    slouken@libsdl.org
*/
#include "SDL_config.h"

#include "CDPlayer.h"
#include "AudioFilePlayer.h"
#include "SDLOSXCAGuard.h"

/*///////////////////////////////////////////////////////////////////////////
    Constants
  //////////////////////////////////////////////////////////////////////////*/

#define kAudioCDFilesystemID (UInt16)(('J' << 8) | 'H') /* 'JH'; this avoids compiler warning */

/* XML PList keys */
#define kRawTOCDataString			"Format 0x02 TOC Data"
#define kSessionsString				"Sessions"
#define kSessionTypeString			"Session Type"
#define kTrackArrayString			"Track Array"
#define kFirstTrackInSessionString	"First Track"
#define kLastTrackInSessionString	"Last Track"
#define kLeadoutBlockString			"Leadout Block"
#define kDataKeyString				"Data"
#define kPointKeyString				"Point"
#define kSessionNumberKeyString		"Session Number"
#define kStartBlockKeyString		"Start Block"

/*///////////////////////////////////////////////////////////////////////////
    Globals
  //////////////////////////////////////////////////////////////////////////*/

#pragma mark -- Globals --

static int						playBackWasInit = 0;
static AudioUnit				theUnit;
static AudioFilePlayer*			thePlayer = NULL;
static CDPlayerCompletionProc	completionProc = NULL;
static SDL_mutex				*apiMutex = NULL;
static SDL_sem					*callbackSem;
static SDL2_CD*					theCDROM;

/*///////////////////////////////////////////////////////////////////////////
    Prototypes
  //////////////////////////////////////////////////////////////////////////*/

#pragma mark -- Prototypes --

static OSStatus	CheckInit();
static void		FilePlayNotificationHandler(void* inRefCon, OSStatus inStatus);
static int		RunCallBackThread(void* inRefCon);

#pragma mark -- Public Functions --

void Lock()
{
    if (!apiMutex) {
        apiMutex = SDL_CreateMutex();
    }
    SDL_LockMutex(apiMutex);
}

void Unlock()
{
    SDL_UnlockMutex(apiMutex);
}

int DetectAudioCDVolumes(FSVolumeRefNum *volumes, int numVolumes)
{
    int volumeIndex;
    int cdVolumeCount = 0;
    OSStatus result = noErr;

    for (volumeIndex = 1; result == noErr || result != nsvErr; volumeIndex++)
    {
        FSVolumeRefNum  actualVolume;
        FSVolumeInfo    volumeInfo;

        memset (&volumeInfo, 0, sizeof(volumeInfo));

        result = FSGetVolumeInfo(kFSInvalidVolumeRefNum,
                                  volumeIndex,
                                  &actualVolume,
                                  kFSVolInfoFSInfo,
                                  &volumeInfo,
                                  NULL,
                                  NULL);

        if (result == noErr)
        {
            if (volumeInfo.filesystemID == kAudioCDFilesystemID) /* It's an audio CD */
            {
                if (volumes != NULL && cdVolumeCount < numVolumes)
                    volumes[cdVolumeCount] = actualVolume;

                cdVolumeCount++;
            }
        }
        else
        {
            /* I'm commenting this out because it seems to be harmless */
            /*SDL_SetError ("DetectAudioCDVolumes: FSGetVolumeInfo returned %d", result);*/
        }
    }

    return cdVolumeCount;
}

int ReadTOCData(FSVolumeRefNum theVolume, SDL2_CD *theCD)
{
    OSStatus			theErr;
    CFURLRef            rootURL = NULL;
    CFURLRef            tocURL = NULL;
    CFMutableDataRef    mutDataRef = NULL;
    CFPropertyListRef	propertyListRef = 0;
    FSRef				rootRef;
    CFReadStreamRef     readStream;
    CFStreamStatus      streamStatus;
    UInt8               *data;
    const char* error = "Unspecified Error";

    theErr = FSGetVolumeInfo(theVolume, 0, 0, kFSVolInfoNone, 0, 0, &rootRef);
    if(theErr != noErr) {
        error = "FSGetVolumeInfo";
        goto bail;
    }

    rootURL = CFURLCreateFromFSRef(kCFAllocatorDefault, &rootRef);
    if (!rootURL) {
        error = "CFURLCreateFromFSRef";
        goto bail;
    }

    /* get stuff from .TOC.plist */
    tocURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault, rootURL, CFSTR(".TOC.plist"), FALSE);
    CFRelease(rootURL); rootURL = NULL;
    if (!tocURL) {
        error = "CFURLCreateCopyAppendingPathComponent";
        goto bail;
    }

    /* Load and parse the TOC XML data */

    readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, tocURL);
    CFRelease(tocURL); tocURL = NULL;
    if (!tocURL) {
        error = "CFReadStreamCreateWithFile";
        goto bail;
    }

    CFReadStreamOpen(readStream);
    streamStatus = CFReadStreamGetStatus(readStream);
    if (streamStatus == kCFStreamStatusError) {
        CFRelease(readStream);
        theErr = (OSStatus)streamStatus;
        error = "CFReadStreamOpen";
        goto bail;
    } else if (streamStatus == kCFStreamStatusOpening) {
        while (streamStatus == kCFStreamStatusOpening) {
            usleep(500);
            streamStatus = CFReadStreamGetStatus(readStream);
        }
    }
    if (streamStatus != kCFStreamStatusOpen) {
        CFRelease(readStream);
        theErr = (OSStatus)streamStatus;
        error = "CFReadStreamOpen";
        goto bail;
    }

    /* Allocate some memory for the XML data */
    mutDataRef = CFDataCreateMutable(kCFAllocatorDefault, 2 * 1024 * 1024 /* 2 MiB, should be big enough */);
    if (!mutDataRef) {
        error = "CFDataCreateMutable";
        goto bail;
    }

    data = new UInt8[4096];
    do {
        CFIndex readBytes = CFReadStreamRead(readStream, data, 4096);
        CFDataAppendBytes(mutDataRef, data, readBytes);
    } while (CFReadStreamHasBytesAvailable(readStream));
    delete [] data;
    streamStatus = CFReadStreamGetStatus(readStream);
    CFRelease(readStream); readStream = NULL;
    if (streamStatus == kCFStreamStatusError) {
        theErr = (OSStatus)streamStatus;
        error = "CFReadStreamRead";
        goto bail;
    }

    propertyListRef = CFPropertyListCreateFromXMLData (kCFAllocatorDefault,
                                                       mutDataRef,
                                                       kCFPropertyListImmutable,
                                                       NULL);
    if (propertyListRef == NULL) {
        error = "CFPropertyListCreateFromXMLData";
        goto bail;
    }

    /* Now we got the Property List in memory. Parse it. */

    /* First, make sure the root item is a CFDictionary. If not, release and bail. */
    if (CFGetTypeID(propertyListRef)== CFDictionaryGetTypeID())
    {
        CFDictionaryRef dictRef = (CFDictionaryRef)propertyListRef;

        CFDataRef   theRawTOCDataRef;
        CFArrayRef  theSessionArrayRef;
        CFIndex     numSessions;
        CFIndex     index;

        /* This is how we get the Raw TOC Data */
        theRawTOCDataRef = (CFDataRef)CFDictionaryGetValue (dictRef, CFSTR(kRawTOCDataString));

        /* Get the session array info. */
        theSessionArrayRef = (CFArrayRef)CFDictionaryGetValue (dictRef, CFSTR(kSessionsString));

        /* Find out how many sessions there are. */
        numSessions = CFArrayGetCount (theSessionArrayRef);

        /* Initialize the total number of tracks to 0 */
        theCD->numtracks = 0;

        /* Iterate over all sessions, collecting the track data */
        for (index = 0; index < numSessions; index++) {
            CFDictionaryRef theSessionDict;
            CFNumberRef     leadoutBlock;
            CFArrayRef      trackArray;
            CFIndex         numTracks;
            CFIndex         trackIndex;
            UInt32          value = 0;

            theSessionDict      = (CFDictionaryRef) CFArrayGetValueAtIndex (theSessionArrayRef, index);
            leadoutBlock        = (CFNumberRef) CFDictionaryGetValue (theSessionDict, CFSTR(kLeadoutBlockString));

            trackArray = (CFArrayRef)CFDictionaryGetValue (theSessionDict, CFSTR(kTrackArrayString));

            numTracks = CFArrayGetCount (trackArray);

            for (trackIndex = 0; trackIndex < numTracks; trackIndex++) {
                CFDictionaryRef theTrackDict;
                CFNumberRef     trackNumber;
                CFNumberRef     sessionNumber;
                CFNumberRef     startBlock;
                CFBooleanRef    isDataTrack;
                UInt32          value;

                theTrackDict  = (CFDictionaryRef) CFArrayGetValueAtIndex (trackArray, trackIndex);

                trackNumber   = (CFNumberRef)  CFDictionaryGetValue(theTrackDict, CFSTR(kPointKeyString));
                sessionNumber = (CFNumberRef)  CFDictionaryGetValue(theTrackDict, CFSTR(kSessionNumberKeyString));
                startBlock    = (CFNumberRef)  CFDictionaryGetValue(theTrackDict, CFSTR(kStartBlockKeyString));
                isDataTrack   = (CFBooleanRef) CFDictionaryGetValue(theTrackDict, CFSTR(kDataKeyString));

                /* Fill in the SDL2_CD struct */
                int idx = theCD->numtracks++;

                CFNumberGetValue (trackNumber, kCFNumberSInt32Type, &value);
                theCD->track[idx].id = value;

                CFNumberGetValue (startBlock, kCFNumberSInt32Type, &value);
                theCD->track[idx].offset = value;

                theCD->track[idx].type = (isDataTrack == kCFBooleanTrue) ? SDL_DATA_TRACK : SDL_AUDIO_TRACK;

                /* Since the track lengths are not stored in .TOC.plist we compute them. */
                if (trackIndex > 0) {
                    theCD->track[idx-1].length = theCD->track[idx].offset - theCD->track[idx-1].offset;
                }
            }

            /* Compute the length of the last track */
            CFNumberGetValue (leadoutBlock, kCFNumberSInt32Type, &value);

            theCD->track[theCD->numtracks-1].length =
                value - theCD->track[theCD->numtracks-1].offset;

            /* Set offset to leadout track */
            theCD->track[theCD->numtracks].offset = value;
        }

    }

    theErr = 0;
    goto cleanup;
bail:
    SDL_SetError ("ReadTOCData: %s returned %d", error, theErr);
    theErr = -1;
cleanup:

    if (propertyListRef != NULL)
        CFRelease(propertyListRef);
    if (mutDataRef != NULL)
        CFRelease(mutDataRef);

    return theErr;
}

int ListTrackFiles (FSVolumeRefNum theVolume, FSRef *trackFiles, int numTracks)
{
    OSStatus        result = -1;
    FSIterator      iterator;
    ItemCount       actualObjects;
    FSRef           rootDirectory;
    FSRef           ref;
    HFSUniStr255    nameStr;

    result = FSGetVolumeInfo(theVolume,
							 0,
							 NULL,
							 kFSVolInfoFSInfo,
							 NULL,
							 NULL,
							 &rootDirectory);

    if (result != noErr) {
        SDL_SetError ("ListTrackFiles: FSGetVolumeInfo returned %d", result);
        return result;
    }

    result = FSOpenIterator (&rootDirectory, kFSIterateFlat, &iterator);
    if (result == noErr) {
        do {
            result = FSGetCatalogInfoBulk (iterator, 1, &actualObjects,
                                           NULL, kFSCatInfoNone, NULL, &ref, NULL, &nameStr);
            if (result == noErr) {

                CFStringRef  name;
                name = CFStringCreateWithCharacters (NULL, nameStr.unicode, nameStr.length);

                /* Look for .aiff extension */
                if (CFStringHasSuffix (name, CFSTR(".aiff")) ||
                    CFStringHasSuffix (name, CFSTR(".cdda"))) {

                    /* Extract the track id from the filename */
                    int trackID = 0, i = 0;
                    while (i < nameStr.length && !isdigit(nameStr.unicode[i])) {
                        ++i;
                    }
                    while (i < nameStr.length && isdigit(nameStr.unicode[i])) {
                        trackID = 10 * trackID +(nameStr.unicode[i] - '0');
                        ++i;
                    }

#if DEBUG_CDROM
                    printf("Found AIFF for track %d: '%s'\n", trackID,
						   CFStringGetCStringPtr(name, kCFStringEncodingUTF8));
#endif

                    /* Track ID's start at 1, but we want to start at 0 */
                    trackID--;

                    assert(0 <= trackID && trackID <= SDL_MAX_TRACKS);

                    if (trackID < numTracks)
                        memcpy(&trackFiles[trackID], &ref, sizeof(FSRef));
                }
                CFRelease(name);
            }
        } while (noErr == result);
        FSCloseIterator(iterator);
    }

    return 0;
}

int LoadFile (const FSRef *ref, int startFrame, int stopFrame)
{
    int error = -1;

    if (CheckInit() < 0)
        goto bail;

    /* release any currently playing file */
    if (ReleaseFile() < 0)
        goto bail;

#if DEBUG_CDROM
    printf ("LoadFile: %d %d\n", startFrame, stopFrame);
#endif

    try {

        /* create a new player, and attach to the audio unit */

        thePlayer = new AudioFilePlayer(ref);
        if (thePlayer == NULL) {
            SDL_SetError ("LoadFile: Could not create player");
            return -3; /*throw (-3);*/
        }

        if (!thePlayer->SetDestination(&theUnit))
            goto bail;

        if (startFrame >= 0)
            thePlayer->SetStartFrame (startFrame);

        if (stopFrame >= 0 && stopFrame > startFrame)
            thePlayer->SetStopFrame (stopFrame);

        /* we set the notifier later */
        /*thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, NULL);*/

        if (!thePlayer->Connect())
            goto bail;

#if DEBUG_CDROM
        thePlayer->Print();
        fflush(stdout);
#endif
    }
    catch (...) {
        goto bail;
    }

    error = 0;

bail:
    return error;
}

int ReleaseFile()
{
    int error = -1;

    /* (Don't see any way that the original C++ code could throw here.) --ryan. */
    try {
        if (thePlayer != NULL) {
            thePlayer->Disconnect();
            delete thePlayer;
            thePlayer = NULL;
        }
    } catch (...) {
        goto bail;
    }

    error = 0;

bail:
    return error;
}

int PlayFile()
{
    OSStatus result = -1;

    if (CheckInit () < 0)
        goto bail;

    try {

        // start processing of the audio unit
        result = AudioOutputUnitStart (theUnit);
        THROW_RESULT("PlayFile: AudioOutputUnitStart");

    } catch (...) {
        goto bail;
    }

    result = 0;

bail:
    return result;
}

int PauseFile ()
{
    OSStatus result = -1;

    if (CheckInit () < 0)
        goto bail;

    try {

        /* stop processing the audio unit */
        result = AudioOutputUnitStop (theUnit);
        THROW_RESULT("PauseFile: AudioOutputUnitStop")
    }
    catch (...) {
        goto bail;
    }

    result = 0;
bail:
    return result;
}

void SetCompletionProc(CDPlayerCompletionProc proc, SDL2_CD *cdrom)
{
    assert(thePlayer != NULL);

    theCDROM = cdrom;
    completionProc = proc;
    thePlayer->SetNotifier (FilePlayNotificationHandler, cdrom);
}

int GetCurrentFrame()
{
    int frame;

    if (thePlayer == NULL)
        frame = 0;
    else
        frame = thePlayer->GetCurrentFrame();

    return frame;
}

#pragma mark -- Private Functions --

static OSStatus CheckInit()
{
    if (playBackWasInit)
        return 0;

    OSStatus result = noErr;

    /* Create the callback semaphore */
    callbackSem = SDL_CreateSemaphore(0);

    /* Start callback thread */
    SDL_CreateThread(RunCallBackThread, "CD Audio playback", NULL);

    try {
        AudioComponentDescription desc;

        desc.componentType = kAudioUnitType_Output;
        desc.componentSubType = kAudioUnitSubType_DefaultOutput;
        desc.componentManufacturer = kAudioUnitManufacturer_Apple;
        desc.componentFlags = 0;
        desc.componentFlagsMask = 0;

        AudioComponent comp = AudioComponentFindNext (NULL, &desc);
        if (comp == NULL) {
            SDL_SetError ("CheckInit: FindNextComponent returned NULL");
            if (result) throw(internalComponentErr);
        }

        result = AudioComponentInstanceNew (comp, &theUnit);
        THROW_RESULT("CheckInit: OpenAComponent")

        // you need to initialize the output unit before you set it as a destination
        result = AudioUnitInitialize (theUnit);
        THROW_RESULT("CheckInit: AudioUnitInitialize")

        playBackWasInit = true;
    } catch (...) {
        return -1;
    }

    return 0;
}

static void FilePlayNotificationHandler(void * inRefCon, OSStatus inStatus)
{
    if (inStatus == kAudioFilePlay_FileIsFinished) {

        /* notify non-CA thread to perform the callback */
        SDL_SemPost(callbackSem);

    } else if (inStatus == kAudioFilePlayErr_FilePlayUnderrun) {

        SDL_SetError ("CDPlayer Notification: buffer underrun");
    } else if (inStatus == kAudioFilePlay_PlayerIsUninitialized) {

        SDL_SetError ("CDPlayer Notification: player is uninitialized");
    } else {

        SDL_SetError ("CDPlayer Notification: unknown error %d", (int)inStatus);
    }
}

static int RunCallBackThread (void *param)
{
    for (;;) {

        SDL_SemWait(callbackSem);

        if (completionProc && theCDROM) {
#if DEBUG_CDROM
            printf ("callback!\n");
#endif
            (*completionProc)(theCDROM);
        } else {
#if DEBUG_CDROM
            printf ("callback?\n");
#endif
        }
    }

#if DEBUG_CDROM
    printf ("thread dying now...\n");
#endif

    return 0;
}

license: Zlib

extension: cpp


text:
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using UnityEngine;

namespace BeatSaberMarkupLanguage.Animations
{
    public class APNGUnityDecoder
    {
        private const float ByteInverse = 1f / 255f;

        [Obsolete("Use ProcessAsync instead.")]
        public static IEnumerator Process(byte[] apngData, Action<AnimationInfo> callback)
        {
            AnimationInfo animationInfo = new();
            Task.Run(() => ProcessingThread(apngData, animationInfo));
            yield return new WaitUntil(() => { return animationInfo.initialized; });
            callback?.Invoke(animationInfo);
        }

        public static Task<AnimationInfo> ProcessAsync(byte[] apngData)
        {
            return Task.Run(() =>
            {
                AnimationInfo animationInfo = new();
                ProcessingThread(apngData, animationInfo);
                return animationInfo;
            });
        }

        private static void ProcessingThread(byte[] apngData, AnimationInfo animationInfo)
        {
            APNG.APNG apng = APNG.APNG.FromStream(new System.IO.MemoryStream(apngData));
            int frameCount = apng.FrameCount;
#pragma warning disable CS0612, CS0618
            animationInfo.frameCount = frameCount;
            animationInfo.initialized = true;
#pragma warning restore CS0612, CS0618

            animationInfo.frames = new System.Collections.Generic.List<FrameInfo>(frameCount);

            FrameInfo prevFrame = default;

            for (int i = 0; i < frameCount; i++)
            {
                Frame apngFrame = apng.Frames[i];

                using (Bitmap bitmap = apngFrame.ToBitmap())
                {
                    FrameInfo frameInfo = new(bitmap.Width, bitmap.Height);

                    bitmap.MakeTransparent(System.Drawing.Color.Black);
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);

                    BitmapData frame = bitmap.LockBits(new Rectangle(Point.Empty, apng.ActualSize), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

                    Marshal.Copy(frame.Scan0, frameInfo.colors, 0, frameInfo.colors.Length);

                    bitmap.UnlockBits(frame);

                    if (apngFrame.fcTLChunk.BlendOp == APNG.Chunks.BlendOps.APNGBlendOpOver && i > 0)
                    {
                        // BGRA
                        byte[] last = prevFrame.colors;
                        byte[] src = frameInfo.colors;

                        for (int clri = frameInfo.colors.Length - 1; i > 2; i -= 4)
                        {
                            float srcA = src[clri - 3] * ByteInverse;
                            float lastA = last[clri - 3] * ByteInverse;

                            float blendedA = srcA + ((1 - srcA) * lastA);
                            src[clri - 3] = (byte)Math.Round(blendedA * 255);

                            for (int c = 0; c < 3; c++)
                            {
                                float srcC = src[clri - i] * ByteInverse;
                                float lastC = last[clri - i] * ByteInverse;

                                src[clri - i] = (byte)Math.Round(((srcA * srcC) + ((1 - srcA) * lastA * lastC * 255f)) / blendedA);
                            }
                        }
                    }

                    frameInfo.delay = apngFrame.FrameRate;
                    animationInfo.frames.Add(frameInfo);
                    prevFrame = frameInfo;
                }
            }
        }
    }
}

repository: monkeymanboy/BeatSaberMarkupLanguage

repo_name: monkeymanboy/BeatSaberMarkupLanguage

gha_license_id: MIT

gha_language: C#

extension: cs


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.ObjectModel;
using Microsoft.Azure.WebJobs.Script.Diagnostics;
using Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics;

namespace Microsoft.Azure.WebJobs.Script.Tests
{
    public class TestMetricsLogger : IMetricsLogger
    {
        public TestMetricsLogger()
        {
            LoggedEvents = new Collection<string>();
            LoggedMetricEvents = new Collection<MetricEvent>();
            MetricEventsBegan = new Collection<MetricEvent>();
            EventsBegan = new Collection<string>();
            MetricEventsEnded = new Collection<MetricEvent>();
            EventsEnded = new Collection<object>();
        }

        public Collection<string> LoggedEvents { get; }

        public Collection<MetricEvent> LoggedMetricEvents { get; }

        public Collection<MetricEvent> MetricEventsBegan { get; }

        public Collection<MetricEvent> MetricEventsEnded { get; }

        public Collection<string> EventsBegan { get; }

        public Collection<object> EventsEnded { get; }

        public void BeginEvent(MetricEvent metricEvent)
        {
            MetricEventsBegan.Add(metricEvent);
        }

        public object BeginEvent(string eventName, string functionName = null)
        {
            string key = MetricsEventManager.GetAggregateKey(eventName, functionName);
            EventsBegan.Add(key);
            return key;
        }

        public void EndEvent(object eventHandle)
        {
            EventsEnded.Add(eventHandle);
        }

        public void EndEvent(MetricEvent metricEvent)
        {
            MetricEventsEnded.Add(metricEvent);
        }

        public void LogEvent(string eventName, string functionName = null)
        {
            LoggedEvents.Add(MetricsEventManager.GetAggregateKey(eventName, functionName));
        }

        public void LogEvent(MetricEvent metricEvent)
        {
            LoggedMetricEvents.Add(metricEvent);
        }
    }
}

branch_name: refs/heads/dev


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE eagle SYSTEM "eagle.dtd">
<eagle version="9.3.0">
<drawing>
<settings>
<setting alwaysvectorfont="no"/>
<setting verticaltext="up"/>
</settings>
<grid distance="0.1" unitdist="inch" unit="inch" style="lines" multiple="1" display="no" altdistance="0.01" altunitdist="inch" altunit="inch"/>
<layers>
<layer number="1" name="Top" color="4" fill="1" visible="no" active="no"/>
<layer number="2" name="Route2" color="1" fill="3" visible="no" active="no"/>
<layer number="3" name="Route3" color="4" fill="3" visible="no" active="no"/>
<layer number="4" name="Route4" color="1" fill="4" visible="no" active="no"/>
<layer number="5" name="Route5" color="4" fill="4" visible="no" active="no"/>
<layer number="6" name="Route6" color="1" fill="8" visible="no" active="no"/>
<layer number="7" name="Route7" color="4" fill="8" visible="no" active="no"/>
<layer number="8" name="Route8" color="1" fill="2" visible="no" active="no"/>
<layer number="9" name="Route9" color="4" fill="2" visible="no" active="no"/>
<layer number="10" name="Route10" color="1" fill="7" visible="no" active="no"/>
<layer number="11" name="Route11" color="4" fill="7" visible="no" active="no"/>
<layer number="12" name="Route12" color="1" fill="5" visible="no" active="no"/>
<layer number="13" name="Route13" color="4" fill="5" visible="no" active="no"/>
<layer number="14" name="Route14" color="1" fill="6" visible="no" active="no"/>
<layer number="15" name="Route15" color="4" fill="6" visible="no" active="no"/>
<layer number="16" name="Bottom" color="1" fill="1" visible="no" active="no"/>
<layer number="17" name="Pads" color="2" fill="1" visible="no" active="no"/>
<layer number="18" name="Vias" color="2" fill="1" visible="no" active="no"/>
<layer number="19" name="Unrouted" color="6" fill="1" visible="no" active="no"/>
<layer number="20" name="Dimension" color="15" fill="1" visible="no" active="no"/>
<layer number="21" name="tPlace" color="7" fill="1" visible="no" active="no"/>
<layer number="22" name="bPlace" color="7" fill="1" visible="no" active="no"/>
<layer number="23" name="tOrigins" color="15" fill="1" visible="no" active="no"/>
<layer number="24" name="bOrigins" color="15" fill="1" visible="no" active="no"/>
<layer number="25" name="tNames" color="7" fill="1" visible="no" active="no"/>
<layer number="26" name="bNames" color="7" fill="1" visible="no" active="no"/>
<layer number="27" name="tValues" color="7" fill="1" visible="no" active="no"/>
<layer number="28" name="bValues" color="7" fill="1" visible="no" active="no"/>
<layer number="29" name="tStop" color="7" fill="3" visible="no" active="no"/>
<layer number="30" name="bStop" color="7" fill="6" visible="no" active="no"/>
<layer number="31" name="tCream" color="7" fill="4" visible="no" active="no"/>
<layer number="32" name="bCream" color="7" fill="5" visible="no" active="no"/>
<layer number="33" name="tFinish" color="6" fill="3" visible="no" active="no"/>
<layer number="34" name="bFinish" color="6" fill="6" visible="no" active="no"/>
<layer number="35" name="tGlue" color="7" fill="4" visible="no" active="no"/>
<layer number="36" name="bGlue" color="7" fill="5" visible="no" active="no"/>
<layer number="37" name="tTest" color="7" fill="1" visible="no" active="no"/>
<layer number="38" name="bTest" color="7" fill="1" visible="no" active="no"/>
<layer number="39" name="tKeepout" color="4" fill="11" visible="no" active="no"/>
<layer number="40" name="bKeepout" color="1" fill="11" visible="no" active="no"/>
<layer number="41" name="tRestrict" color="4" fill="10" visible="no" active="no"/>
<layer number="42" name="bRestrict" color="1" fill="10" visible="no" active="no"/>
<layer number="43" name="vRestrict" color="2" fill="10" visible="no" active="no"/>
<layer number="44" name="Drills" color="7" fill="1" visible="no" active="no"/>
<layer number="45" name="Holes" color="7" fill="1" visible="no" active="no"/>
<layer number="46" name="Milling" color="3" fill="1" visible="no" active="no"/>
<layer number="47" name="Measures" color="7" fill="1" visible="no" active="no"/>
<layer number="48" name="Document" color="7" fill="1" visible="no" active="no"/>
<layer number="49" name="Reference" color="7" fill="1" visible="no" active="no"/>
<layer number="51" name="tDocu" color="7" fill="1" visible="no" active="no"/>
<layer number="52" name="bDocu" color="7" fill="1" visible="no" active="no"/>
<layer number="88" name="SimResults" color="9" fill="1" visible="yes" active="yes"/>
<layer number="89" name="SimProbes" color="9" fill="1" visible="yes" active="yes"/>
<layer number="90" name="Modules" color="5" fill="1" visible="yes" active="yes"/>
<layer number="91" name="Nets" color="2" fill="1" visible="yes" active="yes"/>
<layer number="92" name="Busses" color="1" fill="1" visible="yes" active="yes"/>
<layer number="93" name="Pins" color="2" fill="1" visible="no" active="yes"/>
<layer number="94" name="Symbols" color="4" fill="1" visible="yes" active="yes"/>
<layer number="95" name="Names" color="7" fill="1" visible="yes" active="yes"/>
<layer number="96" name="Values" color="7" fill="1" visible="yes" active="yes"/>
<layer number="97" name="Info" color="7" fill="1" visible="yes" active="yes"/>
<layer number="98" name="Guide" color="6" fill="1" visible="yes" active="yes"/>
</layers>
<schematic xreflabel="%F%N/%S.%C%R" xrefpart="/%S.%C%R">
<libraries>
<library name="221790-1">
<packages>
<package name="TE_221790-1">
<wire x1="-3.556" y1="2.54" x2="-3.556" y2="-2.54" width="0.127" layer="51"/>
<wire x1="4.064" y1="2.54" x2="4.064" y2="-1.397" width="0.127" layer="21"/>
<wire x1="4.064" y1="-1.397" x2="4.064" y2="-2.54" width="0.127" layer="21"/>
<wire x1="4.091" y1="1.397" x2="8.636" y2="1.397" width="0.127" layer="21"/>
<wire x1="8.636" y1="1.397" x2="8.636" y2="2.54" width="0.127" layer="21"/>
<wire x1="4.064" y1="-1.397" x2="8.636" y2="-1.397" width="0.127" layer="21"/>
<wire x1="4.064" y1="2.54" x2="-3.556" y2="2.54" width="0.127" layer="51"/>
<wire x1="-3.556" y1="-2.54" x2="4.064" y2="-2.54" width="0.127" layer="51"/>
<wire x1="9.144" y1="2.54" x2="9.144" y2="-2.413" width="0.127" layer="21"/>
<wire x1="9.652" y1="2.54" x2="9.652" y2="-2.413" width="0.127" layer="21"/>
<wire x1="8.636" y1="2.54" x2="9.144" y2="2.54" width="0.127" layer="21"/>
<wire x1="9.144" y1="2.54" x2="9.652" y2="2.54" width="0.127" layer="21"/>
<wire x1="9.652" y1="2.54" x2="10.16" y2="2.54" width="0.127" layer="21"/>
<wire x1="10.16" y1="2.54" x2="10.668" y2="2.54" width="0.127" layer="21"/>
<wire x1="10.668" y1="2.54" x2="11.176" y2="2.54" width="0.127" layer="21"/>
<wire x1="11.176" y1="2.54" x2="11.684" y2="2.54" width="0.127" layer="21"/>
<wire x1="11.684" y1="2.54" x2="11.684" y2="-2.413" width="0.127" layer="21"/>
<wire x1="11.684" y1="-2.413" x2="11.176" y2="-2.413" width="0.127" layer="21"/>
<wire x1="11.176" y1="-2.413" x2="10.668" y2="-2.413" width="0.127" layer="21"/>
<wire x1="10.668" y1="-2.413" x2="10.16" y2="-2.413" width="0.127" layer="21"/>
<wire x1="10.16" y1="-2.413" x2="9.652" y2="-2.413" width="0.127" layer="21"/>
<wire x1="9.652" y1="-2.413" x2="9.144" y2="-2.413" width="0.127" layer="21"/>
<wire x1="9.144" y1="-2.413" x2="8.636" y2="-2.413" width="0.127" layer="21"/>
<wire x1="8.636" y1="-2.413" x2="8.636" y2="-1.397" width="0.127" layer="21"/>
<wire x1="8.636" y1="-1.397" x2="8.636" y2="1.397" width="0.127" layer="21"/>
<wire x1="10.16" y1="2.54" x2="10.16" y2="-2.413" width="0.127" layer="21"/>
<wire x1="10.668" y1="2.54" x2="10.668" y2="-2.413" width="0.127" layer="21"/>
<wire x1="11.176" y1="2.54" x2="11.176" y2="-2.413" width="0.127" layer="21"/>
<wire x1="-4.2" y1="4.2" x2="12" y2="4.2" width="0.127" layer="39"/>
<wire x1="12" y1="4.2" x2="12" y2="-4.2" width="0.127" layer="39"/>
<wire x1="12" y1="-4.2" x2="-4.2" y2="-4.2" width="0.127" layer="39"/>
<wire x1="-4.2" y1="-4.2" x2="-4.2" y2="4.2" width="0.127" layer="39"/>
<text x="-3.60445" y="3.90481875" size="1.27156875" layer="25">>NAME</text>
<text x="-4.10498125" y="-5.306440625" size="1.271540625" layer="27">>VALUE</text>
<pad name="1" x="0" y="0" drill="1.778"/>
<pad name="2" x="-2.54" y="2.54" drill="1.7018"/>
<pad name="3" x="2.54" y="2.54" drill="1.7018"/>
<pad name="5" x="2.54" y="-2.54" drill="1.7018"/>
<pad name="4" x="-2.54" y="-2.54" drill="1.7018"/>
</package>
</packages>
<symbols>
<symbol name="221790-1">
<circle x="0" y="2.54" radius="1.016" width="0.254" layer="94"/>
<wire x1="-1.016" y1="1.524" x2="0" y2="1.524" width="0.254" layer="94"/>
<wire x1="0" y1="1.524" x2="1.016" y2="1.524" width="0.254" layer="94"/>
<wire x1="0" y1="-2.54" x2="-3.556" y2="-2.54" width="0.254" layer="94"/>
<wire x1="-4.826" y1="3.556" x2="-3.81" y2="2.54" width="0.254" layer="94"/>
<wire x1="-4.826" y1="1.524" x2="-3.81" y2="2.54" width="0.254" layer="94"/>
<wire x1="-4.572" y1="-1.524" x2="-3.556" y2="-2.54" width="0.254" layer="94"/>
<wire x1="-4.572" y1="-3.556" x2="-3.556" y2="-2.54" width="0.254" layer="94"/>
<wire x1="0" y1="1.524" x2="0" y2="-2.54" width="0.254" layer="94"/>
<circle x="0" y="-2.54" radius="0.254" width="0.254" layer="94"/>
<wire x1="-3.81" y1="2.54" x2="2.54" y2="2.54" width="0.254" layer="94"/>
<wire x1="2.54" y1="-2.54" x2="0" y2="-2.54" width="0.254" layer="94"/>
<text x="-3.8155" y="4.06986875" size="1.27183125" layer="95">>NAME</text>
<text x="-4.323640625" y="-5.5953" size="1.271659375" layer="96">>VALUE</text>
<wire x1="0" y1="-2.54" x2="0" y2="-3.302" width="0.254" layer="94"/>
<wire x1="0" y1="-3.302" x2="-0.762" y2="-3.302" width="0.254" layer="94"/>
<wire x1="0" y1="-3.302" x2="0.762" y2="-3.302" width="0.254" layer="94"/>
<wire x1="-0.762" y1="-3.302" x2="-1.27" y2="-4.064" width="0.254" layer="94"/>
<wire x1="0" y1="-3.302" x2="-0.508" y2="-4.064" width="0.254" layer="94"/>
<wire x1="0.762" y1="-3.302" x2="0.254" y2="-4.064" width="0.254" layer="94"/>
<pin name="1" x="2.54" y="2.54" length="middle" direction="pas" rot="R180"/>
<pin name="2" x="2.54" y="-2.54" length="middle" direction="pas" rot="R180"/>
</symbol>
</symbols>
<devicesets>
<deviceset name="221790-1" prefix="J">
<description>Connector; SMA; PCB; Right Angle; Stainless Steel; 0.6 in.; Beryllium Copper</description>
<gates>
<gate name="G$1" symbol="221790-1" x="0" y="0"/>
</gates>
<devices>
<device name="" package="TE_221790-1">
<connects>
<connect gate="G$1" pin="1" pad="1"/>
<connect gate="G$1" pin="2" pad="2 3 4 5"/>
</connects>
<technologies>
<technology name="">
<attribute name="AVAILABILITY" value="Unavailable"/>
<attribute name="COMMENT" value="221790-1"/>
<attribute name="DESCRIPTION" value=" JACK,RIGHT ANGLE,PCB,SMA "/>
<attribute name="EU_ROHS_COMPLIANCE" value="Compliant with Exemptions"/>
<attribute name="MF" value="TE Connectivity"/>
<attribute name="MP" value="221790-1"/>
<attribute name="NUMBER_OF_POSITIONS" value="1"/>
<attribute name="PACKAGE" value="None"/>
<attribute name="PRICE" value="None"/>
<attribute name="TE_PURCHASE_URL" value="https://www.te.com/usa-en/product-221790-1.html?te_bu=Cor&te_type=disp&te_campaign=seda_glo_cor-seda-global-disp-prtnr-fy19-seda-model-bom-cta_sma-317_1&elqCampaignId=32493"/>
</technology>
</technologies>
</device>
</devices>
</deviceset>
</devicesets>
</library>
<library name="con-garry" urn="urn:adsk.eagle:library:147">
<description>Pin Header Connectors

Menufacturer

<author>Created by librarian@cadsoft.de</author></description>
<packages>
<package name="332-02" urn="urn:adsk.eagle:footprint:6784/1" library_version="1">
<description>2 Pin - 2mm Dual Row

Source: www.mpe-connector.de / garry_shortform_2012.pdf</description>
<wire x1="-0.85" y1="-1.9" x2="0.85" y2="-1.9" width="0.2032" layer="21"/>
<wire x1="0.85" y1="-1.9" x2="0.85" y2="-0.4" width="0.2032" layer="21"/>
<wire x1="0.85" y1="0.4" x2="0.85" y2="1.9" width="0.2032" layer="21"/>
<wire x1="0.85" y1="1.9" x2="-0.85" y2="1.9" width="0.2032" layer="21"/>
<wire x1="-0.85" y1="1.9" x2="-0.85" y2="0.4" width="0.2032" layer="21"/>
<wire x1="-0.85" y1="-0.4" x2="-0.85" y2="-1.9" width="0.2032" layer="21"/>
<wire x1="-0.85" y1="0.4" x2="-0.85" y2="-0.4" width="0.2032" layer="21" curve="-129.185"/>
<wire x1="0.85" y1="-0.4" x2="0.85" y2="0.4" width="0.2032" layer="21" curve="-129.185"/>
<pad name="1" x="0" y="-1" drill="0.9" diameter="1.27"/>
<pad name="2" x="0" y="1" drill="0.9" diameter="1.27"/>
<text x="-0.65" y="-1.75" size="0.3048" layer="21" font="vector">1</text>
<text x="-0.62" y="-3.81" size="1.27" layer="25">>NAME</text>
<text x="-0.62" y="2.54" size="1.27" layer="27">>VALUE</text>
<rectangle x1="-0.25" y1="-1.25" x2="0.25" y2="-0.75" layer="51"/>
<rectangle x1="-0.25" y1="0.75" x2="0.25" y2="1.25" layer="51"/>
</package>
</packages>
<packages3d>
<package3d name="332-02" urn="urn:adsk.eagle:package:6810/1" type="box" library_version="1">
<description>2 Pin - 2mm Dual Row
Source: www.mpe-connector.de / garry_shortform_2012.pdf</description>
<packageinstances>
<packageinstance name="332-02"/>
</packageinstances>
</package3d>
</packages3d>
<symbols>
<symbol name="MV" urn="urn:adsk.eagle:symbol:6783/1" library_version="1">
<wire x1="1.27" y1="0" x2="0" y2="0" width="0.6096" layer="94"/>
<text x="2.54" y="-0.762" size="1.524" layer="95">>NAME</text>
<text x="-0.762" y="1.397" size="1.778" layer="96">>VALUE</text>
<pin name="S" x="-2.54" y="0" visible="off" length="short" direction="pas"/>
</symbol>
</symbols>
<devicesets>
<deviceset name="332-02" urn="urn:adsk.eagle:component:6832/1" prefix="X" library_version="1">
<description>2 Pin - 2mm Dual Row

Source: www.mpe-connector.de / garry_shortform_2012.pdf</description>
<gates>
<gate name="-1" symbol="MV" x="-10.16" y="0" addlevel="always"/>
<gate name="-2" symbol="MV" x="10.16" y="0" addlevel="always"/>
</gates>
<devices>
<device name="" package="332-02">
<connects>
<connect gate="-1" pin="S" pad="1"/>
<connect gate="-2" pin="S" pad="2"/>
</connects>
<package3dinstances>
<package3dinstance package3d_urn="urn:adsk.eagle:package:6810/1"/>
</package3dinstances>
<technologies>
<technology name=""/>
</technologies>
</device>
</devices>
</deviceset>
</devicesets>
</library>
</libraries>
<attributes>
</attributes>
<variantdefs>
</variantdefs>
<classes>
<class number="0" name="default" width="0" drill="0">
</class>
</classes>
<parts>
<part name="J1" library="221790-1" deviceset="221790-1" device=""/>
<part name="X1" library="con-garry" library_urn="urn:adsk.eagle:library:147" deviceset="332-02" device="" package3d_urn="urn:adsk.eagle:package:6810/1"/>
<part name="X2" library="con-garry" library_urn="urn:adsk.eagle:library:147" deviceset="332-02" device="" package3d_urn="urn:adsk.eagle:package:6810/1"/>
</parts>
<sheets>
<sheet>
<plain>
</plain>
<instances>
<instance part="J1" gate="G$1" x="-17.78" y="0" smashed="yes">
<attribute name="NAME" x="-21.5955" y="4.06986875" size="1.27183125" layer="95"/>
<attribute name="VALUE" x="-22.103640625" y="-5.5953" size="1.271659375" layer="96"/>
</instance>
<instance part="X1" gate="-1" x="-2.54" y="12.7" smashed="yes" rot="R90">
<attribute name="NAME" x="-1.778" y="15.24" size="1.524" layer="95" rot="R90"/>
<attribute name="VALUE" x="-3.937" y="11.938" size="1.778" layer="96" rot="R90"/>
</instance>
<instance part="X1" gate="-2" x="2.54" y="12.7" smashed="yes" rot="R90">
<attribute name="NAME" x="3.302" y="15.24" size="1.524" layer="95" rot="R90"/>
<attribute name="VALUE" x="1.143" y="11.938" size="1.778" layer="96" rot="R90"/>
</instance>
<instance part="X2" gate="-1" x="-2.54" y="-12.7" smashed="yes" rot="R270">
<attribute name="NAME" x="-3.302" y="-15.24" size="1.524" layer="95" rot="R270"/>
<attribute name="VALUE" x="-1.143" y="-11.938" size="1.778" layer="96" rot="R270"/>
</instance>
<instance part="X2" gate="-2" x="2.54" y="-12.7" smashed="yes" rot="R270">
<attribute name="NAME" x="1.778" y="-15.24" size="1.524" layer="95" rot="R270"/>
<attribute name="VALUE" x="3.937" y="-11.938" size="1.778" layer="96" rot="R270"/>
</instance>
</instances>
<busses>
</busses>
<nets>
<net name="DAT" class="0">
<segment>
<pinref part="J1" gate="G$1" pin="1"/>
<pinref part="X1" gate="-1" pin="S"/>
<wire x1="-15.24" y1="2.54" x2="-2.54" y2="2.54" width="0.1524" layer="91"/>
<wire x1="-2.54" y1="2.54" x2="-2.54" y2="10.16" width="0.1524" layer="91"/>
<pinref part="X1" gate="-2" pin="S"/>
<wire x1="-2.54" y1="2.54" x2="2.54" y2="2.54" width="0.1524" layer="91"/>
<wire x1="2.54" y1="2.54" x2="2.54" y2="10.16" width="0.1524" layer="91"/>
<junction x="-2.54" y="2.54"/>

</segment>
</net>
<net name="GND" class="0">
<segment>
<pinref part="J1" gate="G$1" pin="2"/>
<pinref part="X2" gate="-1" pin="S"/>
<wire x1="-15.24" y1="-2.54" x2="-2.54" y2="-2.54" width="0.1524" layer="91"/>
<wire x1="-2.54" y1="-2.54" x2="-2.54" y2="-10.16" width="0.1524" layer="91"/>
<pinref part="X2" gate="-2" pin="S"/>
<wire x1="-2.54" y1="-2.54" x2="2.54" y2="-2.54" width="0.1524" layer="91"/>
<wire x1="2.54" y1="-2.54" x2="2.54" y2="-10.16" width="0.1524" layer="91"/>
<junction x="-2.54" y="-2.54"/>

</segment>
</net>
</nets>
</sheet>
</sheets>
</schematic>
</drawing>
<compatibility>
<note version="8.2" severity="warning">
Since Version 8.2, EAGLE supports online libraries. The ids
of those online libraries will not be understood (or retained)
with this version.
</note>
<note version="8.3" severity="warning">
Since Version 8.3, EAGLE supports URNs for individual library
assets (packages, symbols, and devices). The URNs of those assets
will not be understood (or retained) with this version.
</note>
<note version="8.3" severity="warning">
Since Version 8.3, EAGLE supports the association of 3D packages
with devices in libraries, schematics, and board files. Those 3D
packages will not be understood (or retained) with this version.
</note>
</compatibility>
</eagle>

gha_language: C

extension: sch


text:
package test

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
	"time"

	"CloudAssetUploader/config"
	"CloudAssetUploader/constants"
	"CloudAssetUploader/data"
	"CloudAssetUploader/responses"
	"CloudAssetUploader/server"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/rs/zerolog/log"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestMain(m *testing.M) {
	setUp()
	code := m.Run()
	os.Exit(code)
}

var (
	env        *config.Env
	httpClient *http.Client
)

func setUp() {
	httpClient = &http.Client{}
	setLocalhostEnvVars()

	awsRegion := os.Getenv("AWS_REGION")
	if awsRegion == "" {
		awsRegion = constants.DefaultRegion
	}
	sess, err := session.NewSession(&aws.Config{
		Region: aws.String(awsRegion),
	})
	if err != nil {
		log.Fatal().Msgf("Could not connect to aws: %s", err)
	}

	connStr, err := data.BuildConnectionStringForMongoDB()
	if err != nil {
		log.Fatal().Msgf("Could not build connection for MongoDB: %s", err)
	}

	db, err := data.NewDB(connStr)
	if err != nil {
		log.Fatal().Msgf("Could not connect to MongoDB: %s", err)
	}

	env = config.NewEnv(sess, db)
	err = env.AssetUploader.SetupBucket()
	if err != nil {
		log.Fatal().Msgf("Could not setup AWS bucket env. Err: %s", err)
	}
}

func setLocalhostEnvVars() {
	err := os.Setenv("MONGO_USERNAME", "mongoadmin")
	err = os.Setenv("MONGO_PASSWORD", "bigSecret")
	err = os.Setenv("MONGO_CONTAINER_NAME", "localhost")
	err = os.Setenv("MONGO_PORT", "12345")

	if err != nil {
		log.Error().Msg("Could not set environment variables for connection to MongoDB container from local machine. Integration tests will fail.")
	}
}

func TestAPIFlows(t *testing.T) {
	// First, request an upload URL with valid expiration
	rec := httptest.NewRecorder()
	upldReq, err := http.NewRequest(constants.RequestMethodPost, fmt.Sprintf("%s?timeout=311", constants.AssetsURL), nil)
	require.NoError(t, err)

	server.RequestUploadURL(env).ServeHTTP(rec, upldReq)

	assert.Equal(t, http.StatusOK, rec.Code)
	buf, err := ioutil.ReadAll(rec.Body)
	require.NoError(t, err)
	validateContentType(t, rec)

	uploadResp := &responses.UploadURLResponse{}
	require.NoError(t, json.Unmarshal(buf, uploadResp))

	// Now make a PUT request to upload an asset to AWS
	upldFile, err := getUploadBytes()
	require.NoError(t, err)

	awsUploadReq, err := http.NewRequest(constants.RequestMethodPut, uploadResp.URL, bytes.NewBuffer(upldFile))
	require.NoError(t, err)

	awsResp, err := httpClient.Do(awsUploadReq)
	require.NoError(t, err)

	assert.Equal(t, http.StatusOK, awsResp.StatusCode)

	// Set the status of the asset to uploaded
	statusRec := httptest.NewRecorder()
	statusReq, err := http.NewRequest(constants.RequestMethodPut,
		fmt.Sprintf("%s?id=%s&status=%s", constants.StatusURL, uploadResp.ID, constants.AssetStatusUploaded), nil)
	require.NoError(t, err)

	server.SetUploadStatus(env).ServeHTTP(statusRec, statusReq)

	assert.Equal(t, http.StatusOK, statusRec.Code)
	buf, err = ioutil.ReadAll(statusRec.Body)
	require.NoError(t, err)
	validateContentType(t, statusRec)

	statusResp := &responses.StatusUpdateResponse{}
	require.NoError(t, json.Unmarshal(buf, statusResp))
	assert.Equal(t, uploadResp.ID, statusResp.ID)
	assert.Equal(t, constants.AssetStatusUploaded, statusResp.Status)

	// Make a request for a download URL for the uploaded asset
	downloadRec := httptest.NewRecorder()
	downloadReq, err := http.NewRequest(constants.RequestMethodGet,
		fmt.Sprintf("%s?id=%s", constants.AssetsURL, uploadResp.ID), nil)
	require.NoError(t, err)

	server.GetDownloadURL(env).ServeHTTP(downloadRec, downloadReq)

	assert.Equal(t, http.StatusOK, downloadRec.Code)
	buf, err = ioutil.ReadAll(downloadRec.Body)
	require.NoError(t, err)
	validateContentType(t, downloadRec)

	downloadResp := &responses.DownloadURLResponse{}
	require.NoError(t, json.Unmarshal(buf, downloadResp))
	assert.Equal(t, uploadResp.ID, downloadResp.ID)
	assert.Equal(t, statusResp.ID, downloadResp.ID)

	// Actually download the file from AWS
	awsDownloadResp, err := http.Get(downloadResp.DownloadURL)
	require.NoError(t, err)
	assert.Equal(t, http.StatusOK, awsDownloadResp.StatusCode)

	// Now make a PUT request to upload an asset to AWS after the expiry time has passed.
	expUpldResp := getUploadURLResponse(env, t, "2")
	time.Sleep(2 * time.Second)

	upldFile, err = getUploadBytes()
	require.NoError(t, err)

	awsExpUploadReq, err := http.NewRequest(constants.RequestMethodPut, expUpldResp.URL, bytes.NewBuffer(upldFile))
	require.NoError(t, err)

	awsExpResp, err := httpClient.Do(awsExpUploadReq)
	require.NoError(t, err)

	assert.Equal(t, http.StatusForbidden, awsExpResp.StatusCode)
}

func getUploadURLResponse(env *config.Env, t *testing.T, timeout string) *responses.UploadURLResponse {
	// Check that upload URL actually expires after the specified timeout
	rec := httptest.NewRecorder()
	req, err := http.NewRequest(constants.RequestMethodPost,
		fmt.Sprintf("%s?timeout=%s", constants.AssetsURL, timeout), nil)
	require.NoError(t, err)

	server.RequestUploadURL(env).ServeHTTP(rec, req)

	assert.Equal(t, http.StatusOK, rec.Code)
	buf, err := ioutil.ReadAll(rec.Body)
	require.NoError(t, err)
	validateContentType(t, rec)

	resp := &responses.UploadURLResponse{}
	require.NoError(t, json.Unmarshal(buf, resp))
	return resp
}

func validateContentType(t *testing.T, rec *httptest.ResponseRecorder) {
	contentType := rec.Header().Get(constants.HeaderContentType)
	assert.Equal(t, constants.ApplicationJSON, contentType)
}

func getUploadBytes() ([]byte, error) {
	workDir, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	f, err := os.Open(fmt.Sprintf("%s/%s", workDir, constants.UploadImagePath))
	if err != nil {
		return nil, err
	}

	buf, err := ioutil.ReadAll(f)
	return buf, err
}


text:
package main

// TODO: Flag to ignore included bundles (only extract the requested). Still need to parse
// the included to figure out the directories metadata. Skip the packs for includes, just
// download fullfile.

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"syscall"

	"github.com/clearlinux/mixer-tools/internal/client"
	"github.com/clearlinux/mixer-tools/swupd"
)

func usage() {
	fmt.Printf(`swupd-extract reads a swupd update repository and write it to disk

Usage:

    swupd-extract https://.../version        [bundles...]
    swupd-extract /local/path/to/.../version [bundles...]

The program downloads the content of a specific version in a swupd
repository and extract the content of the specified bundles (groups of
content). If no bundle is specified the program will list the bundles
available. Bundles specified will automatically trigger the extraction
of bundles that they include.

The program extracts the content to a directory called "output" or a
directory set with the -output flag. Intermediate data is saved in a
directory sibling to the output directory called "swupd-state" or a
directory set with the -state flag.

The state directory can hold intermediate data for multiple versions
from the same repository.

There is a shorthand for extracting content from Clear Linux. For this
case the version can be omitted so that the latest version is used:

    swupd-extract clear/20520 [bundles...]
    swupd-extract clear       [bundles...]

If not available locally, the certificate for Clear Linux is
automatically downloaded and verified.

Flags:
`)
	flag.PrintDefaults()
	os.Exit(1)
}

const (
	clearLinuxLatestURL         = "https://download.clearlinux.org/latest"
	clearLinuxBaseContent       = "https://cdn.download.clearlinux.org/update"
	clearLinuxCertificateURL    = "https://cdn.download.clearlinux.org/current/Swupd_Root.pem"
	clearLinuxCertificateSHA256 = "ff06fc76ec5148040acb4fcb2bc8105cc72f1963b55de0daf3a4ed664c6fe72c"
)

func main() {
	log.SetFlags(0)

	var (
		outputDir   string
		stateDir    string
		cert        string
		noCache     bool
		noOverwrite bool
	)

	flag.StringVar(&outputDir, "output", "output", "where to extract the files")
	flag.StringVar(&stateDir, "state", "", "directory to store intermediate files")
	flag.StringVar(&cert, "cert", "", "certificate used to verify content")
	flag.BoolVar(&noCache, "no-cache", false, "don't use cached files, force downloads")
	flag.BoolVar(&noOverwrite, "no-overwrite", false, "don't overwrite output files")
	flag.Parse()

	if os.Getuid() != 0 {
		log.Fatal("This program needs to run as root to write files with proper permissions.")
	}

	if len(flag.Args()) == 0 {
		usage()
		return
	}

	// Normalize content argument to not have ending slashes.
	content := flag.Arg(0)
	for content[len(content)-1] == '/' {
		content = content[:len(content)-1]
	}

	if strings.HasPrefix(content, "clear/") || strings.HasPrefix(content, "clearlinux/") {
		parts := strings.SplitN(content, "/", 2)
		content = clearLinuxBaseContent + "/" + parts[1]
	} else if content == "clear" || content == "clearlinux" {
		// Query latest version from Clear Linux.
		res, err := http.Get(clearLinuxLatestURL)
		if err != nil {
			log.Fatalf("ERROR: no version passed and couldn't query latest version of Clear Linux: %s", err)
		}
		if res.StatusCode != http.StatusOK {
			log.Fatalf("ERROR: no version passed and couldn't query latest version of Clear Linux: %s resulted in %d %s", clearLinuxLatestURL, res.StatusCode, http.StatusText(res.StatusCode))
		}
		latestBytes, err := ioutil.ReadAll(res.Body)
		if err != nil {
			log.Fatalf("ERROR: no version passed and couldn't query latest version of Clear Linux: %s", err)
		}
		content = clearLinuxBaseContent + "/" + string(bytes.TrimSpace(latestBytes))
	}

	// Extract baseContent and version information.
	sep := strings.LastIndex(content, "/")
	if sep == -1 {
		log.Fatalf("Invalid URL or directory for content: %s", content)
	}
	baseContent, version := content[:sep], content[sep+1:]

	if stateDir == "" {
		stateDir = filepath.Join(filepath.Dir(outputDir), "swupd-state")
	}

	parsed, err := strconv.ParseUint(version, 10, 32)
	if err != nil {
		log.Fatalf("ERROR: invalid content URL or directory %s: last part must be the version number, but found %q instead", content, version)
	}
	if parsed == 0 {
		log.Fatalf("ERROR: version must be greater than zero")
	}

	var mayDownloadClearLinuxCert bool
	if cert == "" {
		cert = findDefaultCert()
		if cert == "" {
			if baseContent != clearLinuxBaseContent {
				log.Fatalf("ERROR: couldn't find Swupd_Root.pem in current directory and no -cert flag was passed")
			}
			cert = filepath.Join(stateDir, "Swupd_Root.pem")
			mayDownloadClearLinuxCert = true
		}
	}

	fmt.Printf(`» Parameters

  Base content:     %s
  Version:          %s
  Use Cache:        %t
  Certificate:      %s
  State directory:  %s
  Output directory: %s

`, baseContent, version, !noCache, cert, stateDir, outputDir)

	fmt.Printf("» Verifying state directory\n")
	state, err := client.NewState(stateDir, baseContent)
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}
	state.NoCache = noCache
	state.Verbose = true

	if mayDownloadClearLinuxCert {
		if _, err = os.Stat(cert); err != nil {
			if !os.IsNotExist(err) {
				log.Fatalf("ERROR: couldn't open certificate file: %s", err)
			}
			tempCert := cert + ".temp"
			err = client.Download(clearLinuxCertificateURL, tempCert)
			if err != nil {
				log.Fatalf("ERROR: couldn't download Clear Linux certificate: %s", err)
			}
			var certBytes []byte
			certBytes, err = ioutil.ReadFile(tempCert)
			if err != nil {
				_ = os.Remove(tempCert)
				log.Fatalf("ERROR: couldn't downloaded Clear Linux certificate: %s", err)
			}
			tempSHA256Bytes := sha256.Sum256(certBytes)
			tempSHA256 := hex.EncodeToString(tempSHA256Bytes[:])
			if string(tempSHA256[:]) != clearLinuxCertificateSHA256 {
				_ = os.Remove(tempCert)
				log.Fatalf(`ERROR: verification of downloaded Clear Linux certificate failed:
  got SHA256 hash %q
     but expected %q`, tempSHA256, clearLinuxCertificateSHA256)
			}
			err = os.Rename(tempCert, cert)
			if err != nil {
				log.Fatalf("ERROR: couldn't rename downloaded certificate to its final name: %s", err)
			}
		}
	}

	fmt.Printf("» Reading metadata\n")
	momFile, err := state.GetFile(version, "Manifest.MoM")
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}
	momSig, err := state.GetFile(version, "Manifest.MoM.sig")
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}

	err = verifySignature(momFile, momSig, cert)
	if err != nil {
		log.Fatalf("ERROR: couldn't verify Manifest.MoM: %s", err)
	}

	mom, err := swupd.ParseManifestFile(momFile)
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}

	// If not bundles passed, just show the list of available bundles.
	if len(flag.Args()) == 1 {
		sort.Slice(mom.Files, func(i, j int) bool {
			return mom.Files[i].Name < mom.Files[j].Name
		})
		fmt.Printf("Available bundles in %s\n", content)
		for _, f := range mom.Files {
			fmt.Printf("  %s\n", f.Name)
		}
		return
	}

	requestedBundles := flag.Args()[1:]
	bundleMap, err := resolveBundles(state, mom, requestedBundles)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("» Extracting packs\n")
	for _, b := range bundleMap {
		err = state.GetZeroPack(fmt.Sprint(b.Header.Version), b.Name)
		if err != nil {
			log.Fatalf("ERROR: couldn't get pack for %s: %s", b.Name, err)
		}
	}

	fmt.Printf("» Copying files\n")
	allFileMap := make(map[string]*swupd.File)
	var allFiles []*swupd.File
	for _, b := range bundleMap {
		for _, f := range b.Files {
			if f.Status == swupd.StatusDeleted || f.Status == swupd.StatusGhosted {
				continue
			}
			// TODO: Should ignore files with certain f.Modifiers?
			if _, ok := allFileMap[f.Name]; ok {
				continue
			}
			allFileMap[f.Name] = f
			allFiles = append(allFiles, f)
		}
	}

	sort.Slice(allFiles, func(i, j int) bool {
		return allFiles[i].Name < allFiles[j].Name
	})

	err = copyAllFiles(state, outputDir, allFiles, noOverwrite)
	if err != nil {
		log.Fatalf("ERROR: couldn't copy files: %s", err)
	}
}

func resolveBundles(state *client.State, mom *swupd.Manifest, requested []string) (map[string]*swupd.Manifest, error) {
	var includes []string

	// Ignore requested duplicates.
	sort.Strings(requested)
	for i, name := range requested {
		if i > 0 && requested[i-1] == name {
			continue
		}
		includes = append(includes, name)
	}

	// Visit bundles and their included files. For the purposes of extracting, we
	// don't care if there are cycles in the bundles, so don't validate that.
	max := 0
	bundles := make(map[string]*swupd.Manifest)
	for len(includes) > 0 {
		var name string
		name, includes = includes[0], includes[1:]

		// Already included.
		if _, ok := bundles[name]; ok {
			continue
		}

		if max < len(name) {
			max = len(name)
		}

		var bundleFile *swupd.File
		for _, f := range mom.Files {
			if f.Name == name {
				bundleFile = f
				break
			}
		}
		if bundleFile == nil {
			return nil, fmt.Errorf("bundle %s not found in Manifest.MoM", name)
		}

		m, err := state.GetBundleManifest(fmt.Sprint(bundleFile.Version), name, bundleFile.Hash.String())
		if err != nil {
			return nil, err
		}

		for _, inc := range m.Header.Includes {
			includes = append(includes, inc.Name)
		}
		bundles[name] = m
	}

	fmt.Println()
	for name, b := range bundles {
		fmt.Printf("  %-*s %d\n", max, name, b.Header.Version)
	}
	fmt.Println()

	return bundles, nil
}

func copyAllFiles(state *client.State, outputDir string, allFiles []*swupd.File, noOverwrite bool) error {
	err := os.MkdirAll(outputDir, 0755)
	if err != nil {
		return err
	}

	for _, f := range allFiles {
		src := state.Path("staged/", f.Hash.String())
		dst := filepath.Join(outputDir, f.Name)

		// Check if we have the source file, if not download it.
		srcFI, err := os.Lstat(src)
		if err != nil {
			if !os.IsNotExist(err) {
				return fmt.Errorf("couldn't access existing staged file %s for %s: %s", src, dst, err)
			}
			err = state.GetFullfile(fmt.Sprint(f.Version), f.Hash.String())
			if err != nil {
				return fmt.Errorf("couldn't download fullfile for %s with hash %s: %s", dst, f.Hash.String(), err)
			}
			srcFI, err = os.Lstat(src)
			if err != nil {
				return fmt.Errorf("couldn't access staged file for %s: %s", dst, err)
			}
		}

		// Check if destination file is already what we want.
		dstFI, err := os.Lstat(dst)
		if err != nil && !os.IsNotExist(err) {
			return fmt.Errorf("couldn't access existing file %s: %s", dst, err)
		}
		if err == nil {
			var hash string
			hash, err = swupd.GetHashForFile(dst)
			if err != nil {
				return err
			}
			if hash == f.Hash.String() {
				continue
			}

			// Try to fix the permissions of directory, to avoid destroying
			// its contents if not necessary.
			if srcFI.IsDir() && dstFI.IsDir() {
				if srcFI.Mode() != dstFI.Mode() {
					fmt.Printf("! fixing mode for %s from %s to %s\n", dst, dstFI.Mode(), srcFI.Mode())
					err = os.Chmod(dst, srcFI.Mode())
					if err != nil {
						return fmt.Errorf("couldn't fix mode for existing file %s: %s", dst, err)
					}
				}
				srcStat := srcFI.Sys().(*syscall.Stat_t)
				dstStat := dstFI.Sys().(*syscall.Stat_t)
				if srcStat.Uid != dstStat.Uid || srcStat.Gid != dstStat.Gid {
					fmt.Printf("! fixing ownership for %s from %d:%d to %d:%d\n", dst, dstStat.Uid, dstStat.Gid, srcStat.Uid, srcStat.Gid)
					err = os.Chown(dst, int(srcStat.Uid), int(srcStat.Gid))
					if err != nil {
						return fmt.Errorf("couldn't fix ownership of existing file %s: %s", dst, err)
					}
				}
				continue
			}

			if noOverwrite {
				fmt.Printf("! skipping %s\n", dst)
				continue
			}

			fmt.Printf("! overwriting %s\n", dst)
			err = os.RemoveAll(dst)
			if err != nil {
				return fmt.Errorf("couldn't remove %s for overwriting: %s", dst, err)
			}
		}

		switch f.Type {
		case swupd.TypeFile:
			err = copyFile(dst, src, srcFI)
		case swupd.TypeDirectory:
			err = os.Mkdir(dst, srcFI.Mode())
			if err != nil {
				return err
			}
			err = os.Chmod(dst, srcFI.Mode())
		case swupd.TypeLink:
			var linkname string
			linkname, err = os.Readlink(src)
			if err != nil {
				return err
			}
			err = os.Symlink(linkname, dst)
		default:
			err = fmt.Errorf("unknown type for %s", f.Name)
		}
		if err != nil {
			return err
		}
	}

	return nil
}

func copyFile(dst string, src string, srcFI os.FileInfo) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}

	dstFile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, srcFI.Mode())
	if err != nil {
		_ = srcFile.Close()
		return err
	}

	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		_ = srcFile.Close()
		_ = dstFile.Close()
		return fmt.Errorf("failure to copy data from %s to %s: %s", src, dst, err)
	}
	err = srcFile.Close()
	if err != nil {
		_ = dstFile.Close()
		return err
	}

	srcStat := srcFI.Sys().(*syscall.Stat_t)
	err = dstFile.Chown(int(srcStat.Uid), int(srcStat.Gid))
	if err != nil {
		_ = dstFile.Close()
		return err
	}
	if srcFI.Mode()&(os.ModeSticky|os.ModeSetgid|os.ModeSetuid) != 0 {
		err = dstFile.Chmod(srcFI.Mode())
		if err != nil {
			_ = dstFile.Close()
			return err
		}
	}
	return dstFile.Close()
}

func verifySignature(content, sig, cert string) error {
	cmd := exec.Command(
		"openssl", "smime", "-verify",
		"-in", sig,
		"-inform", "der",
		"-content", content,
		"-CAfile", cert,
		"-purpose", "any",
	)
	var buf bytes.Buffer
	cmd.Stdout = &buf
	cmd.Stderr = &buf
	err := cmd.Run()
	if err != nil {
		return fmt.Errorf("%s\nsignature verification failed: %s\nCOMMAND LINE: %s", buf.Bytes(), err, strings.Join(cmd.Args, " "))
	}
	return nil
}

func findDefaultCert() string {
	certInCurrentDir, err := filepath.Abs("Swupd_Root.pem")
	if err != nil {
		log.Fatal(err)
	}

	defaultCerts := []string{
		certInCurrentDir,
		"/usr/share/clear/update-ca/Swupd_Root.pem",
	}

	for _, cert := range defaultCerts {
		if _, err := os.Stat(cert); err == nil {
			return cert
		}
	}

	return ""
}

repository: clearlinux/mixer-tools

repo_name: clearlinux/mixer-tools

gha_language: Go


text:
SUMMARY = "Xdelta is a tool for differential compression"
DESCRIPTION = "Open-source binary diff, differential compression tools, \
               VCDIFF (RFC 3284) delta compression."
HOMEPAGE = "http://xdelta.org/"
SECTION = "console/utils"

LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=393a5ca445f6965873eca0259a17f833"

SRC_URI = "git://github.com/jmacd/xdelta.git;branch=release3_1_apl;protocol=https"
SRCREV = "4b4aed71a959fe11852e45242bb6524be85d3709"
S = "${WORKDIR}/git/xdelta3"

inherit autotools

# Optional secondary compression
PACKAGECONFIG ??= ""
PACKAGECONFIG[lzma] = "--with-liblzma,--without-liblzma,xz"

BBCLASSEXTEND = "native nativesdk"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_language: BitBake

extension: bb


text:
@incollection{schaffert2008personliche,
 author = {Schaffert, Sandra and Kalz, Marco},
 title = {Persönliche Lernumgebungen: Grundlagen, Möglichkeiten und Herausforderungen eines neuen Konzeptes},
 year = {2008}
}

repository: mkalz/mkalz-academic

repo_name: mkalz/mkalz-academic

extension: bib


text:
/*
 *  Copyright 2019 Carnegie Technologies
 *
 *  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.
 */

extern "C"
{
#include "lwip/init.h"
#include "lwip/sys.h"
#include "lwip/timeouts.h"
}

#include <cassert>

#include "basic/Random.hpp"
#include "sys/Time.hpp"
#include "event/EventManager.hpp"

#include "LwipEventPoller.hpp"

using namespace Pravala;

/// @brief Returns a timestamp in milliseconds, this is only used by lwIP for time diffs
/// @return The current timestamp in milliseconds, this is only used by lwIP for time diffs
u32_t sys_now ( void )
{
    static Time startTime;

    if ( startTime.isZero() )
        startTime = EventManager::getCurrentTime();

    return ( uint32_t ) EventManager::getCurrentTime().getDiffInMilliSeconds ( startTime );
}

LwipEventPoller & LwipEventPoller::get()
{
    static LwipEventPoller * global = 0;

    if ( !global )
    {
        // lwip_init will randomize port numbers (using rand()). To make sure they are actually random,
        // let's initialize the random number generator. Note that if it has already been initialized
        // by something else - nothing will happen.

        Random::init();

        // This is only safe to call once. There is no deinit function.
        lwip_init();

        global = new LwipEventPoller();
    }

    return *global;
}

LwipEventPoller::LwipEventPoller(): _refCount ( 0 ), _timer ( *this ), _nextEvent ( 0 ), _running ( false )
{
}

void LwipEventPoller::start()
{
    _running = true;
    _nextEvent = 0;
    checkLwipTimer();
}

void LwipEventPoller::stop()
{
    _running = false;
    _nextEvent = 0;
    _timer.stop();
}

void LwipEventPoller::timerExpired ( Timer * timer )
{
    ( void ) timer;
    assert ( timer == &_timer );

    if ( !_running )
        return;

    const uint32_t delay = sys_timeouts_sleeptime();

    if ( delay < 1 )
    {
        // delay = 0 means that timers should run right away.
        sys_check_timeouts();
    }

    checkLwipTimer();
}

void LwipEventPoller::checkLwipTimer()
{
    if ( !_running )
        return;

    const uint32_t delay = sys_timeouts_sleeptime();

    if ( delay == 0xFFFFFFFFU )
    {
        // There are no timers. Nothing to do!
        return;
    }

    const uint32_t nextEvent = sys_now() + delay;

    if ( nextEvent == _nextEvent && _timer.isActive() )
        return;

    _nextEvent = nextEvent;
    _timer.start ( delay );
}

repository: severnt/pravala-toolkit

repo_name: severnt/pravala-toolkit


text:
SUMMARY = "YAML parser/emitter that supports roundtrip preservation of comments, seq/map flow style, and map key order."
AUTHOR = "Anthon van der Neut"

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE;md5=caf8bd842440b537c044e131785a4666"

PYPI_PACKAGE = "ruamel.yaml"

inherit pypi setuptools3

SRC_URI[md5sum] = "7d5a5b0a7621a1247b081cc8e4978354"
SRC_URI[sha256sum] = "412a6f5cfdc0525dee6a27c08f5415c7fd832a7afcb7a0ed7319628aed23d408"

do_install_prepend() {
    export RUAMEL_NO_PIP_INSTALL_CHECK=1
}


text:
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microcharts;
using SkiaSharp;
using Newtonsoft.Json.Linq;

namespace Microcharts.Matplotlib
{
    public class ChartBuilder<TChart> : IChartBuilder
        where TChart : Chart, new()
    {
        public static readonly SKColor[] DefinedColors =
		{
			SKColor.Parse("#266489"),
			SKColor.Parse("#68B9C0"),
			SKColor.Parse("#90D585"),
			SKColor.Parse("#F3C151"),
			SKColor.Parse("#F37F64"),
			SKColor.Parse("#424856"),
			SKColor.Parse("#8F97A4"),
			SKColor.Parse("#DAC096"),
			SKColor.Parse("#76846E"),
			SKColor.Parse("#DABFAF"),
			SKColor.Parse("#A65B69"),
			SKColor.Parse("#97A69D"),
		};

        public IList<int> Values { get; set; }

        public IList<string> Labels { get; set; }

        public IList<string> Colors { get; set; }

        public virtual Chart Build()
        {
            var labels = Labels;
            var values = Values;
            var colors = Colors;

            if (Labels.Count !=  Values.Count)
                throw new Exception($"{nameof(labels)} and {nameof(values)} have different length.");

            var entries = Enumerable.Range(0, labels.Count).Select(i =>
            {
                var color = SKColor.Empty;

                if (colors == null || colors.Count <= 0 || !SKColor.TryParse(colors[i], out color))
                {
                    color = DefinedColors[i % DefinedColors.Length];
                }

                return new Entry(values[i])
                {
                    Label = labels[i],
                    Color = color,
                    ValueLabel = values[i].ToString()
                };
            });

            var chart = new TChart();
            chart.Entries = entries;
            return chart;
        }
    }
}


text:
SECTION = "devel/chicken"
DESCRIPTION = "Functions useful for working with sets"
LICENSE = "GPL-3"
LIC_FILES_CHKSUM = "file://sets.meta;md5=cf133b67fd4742bbd3b94924b0d07ab1"
DEPENDS_append_class-cross = " chicken-egg-embedded-test-cross"
DEPENDS_append_class-crosssdk = " chicken-egg-embedded-test-crosssdk"
DEPENDS_append_class-nativesdk = " nativesdk-chicken-egg-embedded-test chicken-egg-embedded-test-crosssdk"
DEPENDS = " chicken-egg-embedded-test chicken-egg-embedded-test-cross"
RDEPENDS_${PN} = " chicken-egg-embedded-test"

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

SRC_URI[md5sum] = "f6950d75d058f91c370ed47ceb967371"
SRC_URI[sha256sum] = "85b9e8df7164253caa9b867be2ebaf43ed35f67511ce6e90c751f2661d0127a9"

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

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
# Copyright (C) 2015 Khem Raj <raj.khem@gmail.com>
# Released under the MIT license (see COPYING.MIT for the terms)

DESCRIPTION = "This library is minimum, easy-to-use, C implementation for xml file parsing."
HOMEPAGE = "http://www.libroxml.net"
LICENSE = "LGPL-2.1-only"
LIC_FILES_CHKSUM = "file://License.txt;md5=81cba52d2de829c8be3d167618e6b8b6"
SECTION = "libs"
DEPENDS = ""

SRC_URI = "http://download.libroxml.net/pool/v2.x/${PN}-${PV}.tar.gz"

SRC_URI[sha256sum] = "1da8f20b530eba4409f2b217587d2f1281ff5d9ba45b24aeac71b94c6c621b78"

inherit cmake pkgconfig
EXTRA_OECMAKE += "-DBUILD_TESTING=OFF"

repository: kraj/meta-openwrt

repo_name: kraj/meta-openwrt


text:
DESCRIPTION = "Camera Assistant aims to be an allround calculator for photographers & Cinematographers. \
It currently has the following features: \
  \
  * Depth of field calculator.  \
  * Inverse Depth of field calculator. (Calculate what aperture you need for a given depth/distance & lens) \
  * Field of view calculator.  \
  * Variants of the above, calculate distance to object or lens for a given field of view.  \
  * Database of TV cameras, Motion picture cameras and Still photography cameras."
SECTION = "opie/applications"

PRIORITY = "optional"
LICENSE = "GPL"
AUTHOR = "zaurus@bredband.net"
HOMEPAGE = "http://cameraassistant.sourceforge.net/"

SRC_URI = "${SOURCEFORGE_MIRROR}/cameraassistant/camera-assistant_0.2.0.tar.gz \
	  file://g++-3.4-compile-fixes.patch \
	  file://ca.desktop \
	  file://ca.png "

S = "${WORKDIR}/CameraAssistant"

APPNAME = "ca"
APPTYPE = "binary"
APPDESKTOP = "${WORKDIR}"

do_install() {
    install -d ${D}${palmtopdir}/pics/${APPNAME}/
    install -m 0644 ${WORKDIR}/ca.png ${D}${palmtopdir}/pics/${APPNAME}/
}

inherit opie

SRC_URI[md5sum] = "538e8d4691062524c4181da487d83250"
SRC_URI[sha256sum] = "9caa3e654af03e55582dd515bfcc9bf5aa93c9d22842af16a87a9a226ec581ed"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
#pragma once

#include "Header.h"

class Data : public std::vector<uint8_t>
{
public:
    using std::vector<uint8_t>::vector;
    int size() const { return static_cast<int>(std::vector<uint8_t>::size()); }
};

using DataList = std::vector<Data>;

class Sector
{
public:
    enum class Merge { Unchanged, Improved, NewData };

public:
    Sector(DataRate datarate, Encoding encoding, const Header& header = Header(), int gap3 = 0);
    bool operator==(const Sector& sector) const;

    Merge merge(Sector&& sector);

    bool has_data() const;
    bool has_good_data() const;
    bool has_gapdata() const;
    bool has_shortdata() const;
    bool has_badidcrc() const;
    bool has_baddatacrc() const;
    bool is_deleted() const;
    bool is_altdam() const;
    bool is_rx02dam() const;
    bool is_8k_sector() const;

    void set_badidcrc(bool bad = true);
    void set_baddatacrc(bool bad = true);
    void remove_data();
    void remove_gapdata(bool keep_crc = false);
    void limit_copies(int max_copies);

    int size() const;
    int data_size() const;

    const DataList& datas() const;
    DataList& datas();
    const Data& data_copy(int copy = 0) const;
    Data& data_copy(int copy = 0);

    Merge add(Data&& data, bool bad_crc = false, uint8_t dam = 0xfb);
    int copies() const;

    static int SizeCodeToRealSizeCode(int size);
    static int SizeCodeToLength(int size);

public:
    Header header{ 0,0,0,0 };               // cyl, head, sector, size
    DataRate datarate = DataRate::Unknown;  // 250Kbps
    Encoding encoding = Encoding::Unknown;  // MFM
    int offset = 0;                         // bitstream offset from index, in bits
    int gap3 = 0;                           // inter-sector gap size
    uint8_t dam = 0xfb;                     // data address mark

private:
    bool m_bad_id_crc = false;
    bool m_bad_data_crc = false;
    std::vector<Data> m_data{};         // copies of sector data
};
#pragma once

repository: simonowen/samdisk

repo_name: simonowen/samdisk

branch_name: refs/heads/main

extension: h


text:
@inproceedings{liu2021swin,
  title={Swin transformer: Hierarchical vision transformer using shifted windows},
  author={Liu, Ze and Lin, Yutong and Cao, Yue and Hu, Han and Wei, Yixuan and Zhang, Zheng and Lin, Stephen and Guo, Baining},
  booktitle={Proceedings of the IEEE/CVF International Conference on Computer Vision},
  pages={10012--10022},
  year={2021}
}

url: https://raw.githubusercontent.com/rbt-c/DL-NLP-Readings/82ca76e9184a3b00ac87129d99391477c85cfcd2/Bibtex/Swin Transformer - Hierarchical Vision Transformer using Shifted Windows.bib

repository: rbt-c/DL-NLP-Readings

repo_name: rbt-c/DL-NLP-Readings


text:
# fix behavior of base do_install_prepend - its overwrite ready to use uImage by uncompresses Image
require linux-bpp3.inc

# Mark archs/machines that this kernel supports
#DEFAULT_PREFERENCE = "-1"
#DEFAULT_PREFERENCE_mcx = "1"

# This was introduced to remove uImage from /boot and save 3MB
KERNEL_DROPIMAGE = "y"

PR = "r1"

S = "${WORKDIR}/linux-bpp3_v3.7.1_2"

SRC_URI = "https://github.com/jhofstee/linux/archive/bpp3_v3.7.1_2.zip"
SRC_URI[sha256sum] = "d95c7a558bdd526b382568b4d926cf25827259b5e6e6fbf96941b22b8f9b3dd5"