text:
package factory

import (
	"fmt"
	"reflect"
	"sync"
	"sync/atomic"
	"time"

	"github.com/sirupsen/logrus"

	kapi "k8s.io/api/core/v1"
	knet "k8s.io/api/networking/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	informerfactory "k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
)

// Handler represents an event handler and is private to the factory module
type Handler struct {
	cache.FilteringResourceEventHandler

	id uint64
	// tombstone is used to track the handler's lifetime. handlerAlive
	// indicates the handler can be called, while handlerDead indicates
	// it has been scheduled for removal and should not be called.
	// tombstone should only be set using atomic operations since it is
	// used from multiple goroutines.
	tombstone uint32
}

type informer struct {
	sync.Mutex
	oType    reflect.Type
	inf      cache.SharedIndexInformer
	handlers map[uint64]*Handler
}

func (i *informer) forEachHandler(obj interface{}, f func(h *Handler)) {
	i.Lock()
	defer i.Unlock()

	objType := reflect.TypeOf(obj)
	if objType != i.oType {
		logrus.Errorf("object type %v did not match expected %v", objType, i.oType)
		return
	}

	for _, handler := range i.handlers {
		// Only run alive handlers
		if !atomic.CompareAndSwapUint32(&handler.tombstone, handlerDead, handlerDead) {
			f(handler)
		}
	}
}

// WatchFactory initializes and manages common kube watches
type WatchFactory struct {
	// Must be first member in the struct due to Golang ARM/x86 32-bit
	// requirements with atomic accesses
	handlerCounter uint64

	iFactory  informerfactory.SharedInformerFactory
	informers map[reflect.Type]*informer
	stopChan  chan struct{}
}

const (
	resyncInterval        = 12 * time.Hour
	handlerAlive   uint32 = 0
	handlerDead    uint32 = 1
)

func newInformer(oType reflect.Type, sharedInformer cache.SharedIndexInformer) *informer {
	return &informer{
		oType:    oType,
		inf:      sharedInformer,
		handlers: make(map[uint64]*Handler),
	}
}

var (
	podType       reflect.Type = reflect.TypeOf(&kapi.Pod{})
	serviceType   reflect.Type = reflect.TypeOf(&kapi.Service{})
	endpointsType reflect.Type = reflect.TypeOf(&kapi.Endpoints{})
	policyType    reflect.Type = reflect.TypeOf(&knet.NetworkPolicy{})
	namespaceType reflect.Type = reflect.TypeOf(&kapi.Namespace{})
	nodeType      reflect.Type = reflect.TypeOf(&kapi.Node{})
)

// NewWatchFactory initializes a new watch factory
func NewWatchFactory(c kubernetes.Interface, stopChan chan struct{}) (*WatchFactory, error) {
	// resync time is 12 hours, none of the resources being watched in ovn-kubernetes have
	// any race condition where a resync may be required e.g. cni executable on node watching for
	// events on pods and assuming that an 'ADD' event will contain the annotations put in by
	// ovnkube master (currently, it is just a 'get' loop)
	// the downside of making it tight (like 10 minutes) is needless spinning on all resources
	wf := &WatchFactory{
		iFactory:  informerfactory.NewSharedInformerFactory(c, resyncInterval),
		informers: make(map[reflect.Type]*informer),
		stopChan:  stopChan,
	}

	// Create shared informers we know we'll use
	wf.informers[podType] = newInformer(podType, wf.iFactory.Core().V1().Pods().Informer())
	wf.informers[serviceType] = newInformer(serviceType, wf.iFactory.Core().V1().Services().Informer())
	wf.informers[endpointsType] = newInformer(endpointsType, wf.iFactory.Core().V1().Endpoints().Informer())
	wf.informers[policyType] = newInformer(policyType, wf.iFactory.Networking().V1().NetworkPolicies().Informer())
	wf.informers[namespaceType] = newInformer(namespaceType, wf.iFactory.Core().V1().Namespaces().Informer())
	wf.informers[nodeType] = newInformer(nodeType, wf.iFactory.Core().V1().Nodes().Informer())

	for _, informer := range wf.informers {
		informer.inf.AddEventHandler(wf.newFederatedHandler(informer))
	}

	wf.iFactory.Start(stopChan)
	for oType, synced := range wf.iFactory.WaitForCacheSync(stopChan) {
		if !synced {
			return nil, fmt.Errorf("error in syncing cache for %v informer", oType)
		}
	}

	return wf, nil
}

// Shutdown removes all handlers
func (wf *WatchFactory) Shutdown() {
	close(wf.stopChan)
	for _, inf := range wf.informers {
		inf.Lock()
		defer inf.Unlock()
		for _, handler := range inf.handlers {
			if atomic.CompareAndSwapUint32(&handler.tombstone, handlerAlive, handlerDead) {
				delete(inf.handlers, handler.id)
			}
		}
	}
}

func (wf *WatchFactory) newFederatedHandler(inf *informer) cache.ResourceEventHandlerFuncs {
	return cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			inf.forEachHandler(obj, func(h *Handler) {
				logrus.Debugf("running %v ADD event for handler %d", inf.oType, h.id)
				h.OnAdd(obj)
			})
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			inf.forEachHandler(newObj, func(h *Handler) {
				logrus.Debugf("running %v UPDATE event for handler %d", inf.oType, h.id)
				h.OnUpdate(oldObj, newObj)
			})
		},
		DeleteFunc: func(obj interface{}) {
			if inf.oType != reflect.TypeOf(obj) {
				tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
				if !ok {
					logrus.Errorf("couldn't get object from tombstone: %+v", obj)
					return
				}
				obj = tombstone.Obj
				objType := reflect.TypeOf(obj)
				if inf.oType != objType {
					logrus.Errorf("expected tombstone object resource type %v but got %v", inf.oType, objType)
					return
				}
			}
			inf.forEachHandler(obj, func(h *Handler) {
				logrus.Debugf("running %v DELETE event for handler %d", inf.oType, h.id)
				h.OnDelete(obj)
			})
		},
	}
}

func getObjectMeta(objType reflect.Type, obj interface{}) (*metav1.ObjectMeta, error) {
	switch objType {
	case podType:
		if pod, ok := obj.(*kapi.Pod); ok {
			return &pod.ObjectMeta, nil
		}
	case serviceType:
		if service, ok := obj.(*kapi.Service); ok {
			return &service.ObjectMeta, nil
		}
	case endpointsType:
		if endpoints, ok := obj.(*kapi.Endpoints); ok {
			return &endpoints.ObjectMeta, nil
		}
	case policyType:
		if policy, ok := obj.(*knet.NetworkPolicy); ok {
			return &policy.ObjectMeta, nil
		}
	case namespaceType:
		if namespace, ok := obj.(*kapi.Namespace); ok {
			return &namespace.ObjectMeta, nil
		}
	case nodeType:
		if node, ok := obj.(*kapi.Node); ok {
			return &node.ObjectMeta, nil
		}
	}
	return nil, fmt.Errorf("cannot get ObjectMeta from type %v", objType)
}

func (wf *WatchFactory) addHandler(objType reflect.Type, namespace string, lsel *metav1.LabelSelector, funcs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	inf, ok := wf.informers[objType]
	if !ok {
		return nil, fmt.Errorf("unknown object type %v", objType)
	}

	sel, err := metav1.LabelSelectorAsSelector(lsel)
	if err != nil {
		return nil, fmt.Errorf("error creating label selector: %v", err)
	}

	filterFunc := func(obj interface{}) bool {
		if namespace == "" && lsel == nil {
			// Unfiltered handler
			return true
		}
		meta, err := getObjectMeta(objType, obj)
		if err != nil {
			logrus.Errorf("watch handler filter error: %v", err)
			return false
		}
		if namespace != "" && meta.Namespace != namespace {
			return false
		}
		if lsel != nil && !sel.Matches(labels.Set(meta.Labels)) {
			return false
		}
		return true
	}

	// Process existing items as a set so the caller can clean up
	// after a restart or whatever
	existingItems := inf.inf.GetStore().List()
	if processExisting != nil {
		items := make([]interface{}, 0)
		for _, obj := range existingItems {
			if filterFunc(obj) {
				items = append(items, obj)
			}
		}
		processExisting(items)
	}

	handlerID := atomic.AddUint64(&wf.handlerCounter, 1)

	inf.Lock()
	defer inf.Unlock()

	handler := &Handler{
		cache.FilteringResourceEventHandler{
			FilterFunc: filterFunc,
			Handler:    funcs,
		},
		handlerID,
		handlerAlive,
	}
	inf.handlers[handlerID] = handler
	logrus.Debugf("added %v event handler %d", objType, handlerID)

	// Send existing items to the handler's add function; informers usually
	// do this but since we share informers, it's long-since happened so
	// we must emulate that here
	for _, obj := range existingItems {
		inf.handlers[handlerID].OnAdd(obj)
	}

	return handler, nil
}

func (wf *WatchFactory) removeHandler(objType reflect.Type, handler *Handler) error {
	inf, ok := wf.informers[objType]
	if !ok {
		return fmt.Errorf("tried to remove unknown object type %v event handler", objType)
	}

	if !atomic.CompareAndSwapUint32(&handler.tombstone, handlerAlive, handlerDead) {
		// Already removed
		return fmt.Errorf("tried to remove already removed object type %v event handler %d", objType, handler.id)
	}

	logrus.Debugf("sending %v event handler %d for removal", objType, handler.id)

	go func() {
		inf.Lock()
		defer inf.Unlock()
		if _, ok := inf.handlers[handler.id]; ok {
			// Remove the handler
			delete(inf.handlers, handler.id)
			logrus.Debugf("removed %v event handler %d", objType, handler.id)
		} else {
			logrus.Warningf("tried to remove unknown object type %v event handler %d", objType, handler.id)
		}
	}()

	return nil
}

// AddPodHandler adds a handler function that will be executed on Pod object changes
func (wf *WatchFactory) AddPodHandler(handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(podType, "", nil, handlerFuncs, processExisting)
}

// AddFilteredPodHandler adds a handler function that will be executed when Pod objects that match the given filters change
func (wf *WatchFactory) AddFilteredPodHandler(namespace string, lsel *metav1.LabelSelector, handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(podType, namespace, lsel, handlerFuncs, processExisting)
}

// RemovePodHandler removes a Pod object event handler function
func (wf *WatchFactory) RemovePodHandler(handler *Handler) error {
	return wf.removeHandler(podType, handler)
}

// AddServiceHandler adds a handler function that will be executed on Service object changes
func (wf *WatchFactory) AddServiceHandler(handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(serviceType, "", nil, handlerFuncs, processExisting)
}

// RemoveServiceHandler removes a Service object event handler function
func (wf *WatchFactory) RemoveServiceHandler(handler *Handler) error {
	return wf.removeHandler(serviceType, handler)
}

// AddEndpointsHandler adds a handler function that will be executed on Endpoints object changes
func (wf *WatchFactory) AddEndpointsHandler(handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(endpointsType, "", nil, handlerFuncs, processExisting)
}

// AddFilteredEndpointsHandler adds a handler function that will be executed when Endpoint objects that match the given filters change
func (wf *WatchFactory) AddFilteredEndpointsHandler(namespace string, handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(endpointsType, namespace, nil, handlerFuncs, processExisting)
}

// RemoveEndpointsHandler removes a Endpoints object event handler function
func (wf *WatchFactory) RemoveEndpointsHandler(handler *Handler) error {
	return wf.removeHandler(endpointsType, handler)
}

// AddPolicyHandler adds a handler function that will be executed on NetworkPolicy object changes
func (wf *WatchFactory) AddPolicyHandler(handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(policyType, "", nil, handlerFuncs, processExisting)
}

// RemovePolicyHandler removes a NetworkPolicy object event handler function
func (wf *WatchFactory) RemovePolicyHandler(handler *Handler) error {
	return wf.removeHandler(policyType, handler)
}

// AddNamespaceHandler adds a handler function that will be executed on Namespace object changes
func (wf *WatchFactory) AddNamespaceHandler(handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(namespaceType, "", nil, handlerFuncs, processExisting)
}

// AddFilteredNamespaceHandler adds a handler function that will be executed when Namespace objects that match the given filters change
func (wf *WatchFactory) AddFilteredNamespaceHandler(namespace string, lsel *metav1.LabelSelector, handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(namespaceType, namespace, lsel, handlerFuncs, processExisting)
}

// RemoveNamespaceHandler removes a Namespace object event handler function
func (wf *WatchFactory) RemoveNamespaceHandler(handler *Handler) error {
	return wf.removeHandler(namespaceType, handler)
}

// AddNodeHandler adds a handler function that will be executed on Node object changes
func (wf *WatchFactory) AddNodeHandler(handlerFuncs cache.ResourceEventHandler, processExisting func([]interface{})) (*Handler, error) {
	return wf.addHandler(nodeType, "", nil, handlerFuncs, processExisting)
}

// RemoveNodeHandler removes a Node object event handler function
func (wf *WatchFactory) RemoveNodeHandler(handler *Handler) error {
	return wf.removeHandler(nodeType, handler)
}

repository: markmc/ovn-kubernetes

repo_name: markmc/ovn-kubernetes


text:
DESCRIPTION = "A mode switching tool for controlling 'flip flop' (multiple device) USB gear"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=94d55d512a9ba36caa9b7df079bae19f"

inherit autotools

DEPENDS = "libusb1"

SRC_URI = "http://www.draisberghof.de/usb_modeswitch/usb-modeswitch-${PV}.tar.bz2"
SRC_URI[md5sum] = "e48d4419d0574d342bb183f7465556d0"
SRC_URI[sha256sum] = "4706c9cfe825263e189f55730ea3d1d8634aeb15645a1098532e946e770f7f95"

EXTRA_OEMAKE = "TCL=${bindir}/tclsh"

FILES_${PN} = "${bindir} ${sysconfdir} ${base_libdir}/udev/usb_modeswitch ${sbindir} ${localstatedir}/lib/usb_modeswitch"
RDEPENDS_${PN} = "tcl"
RRECOMMENDS_${PN} = "usb-modeswitch-data"

license: MIT

repository: ExorEmbedded/exor-workspace

license_type: permissive

repo_name: ExorEmbedded/exor-workspace

gha_language: Python

extension: bb


text:
@inproceedings{pichl:sowemine:2015,
 author = {Martin Pichl and Eva Zangerle and Günther Specht},
 booktitle = {Current Trends in Web Engineering, 15th International Conference, ICWE 2015 Workshops (Revised Selected Papers)},
 doi = {10.1007/978-3-319-24800-4_14},
 pages = {163--174},
 publisher = {Springer},
 title = {#nowplaying on #Spotify: Leveraging Spotify Information on Twitter for Artist Recommendations},
 year = {2015}
}

branch_name: refs/heads/main

extension: bib


text:
DESCRIPTION = "Python gtksourceview Bindings"
SECTION = "devel/python"
HOMEPAGE = "http://projects.gnome.org/gtksourceview/pygtksourceview.html"
PRIORITY = "optional"
DEPENDS = "gtksourceview2 python-pygtk"
SRCNAME = "pygtksourceview"
LICENSE = "LGPL"
PR = "r0"

MAJ_VER = "${@bb.data.getVar('PV',d,1).split('.')[0]}.${@bb.data.getVar('PV',d,1).split('.')[1]}"
SRC_URI = "ftp://ftp.gnome.org/pub/gnome/sources/pygtksourceview/${MAJ_VER}/${SRCNAME}-${PV}.tar.bz2"

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

inherit autotools pkgconfig distutils-base

EXTRA_OECONF += "--with-python-includes=${STAGING_INCDIR}/../"

repository: demsey/openembedded

repo_name: demsey/openembedded

branch_name: HEAD


text:
package backpacktf

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

func TestInventoryValues(t *testing.T) {
	config.Load()
	if Authenticate() != nil {
		t.Skip("No token available")
		return
	}
	v, e := InventoryValues(76561197961279983)
	assert.NoError(t, e)
	assert.True(t, v.Value > 0)
	assert.True(t, v.MarketValue > 0)
}

branch_name: refs/heads/master

extension: go


text:
package examples

// Agent is a sample DTO for DB records.
type Agent struct {
	AgentCode   string `db:"agent_code"`
	WorkingArea string `db:"working_area"`
	AgentName   string `db:"agent_name"`
	Commission  string `db:"commission"`
	PhoneNo     string `db:"phone_no"`
	Country     string `db:"country"`
}

repository: Cybernostics/cntest

repo_name: Cybernostics/cntest


text:
// Copyright (c) The Tellor Authors.
// Licensed under the MIT License.

package main

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

	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/cmd/utils"
	"github.com/ethereum/go-ethereum/common/compiler"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/nanmu42/etherscan-api"
	"github.com/pkg/errors"
	"github.com/tellor-io/telliot/pkg/config"
	"github.com/tellor-io/telliot/pkg/contracts"
)

func main() {
	log.SetFlags(log.Ltime | log.Lshortfile | log.Lmsgprefix)

	f, err := ioutil.ReadFile(filepath.Join("configs", "config.json"))
	if err != nil {
		log.Fatal(err)
	}

	cfg := config.Config{}

	if err := json.Unmarshal(f, &cfg); err != nil {
		log.Fatal(err)
	}

	contractsFolder := filepath.Join("scripts", "bindings", "contracts")
	uinswapContractFolder := filepath.Join(contractsFolder, "uniswap")
	balancerContractFolder := filepath.Join(contractsFolder, "balancer")
	if err := os.RemoveAll(contractsFolder); err != nil {
		log.Fatal(err)
	}
	if err := os.MkdirAll(contractsFolder, os.ModePerm); err != nil {
		log.Fatal(err)
	}
	if err := os.Mkdir(balancerContractFolder, os.ModePerm); err != nil {
		log.Fatal(err)
	}
	if err := os.Mkdir(uinswapContractFolder, os.ModePerm); err != nil {
		log.Fatal(err)
	}

	generate(contracts.TellorRinkebyAddress, filepath.Join(contractsFolder, "proxy.sol"), "v0.5.16")
	log.Println("Generated proxy contract in:", contractsFolder)
	time.Sleep(5 * time.Second)
	// TODO how to detect that the proxy has changed and this needs updating.
	generate("0x7e05e8a675e649261acc19423db34dd4826f9a98", filepath.Join(contractsFolder, "master.sol"), "v0.5.16")
	log.Println("Generated master contract in:", contractsFolder)
	time.Sleep(5 * time.Second)
	// Generating Balancer core pool factory contract.
	generate("0x9C84391B443ea3a48788079a5f98e2EaD55c9309", balancerContractFolder, "")
	log.Println("Generated balancer contract in:", balancerContractFolder)
	time.Sleep(5 * time.Second)
	// Generating Uniswap factory contract.
	generate("0x03E6c12eF405AC3F642B9184eDed8E1322de1a9e", filepath.Join(uinswapContractFolder, "uniswap.sol"), "")
	log.Println("Generated balancer contract in:", uinswapContractFolder)

}

func generate(address string, contractFPath string, solcVersion string) {
	filename := filepath.Base(contractFPath)
	pkgName := strings.TrimSuffix(filename, filepath.Ext(filename))
	client := etherscan.New(etherscan.Rinkby, "")
	src, err := client.ContractSource(address)
	if err != nil {
		log.Fatal(err)
	}

	var contractFiles = []string{contractFPath}
	var codes map[string]Code
	var ok bool

	if codes, ok = isJSONString(src[0].SourceCode); ok {
		contractFiles = []string{}
		for fileName := range codes {
			filePath := filepath.Join(contractFPath, fileName)
			contractFiles = append(contractFiles, filePath)
			if err := ioutil.WriteFile(filePath, []byte(codes[fileName].Content), os.ModePerm); err != nil {
				log.Fatal(err)
			}
		}

	} else if err := ioutil.WriteFile(contractFPath, []byte(src[0].SourceCode), os.ModePerm); err != nil {
		log.Fatal(err)
	}

	// Get solc version from etherscan if empty.
	if solcVersion == "" {
		solcVersion = strings.Split(src[0].CompilerVersion, "+")[0]
	}
	solcPath, err := downloadSolc(solcVersion)
	if err != nil {
		log.Fatal(err)
	}

	contracts, err := compiler.CompileSolidity(solcPath, contractFiles...)
	if err != nil {
		utils.Fatalf("Failed to build Solidity contract: %v", err)
	}
	var (
		abis  []string
		types []string
		bins  []string
		sigs  []map[string]string
		libs  = make(map[string]string)
	)
	// Gather all non-excluded contract for binding
	for name, contract := range contracts {
		abi, err := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
		if err != nil {
			log.Fatal(err)
		}
		abis = append(abis, string(abi))
		bins = append(bins, contract.Code)
		sigs = append(sigs, contract.Hashes)
		nameParts := strings.Split(name, ":")
		types = append(types, nameParts[len(nameParts)-1])

		libPattern := crypto.Keccak256Hash([]byte(name)).String()[2:36]
		libs[libPattern] = nameParts[len(nameParts)-1]
	}

	code, err := bind.Bind(types, abis, bins, sigs, pkgName, bind.LangGo, libs, map[string]string{})
	if err != nil {
		log.Fatal(err)
	}

	pkgFolder := filepath.Join("pkg", "contracts", pkgName)
	pkgPath := filepath.Join(pkgFolder, pkgName+".go")

	os.RemoveAll(pkgFolder)
	if err := os.MkdirAll(pkgFolder, os.ModePerm); err != nil {
		log.Fatal(err)
	}

	if err := ioutil.WriteFile(pkgPath, []byte(code), os.ModePerm); err != nil {
		log.Fatal(err)
	}
}

// downloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into memory.
func downloadFile(filepath string, url string) error {

	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return errors.Wrap(err, "gettings the file")
	}
	defer resp.Body.Close()

	// Create the file
	out, err := os.Create(filepath)
	if err != nil {
		return errors.Wrap(err, "creating destination file")
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	return errors.Wrap(err, "writing the file")
}

// downloadSolc will download @solcVersion of the Solc compiler to tmp/solc directory.
func downloadSolc(solcVersion string) (string, error) {
	solcDir := filepath.Join("tmp", "solc")
	if err := os.MkdirAll(solcDir, os.ModePerm); err != nil {
		return "", err
	}
	solcPath := filepath.Join(solcDir, solcVersion)
	if _, err := os.Stat(solcPath); os.IsNotExist(err) {
		log.Println("downloading solc")
		err = downloadFile(solcPath, fmt.Sprintf("https://github.com/ethereum/solidity/releases/download/%s/solc-static-linux", solcVersion))
		if err != nil {
			return "", err
		}
		if err := os.Chmod(solcPath, os.ModePerm); err != nil {
			return "", err
		}
	}
	return solcPath, nil
}

type Code struct {
	Content string
}

func isJSONString(s string) (map[string]Code, bool) {
	var out map[string]Code
	ok := json.Unmarshal([]byte(s), &out) == nil
	return out, ok
}

repository: TheRocketCat/telliot

repo_name: TheRocketCat/telliot

gha_license_id: MIT

gha_language: Go


text:
package main

import (
	"fmt"
	"os/exec"
	"syscall"
)

func main3(){

	//config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")

	//err := syscall.Exec("/sbin/resolvconf", []string{}, []string{})

	cmd := exec.Command("/sbin/resolvconf", "-u")
	//bytes := make([]byte, 10000)
	out, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Errorf("err=%v", err)
	}
	fmt.Printf("pid=%d, exited=%t, exitCode=%d, out=%+v", cmd.ProcessState.Pid(), cmd.ProcessState.Exited(),
		cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus(), string(out))

	//for _, s := range config.Servers {
	//	fmt.Println(s)
	//}

}

repository: logward/dns-proxy-server

repo_name: logward/dns-proxy-server


text:
;
; Copyright (c) Microsoft Corporation.  All rights reserved.
;
;
; Use of this sample source code is subject to the terms of the Microsoft
; license agreement under which you licensed this sample source code. If
; you did not accept the terms of the license agreement, you are not
; authorized to use this sample source code. For the terms of the license,
; please see the license agreement between you and Microsoft or, if applicable,
; see the LICENSE.RTF on your install media or the root of your tools installation.
; THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
;
;******************************************************************************
; TITLE:        BOOT.BIB
;
;
; Windows CE BIOS Bootloader Source Module
;
;******************************************************************************

MEMORY
;
;   The text address (0x1000) is dictated by the boot sector code which
;       loads this image at 0000:1000h.  All addresses should be under 64KB to
;       be compatible with x86 real-mode.
;
;   Name    Start      Size      Type
;   ------- --------  --------   ----
    BLDR    00001000  00005000   RAMIMAGE    ; Size should be evenly divisible by 512b.
    BPB     00007C00  00000070   RESERVED    ; BIOS parameter block data and DPT.
    VESA    00008000  00001000   RESERVED    ; VESA work RAM.
;   RAM     00009000  00001900   RAM
;   SCACHE  0000A900  00000200   RESERVED    ; Sector cache.
;   STACK   0000AB00  00001500   RESERVED    ; Stack base will be set to 0x7FFC to leave 0x8000 free.
    RAM     00009000  00002200   RAM
    SCACHE  0000B200  00000200   RESERVED    ; This is where the FAT sector chains are read.
    STACK   0000B400  00001500   RESERVED    ; The SP is set in Startup.asm.
    READBUF 0000C900  00003700   RESERVED    ; Data from disk is read into this buffer first.

CONFIG

        ; Autosize image to convert any unused RAMIMAGE area to RAM area
    AUTOSIZE=OFF
        ; Don't compress writable sections
    COMPRESSION=OFF
        ; Don't include profiling information
    PROFILE=OFF
        ; Move kernel-writable sections to start of RAM
    KERNELFIXUPS=ON
        ; ROM info
    ROMSTART=00001000
    ROMSIZE=05000
    ROMWIDTH=32
    ROMOFFSET=0

MODULES
;
;   Name            Path                                            Memory Type
;   --------------  ----------------------------------------------  -----------
    nk.exe          $(SG_OUTPUT_ROOT)\platform\$(_TGTPLAT)\target\$(_TGTCPU)\$(WINCEDEBUG)\bldr_fat32.exe                                                                         BLDR


text:
package happytrip

import (
	"github.com/bububa/opentaobao/core"
	"github.com/bububa/opentaobao/model/happytrip"
)

// AlibabaHappytripTaxiOrderCancel 取消叫车
// alibaba.happytrip.taxi.order.cancel
//
// 取消叫车订单,行程中的订单不能取消
func AlibabaHappytripTaxiOrderCancel(clt *core.SDKClient, req *happytrip.AlibabaHappytripTaxiOrderCancelAPIRequest, session string) (*happytrip.AlibabaHappytripTaxiOrderCancelAPIResponse, error) {
	var resp happytrip.AlibabaHappytripTaxiOrderCancelAPIResponse
	err := clt.Post(req, &resp, session)
	if err != nil {
		return nil, err
	}
	return &resp, nil
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao


text:
Wickham et al., (2019). Welcome to the tidyverse. Journal of Open Source Software,
  4(43), 1686, https://doi.org/10.21105/joss.01686

repository: mackenziequ/blogs

repo_name: mackenziequ/blogs


text:
@article{Čufar2020,
  doi = {10.21105/joss.02614},
  url = {https://doi.org/10.21105/joss.02614},
  year = {2020},
  publisher = {The Open Journal},
  volume = {5},
  number = {54},
  pages = {2614},
  author = {Matija Čufar},
  title = {Ripserer.jl: flexible and efficient persistent homology computation in Julia},
  journal = {Journal of Open Source Software}
}


text:
//Copyright (c) 2013, The Impendulo Authors
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification,
//are permitted provided that the following conditions are met:
//
//  Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//
//  Redistributions in binary form must reproduce the above copyright notice, this
//  list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
//ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package pmd

import (
	"encoding/gob"
	"encoding/xml"
	"fmt"

	"github.com/godfried/impendulo/tool"
	"github.com/godfried/impendulo/tool/result"

	"html/template"

	"labix.org/v2/mgo/bson"

	"sort"
	"strings"
)

type (
	//Report is the result of running PMD on a Java source file.
	Report struct {
		Id      bson.ObjectId
		Version string  `xml:"version,attr"`
		Files   []*File `xml:"file"`
		Errors  int
	}

	//File defines a source file analysed by PMD and all of the errors
	//found in it.
	File struct {
		Name       string     `xml:"name,attr"`
		Violations Violations `xml:"violation"`
	}

	//Violations
	Violations []*Violation

	//Violation describes an error detected by PMD.
	Violation struct {
		Id          bson.ObjectId
		Begin       int          `xml:"beginline,attr"`
		End         int          `xml:"endline,attr"`
		Rule        string       `xml:"rule,attr"`
		RuleSet     string       `xml:"ruleset,attr"`
		Url         template.URL `xml:"externalInfoUrl,attr"`
		Priority    int          `xml:"priority,attr"`
		Description string       `xml:",innerxml"`
		//The locations where the error was detected.
		Starts, Ends []int
	}
)

func init() {
	gob.Register(new(Report))
}

//NewReport generates a new Report from XML generated by PMD.
func NewReport(id bson.ObjectId, data []byte) (*Report, error) {
	var r *Report
	if e := xml.Unmarshal(data, &r); e != nil {
		return nil, tool.NewXMLError(e, "pmd/pmdResult.go")
	}
	r.Id = id
	r.Errors = 0
	for _, f := range r.Files {
		r.Errors += len(f.Violations)
		f.CompressViolations()
	}
	return r, nil
}

func (r *Report) Lines() []*result.Line {
	lines := make([]*result.Line, 0, len(r.Files)*10)
	for _, f := range r.Files {
		for _, v := range f.Violations {
			for i, s := range v.Starts {
				lines = append(lines, &result.Line{Title: v.Rule, Description: v.Description, Start: s, End: v.Ends[i]})
			}
		}
	}
	return lines
}

//Success is true if no errors were found.
func (r *Report) Success() bool {
	return r.Errors == 0
}

//String
func (r *Report) String() string {
	if r.Files == nil {
		return fmt.Sprintf("Report{ Errors: %d\n.", r.Errors)
	}
	s := fmt.Sprintf("Report{ Errors: %d\nFiles:\n.", r.Errors)
	for _, f := range r.Files {
		s += f.String()
	}
	return s + "}\n"
}

//File retrieves a File whose name ends with the provided name.
func (r *Report) File(name string) *File {
	for _, f := range r.Files {
		if strings.HasSuffix(f.Name, name) {
			return f
		}
	}
	return nil
}

//CompressViolations packs all Violations of the same
//type into a single Violation by storing their location seperately.
func (f *File) CompressViolations() {
	indices := make(map[string]int)
	c := make(Violations, 0, len(f.Violations))
	for _, v := range f.Violations {
		i, ok := indices[v.Rule]
		if !ok {
			//Only store if the Violation type has not been stored yet.
			v.Starts = make([]int, 0, len(f.Violations))
			v.Ends = make([]int, 0, len(f.Violations))
			v.Id = bson.NewObjectId()
			c = append(c, v)
			i = len(c) - 1
			indices[v.Rule] = i
		}
		//Add Violation location.
		c[i].Starts = append(c[i].Starts, v.Begin)
		c[i].Ends = append(c[i].Ends, v.End)
	}
	sort.Sort(c)
	f.Violations = c
}

//String
func (f *File) String() string {
	return fmt.Sprintf("File{ Name: %s\n}\n.", f.Name)
}

func (v Violations) Len() int {
	return len(v)
}

func (v Violations) Swap(i, j int) {
	v[i], v[j] = v[j], v[i]
}

func (v Violations) Less(i, j int) bool {
	return v[i].Rule < v[j].Rule
}

repository: godfried/impendulo

repo_name: godfried/impendulo


text:
// Copyright 2013 Sonia Keys
// License: MIT

// Accuracy: Chapter 2, About accuracy.
//
// This is a documentation only package.  The book has good advice for
// program authors.
//
// In general, packages use the Go float64 type throughout.  Float64 implements
// IEEE-754 64 bit floating point numbers fairly closely.  See the Go
// programming language reference and the IEEE-754 reference for more details.
//
// The example functions in the library make heavy use of the external package
// github.com/soniakeys/sexagesimal for formatted output.  That package has
// features for recognizing the accuracy limitations of a float64 and
// and indicating accuracy limits in formatted output.  See sexagesimal package
// documentation for more details.
package accuracy


text:
require tegra-binaries-${PV}.inc
require tegra-shared-binaries.inc

DESCRIPTION = "NVIDIA sensor HAL daemon"

COMPATIBLE_MACHINE = "(tegra)"

do_configure() {
    tar -C ${B} -x -f ${S}/nv_tegra/nvidia_drivers.tbz2 usr/sbin/nvs-service
}

do_compile[noexec] = "1"

do_install() {
    install -d ${D}${sbindir}
    install -m 0755 ${B}/usr/sbin/nvs-service ${D}${sbindir}/
}

PACKAGES = "${PN}"
FILES_${PN} = "${sbindir} ${sysconfdir}"
RDEPENDS_${PN} = "bash tegra-libraries"
INSANE_SKIP_${PN} = "ldflags"

PACKAGE_ARCH = "${SOC_FAMILY_PKGARCH}"

repository: b-man/meta-tegra

repo_name: b-man/meta-tegra


text:
package sqlr

import "github.com/jjeffery/sqlr/private/column"

// Schema contains information about the database that is used
// when generating SQL statements.
//
// Information stored in the schema includes the SQL dialect,
// and the naming convention used to convert Go struct field names
// into database column names.
//
// Although the zero value schema can be used and represents a database schema
// with default values, it is more common to use the NewSchema function to
// create a schema with one or more options.
//
// A schema maintains an internal cache, which is used to store details of
// frequently called SQL commands for improved performance.
//
// A schema can be inexpensively cloned to provide a deep copy.
// This can occasionally be useful to define a common schema for a database,
// and then create copies to handle naming rules that are specific to a particular
// table, or a particular group of tables.
type Schema struct {
	dialect    Dialect
	convention NamingConvention
	cache      stmtCache
	fieldMap   *fieldMap
	identMap   *identMap
	key        string
}

// NewSchema creates a schema with options.
func NewSchema(opts ...SchemaOption) *Schema {
	schema := &Schema{}
	for _, opt := range opts {
		if opt != nil {
			opt(schema)
		}
	}
	return schema
}

// columnNamer returns an object that implements the columnNamer interface
// for the schema. The column namer returns the column name based on the
// list of field name/column name mappings for the schema, and the naming
// convention.
func (s *Schema) columnNamer() columnNamer {
	return columnNamerFunc(func(col *column.Info) string {
		if s.fieldMap != nil {
			if columnName, ok := s.fieldMap.lookup(col.FieldNames); ok {
				// If the field map returns an empty string, this means to
				// fallback to the naming convention. This provides a mechanism
				// to override any naming from a previous schema.
				if columnName != "" {
					return columnName
				}
			}
		}
		convention := s.convention
		if convention == nil {
			convention = defaultNamingConvention
		}
		return col.Path.ColumnName(convention, s.key)
	})
}

// renameIdent implements the identRenamer interface.
func (s *Schema) renameIdent(ident string) (string, bool) {
	if s.identMap == nil {
		return "", false
	}
	return s.identMap.lookup(ident)
}

// getDialect returns the dialect for the schema. The aim is to make
// and empty Schema usable, so this method is necessary to ensure that
// a non-nil dialect is always available.
func (s *Schema) getDialect() Dialect {
	if s.dialect != nil {
		return s.dialect
	}
	return DefaultDialect
}

// Clone creates a copy of the schema, with options applied.
func (s *Schema) Clone(opts ...SchemaOption) *Schema {
	clone := &Schema{
		dialect:    s.dialect,
		convention: s.convention,
		fieldMap:   newFieldMap(s.fieldMap),
		identMap:   newIdentMap(s.identMap),
		key:        s.key,
	}
	for _, opt := range opts {
		opt(clone)
	}
	return clone
}

// Prepare creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the returned
// statement.
func (s *Schema) Prepare(row interface{}, query string) (*Stmt, error) {
	// determine row type to use for statement
	rowType, err := inferRowType(row)
	if err != nil {
		return nil, err
	}

	// convert common shorthand SQL notations
	if query, err = checkSQL(query); err != nil {
		return nil, err
	}

	// attempt to get statement from the schema's statement cache
	stmt, ok := s.cache.lookup(rowType, query)
	if !ok {
		// build statement from scratch
		stmt, err = newStmt(s.getDialect(), s.columnNamer(), s, rowType, query)
		if err != nil {
			return nil, err
		}
		// add to schema's statement cache, returning the statement in the
		// cache -- this is just in case another goroutine has beaten us to it
		stmt = s.cache.set(rowType, query, stmt)
	}
	return stmt, nil
}

// Select executes a SELECT query and stores the result in rows.
// The argument passed to rows can be one of the following:
//  A pointer to an array of structs; or
//  a pointer to an array of struct pointers; or
//  a pointer to a struct.
// When rows is a pointer to an array it is populated with
// one item for each row returned by the SELECT query.
//
// When rows is a pointer to a struct, it is populated with
// the first row returned from the query. This is a good
// option when the query will only return one row.
//
// Select returns the number of rows returned by the SELECT
// query.
func (s *Schema) Select(db DB, rows interface{}, sql string, args ...interface{}) (int, error) {
	stmt, err := s.Prepare(rows, sql)
	if err != nil {
		return 0, err
	}
	return stmt.Select(db, rows, args...)
}

// Exec executes the query with the given row and optional arguments.
// It returns the number of rows affected by the statement.
//
// If the statement is an INSERT statement and the row has an auto-increment field,
// then the row is updated with the value of the auto-increment column, as long as
// the SQL driver supports this functionality.
func (s *Schema) Exec(db DB, row interface{}, sql string, args ...interface{}) (int, error) {
	stmt, err := s.Prepare(row, sql)
	if err != nil {
		return 0, err
	}
	return stmt.Exec(db, row, args...)
}

// Key returns the key associated with the schema.
func (s *Schema) Key() string {
	return s.key
}

repository: nochso/sqlr

repo_name: nochso/sqlr


text:
LICENSE = "GPL"
DEFAULT_PREFERENCE = "-1"

S = "${WORKDIR}/${PN}"
PV = "0.72+cvs${SRCDATE}"
PR = "r1"

PARALLEL_MAKE = ""
inherit autotools gpe

SRC_URI = "${HANDHELDS_CVS};module=gpe/base/${PN}"

DEPENDS = "libhandoff libsoup libeventdb libschedule libxsettings libxsettings-client libgpepimc libdisplaymigration libgpevtype"
SECTION = "gpe"
RDEPENDS = "gpe-icons"
DESCRIPTION = "GPE calendar"

repository: BackupTheBerlios/openslug-svn

repo_name: BackupTheBerlios/openslug-svn


text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	"context"

	v1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeApplicationSets implements ApplicationSetInterface
type FakeApplicationSets struct {
	Fake *FakeArgoprojV1alpha1
	ns   string
}

var applicationsetsResource = schema.GroupVersionResource{Group: "argoproj.io", Version: "v1alpha1", Resource: "applicationsets"}

var applicationsetsKind = schema.GroupVersionKind{Group: "argoproj.io", Version: "v1alpha1", Kind: "ApplicationSet"}

// Get takes name of the applicationSet, and returns the corresponding applicationSet object, and an error if there is any.
func (c *FakeApplicationSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ApplicationSet, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(applicationsetsResource, c.ns, name), &v1alpha1.ApplicationSet{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.ApplicationSet), err
}

// List takes label and field selectors, and returns the list of ApplicationSets that match those selectors.
func (c *FakeApplicationSets) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ApplicationSetList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewListAction(applicationsetsResource, applicationsetsKind, c.ns, opts), &v1alpha1.ApplicationSetList{})

	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v1alpha1.ApplicationSetList{ListMeta: obj.(*v1alpha1.ApplicationSetList).ListMeta}
	for _, item := range obj.(*v1alpha1.ApplicationSetList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested applicationSets.
func (c *FakeApplicationSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewWatchAction(applicationsetsResource, c.ns, opts))

}

// Create takes the representation of a applicationSet and creates it.  Returns the server's representation of the applicationSet, and an error, if there is any.
func (c *FakeApplicationSets) Create(ctx context.Context, applicationSet *v1alpha1.ApplicationSet, opts v1.CreateOptions) (result *v1alpha1.ApplicationSet, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(applicationsetsResource, c.ns, applicationSet), &v1alpha1.ApplicationSet{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.ApplicationSet), err
}

// Update takes the representation of a applicationSet and updates it. Returns the server's representation of the applicationSet, and an error, if there is any.
func (c *FakeApplicationSets) Update(ctx context.Context, applicationSet *v1alpha1.ApplicationSet, opts v1.UpdateOptions) (result *v1alpha1.ApplicationSet, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(applicationsetsResource, c.ns, applicationSet), &v1alpha1.ApplicationSet{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.ApplicationSet), err
}

// Delete takes name of the applicationSet and deletes it. Returns an error if one occurs.
func (c *FakeApplicationSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewDeleteActionWithOptions(applicationsetsResource, c.ns, name, opts), &v1alpha1.ApplicationSet{})

	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeApplicationSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
	action := testing.NewDeleteCollectionAction(applicationsetsResource, c.ns, listOpts)

	_, err := c.Fake.Invokes(action, &v1alpha1.ApplicationSetList{})
	return err
}

// Patch applies the patch and returns the patched applicationSet.
func (c *FakeApplicationSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ApplicationSet, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(applicationsetsResource, c.ns, name, pt, data, subresources...), &v1alpha1.ApplicationSet{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.ApplicationSet), err
}

repository: argoproj/argo-cd

repo_name: argoproj/argo-cd


text:
// Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
// This program and the accompanying materials are made available under the terms of the under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

package scpintegration_test

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("SCP Backup", func() {
	var (
		consistencyThreshold = time.Second * 5
		scpTimeout           = time.Second * 10
	)

	Context("When SCP server is correctly configured with flags", func() {
		var (
			runningBin      *gexec.Session
			baseDir         string
			destPath        string
			hostFingerprint string
			deploymentName  string
		)

		pathWithDate := func(deployment string, endParts ...string) string {
			today := time.Now()
			dateComponents := []string{fmt.Sprintf("%d", today.Year()), fmt.Sprintf("%02d", today.Month()), fmt.Sprintf("%02d", today.Day())}
			args := []string{destPath}
			if deployment != "" {
				args = append(args, deployment)
			}
			args = append(args, dateComponents...)
			args = append(args, endParts...)
			return filepath.Join(args...)
		}

		checkFilesHaveBeenCopied := func(deploymentName string) {
			content1, err := ioutil.ReadFile(pathWithDate(deploymentName, "1.txt"))
			Expect(err).NotTo(HaveOccurred())
			Expect(content1).To(Equal([]byte("1")))
			content2, err := ioutil.ReadFile(pathWithDate(deploymentName, "subdir", "2.txt"))
			Expect(err).NotTo(HaveOccurred())
			Expect(content2).To(Equal([]byte("2")))
			contentDotFile, err := ioutil.ReadFile(pathWithDate(deploymentName, ".dotFile.txt"))
			Expect(err).NotTo(HaveOccurred())
			Expect(contentDotFile).To(Equal([]byte("I'm a hidden file")))
		}

		JustBeforeEach(func() {
			var err error
			baseDir, err = ioutil.TempDir("", "scp-integration-tests")
			Expect(err).NotTo(HaveOccurred())
			dirToBackup := filepath.Join(baseDir, "source")
			destPath = filepath.Join(baseDir, "target")
			Expect(os.Mkdir(dirToBackup, 0755)).To(Succeed())
			Expect(os.Mkdir(destPath, 0755)).To(Succeed())

			Expect(ioutil.WriteFile(filepath.Join(dirToBackup, ".dotFile.txt"), []byte("I'm a hidden file"), 0644)).To(Succeed())
			Expect(ioutil.WriteFile(filepath.Join(dirToBackup, "1.txt"), []byte("1"), 0644)).To(Succeed())
			Expect(os.Mkdir(filepath.Join(dirToBackup, "subdir"), 0755)).To(Succeed())
			Expect(ioutil.WriteFile(filepath.Join(dirToBackup, "subdir", "2.txt"), []byte("2"), 0644)).To(Succeed())

			runningBin = performBackup("localhost", unixUser.Username, destPath, string(privateKeyContents), hostFingerprint, 22, dirToBackup, deploymentName)
		})

		AfterEach(func() {
			Expect(os.RemoveAll(baseDir)).To(Succeed())
			Eventually(runningBin.Terminate()).Should(gexec.Exit())
		})

		Context("host finger print not provided", func() {
			BeforeEach(func() {
				hostFingerprint = ""
				deploymentName = ""
			})
			It("copies files over SCP", func() {
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say("Fingerprint not found, performing key-scan"))
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say("scp completed"))
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say(`"destination_name":"foo"`))
				runningBin.Terminate().Wait()
				checkFilesHaveBeenCopied(deploymentName)
			})
		})

		Context("valid host finger print provided", func() {
			BeforeEach(func() {
				deploymentName = ""
				cmd := exec.Command("ssh-keyscan", "-p", strconv.Itoa(22), "localhost")
				output, err := cmd.Output()
				Expect(err).NotTo(HaveOccurred())
				hostFingerprint = strings.Split(string(output), "\n")[0]
			})

			It("copies files over SCP", func() {
				Consistently(runningBin.Out, consistencyThreshold).ShouldNot(gbytes.Say("Fingerprint not found, performing key-scan"))
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say("scp completed"))
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say(`"destination_name":"foo"`))
				runningBin.Terminate().Wait()
				checkFilesHaveBeenCopied(deploymentName)
			})
		})

		Context("invalid host fingerprint provided", func() {
			BeforeEach(func() {
				deploymentName = ""
				hostFingerprint = "localhost ssh-rsa totally-invalid"
			})
			It("fails to copy files over SCP", func() {
				Consistently(runningBin.Out, consistencyThreshold).ShouldNot(gbytes.Say("Fingerprint not found, performing key-scan"))
				Consistently(runningBin.Out, consistencyThreshold).ShouldNot(gbytes.Say("scp completed"))
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say("Host key verification failed"))
				Expect(runningBin.Terminate().Wait().ExitCode()).ToNot(Equal(BeZero()))
			})
		})

		Context("when add_deployment_name_to_backup_path is true", func() {
			BeforeEach(func() {
				hostFingerprint = ""
				deploymentName = "deployment-name"
			})

			It("copies files over SCP with the deployment name in the path", func() {
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say("Fingerprint not found, performing key-scan"))
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say("scp completed"))
				Eventually(runningBin.Out, scpTimeout).Should(gbytes.Say(`"destination_name":"foo"`))
				runningBin.Terminate().Wait()
				checkFilesHaveBeenCopied(deploymentName)
			})
		})
	})
})

func runBackup(params ...string) *gexec.Session {
	backupCmd := exec.Command(pathToServiceBackupBinary, params...)
	session, err := gexec.Start(backupCmd, GinkgoWriter, GinkgoWriter)
	Expect(err).ToNot(HaveOccurred())
	return session
}

func performBackup(scpServer, scpUser, scpDestination, scpKey, hostFingerprint string, scpPort int, sourceFolder, deploymentName string) *gexec.Session {
	file, err := ioutil.TempFile("", "config.yml")
	Expect(err).NotTo(HaveOccurred())

	parts := strings.Split(scpKey, "\n")
	scpKey = strings.Join(parts, "\n      ")

	addDeploymentNameToPath := deploymentName != ""

	file.Write([]byte(fmt.Sprintf(`---
destinations:
- type: scp
  name: foo
  config:
    server: %s
    user: %s
    destination: %s
    fingerprint: '%s'
    key: |
      %s
    port: %d
source_folder: %s
source_executable: true
exit_if_in_progress: true
cron_schedule: '*/5 * * * * *'
cleanup_executable: true
missing_properties_message: custom message
deployment_name: %s
add_deployment_name_to_backup_path: %t`, scpServer, scpUser, scpDestination, hostFingerprint, scpKey, scpPort, sourceFolder, deploymentName, addDeploymentNameToPath,
	)))
	file.Close()

	return runBackup(file.Name())
}

repository: pivotal-cf/service-backup

repo_name: pivotal-cf/service-backup


text:
// Code generated by mockery. DO NOT EDIT.

package mocks

import (
	cache "sigs.k8s.io/controller-runtime/pkg/cache"
	client "sigs.k8s.io/controller-runtime/pkg/client"

	context "context"

	mock "github.com/stretchr/testify/mock"

	schema "k8s.io/apimachinery/pkg/runtime/schema"

	types "k8s.io/apimachinery/pkg/types"
)

// Cache is an autogenerated mock type for the Cache type
type Cache struct {
	mock.Mock
}

// Get provides a mock function with given fields: ctx, key, obj, opts
func (_m *Cache) Get(ctx context.Context, key types.NamespacedName, obj client.Object, opts ...client.GetOption) error {
	_va := make([]interface{}, len(opts))
	for _i := range opts {
		_va[_i] = opts[_i]
	}
	var _ca []interface{}
	_ca = append(_ca, ctx, key, obj)
	_ca = append(_ca, _va...)
	ret := _m.Called(_ca...)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, types.NamespacedName, client.Object, ...client.GetOption) error); ok {
		r0 = rf(ctx, key, obj, opts...)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// GetInformer provides a mock function with given fields: ctx, obj
func (_m *Cache) GetInformer(ctx context.Context, obj client.Object) (cache.Informer, error) {
	ret := _m.Called(ctx, obj)

	var r0 cache.Informer
	var r1 error
	if rf, ok := ret.Get(0).(func(context.Context, client.Object) (cache.Informer, error)); ok {
		return rf(ctx, obj)
	}
	if rf, ok := ret.Get(0).(func(context.Context, client.Object) cache.Informer); ok {
		r0 = rf(ctx, obj)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(cache.Informer)
		}
	}

	if rf, ok := ret.Get(1).(func(context.Context, client.Object) error); ok {
		r1 = rf(ctx, obj)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// GetInformerForKind provides a mock function with given fields: ctx, gvk
func (_m *Cache) GetInformerForKind(ctx context.Context, gvk schema.GroupVersionKind) (cache.Informer, error) {
	ret := _m.Called(ctx, gvk)

	var r0 cache.Informer
	var r1 error
	if rf, ok := ret.Get(0).(func(context.Context, schema.GroupVersionKind) (cache.Informer, error)); ok {
		return rf(ctx, gvk)
	}
	if rf, ok := ret.Get(0).(func(context.Context, schema.GroupVersionKind) cache.Informer); ok {
		r0 = rf(ctx, gvk)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(cache.Informer)
		}
	}

	if rf, ok := ret.Get(1).(func(context.Context, schema.GroupVersionKind) error); ok {
		r1 = rf(ctx, gvk)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// IndexField provides a mock function with given fields: ctx, obj, field, extractValue
func (_m *Cache) IndexField(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error {
	ret := _m.Called(ctx, obj, field, extractValue)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, client.Object, string, client.IndexerFunc) error); ok {
		r0 = rf(ctx, obj, field, extractValue)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// List provides a mock function with given fields: ctx, list, opts
func (_m *Cache) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
	_va := make([]interface{}, len(opts))
	for _i := range opts {
		_va[_i] = opts[_i]
	}
	var _ca []interface{}
	_ca = append(_ca, ctx, list)
	_ca = append(_ca, _va...)
	ret := _m.Called(_ca...)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, client.ObjectList, ...client.ListOption) error); ok {
		r0 = rf(ctx, list, opts...)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// Start provides a mock function with given fields: ctx
func (_m *Cache) Start(ctx context.Context) error {
	ret := _m.Called(ctx)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context) error); ok {
		r0 = rf(ctx)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// WaitForCacheSync provides a mock function with given fields: ctx
func (_m *Cache) WaitForCacheSync(ctx context.Context) bool {
	ret := _m.Called(ctx)

	var r0 bool
	if rf, ok := ret.Get(0).(func(context.Context) bool); ok {
		r0 = rf(ctx)
	} else {
		r0 = ret.Get(0).(bool)
	}

	return r0
}

// NewCache creates a new instance of Cache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewCache(t interface {
	mock.TestingT
	Cleanup(func())
}) *Cache {
	mock := &Cache{}
	mock.Mock.Test(t)

	t.Cleanup(func() { mock.AssertExpectations(t) })

	return mock
}

repository: projectcontour/contour

repo_name: projectcontour/contour


text:
require navit.inc

PV = "0.1.0+svnrev${SRCREV}"
PR = "r1"

DEFAULT_PREFERENCE = "-1"

S = "${WORKDIR}/navit"

SRC_URI = "svn://anonymous@navit.svn.sourceforge.net/svnroot/navit/trunk;module=navit;proto=https"

EXTRA_AUTORECONF = " -I m4"


text:
package healthchecks

import (
	"testing"

	"github.com/openshift/osde2e/pkg/common/util"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	kubernetes "k8s.io/client-go/kubernetes/fake"
)

func secrets(numItems int) []v1.Secret {
	secrets := []v1.Secret{}
	for i := 0; i < numItems; i++ {
		secrets = append(secrets, v1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Labels:    map[string]string{"certificate_request": ""},
				Name:      util.RandomStr(5),
				Namespace: "openshift-config",
			},
		})
	}
	return secrets
}

func secretList(numItems int) *v1.SecretList {
	return &v1.SecretList{
		Items: secrets(numItems),
	}
}

func TestCerts(t *testing.T) {
	tests := []struct {
		description string
		expected    bool
		objs        []runtime.Object
	}{
		{
			description: "no certs present",
			expected:    false,
			objs:        []runtime.Object{secretList(0)},
		},
		{
			description: "one cert present",
			expected:    true,
			objs:        []runtime.Object{secretList(1)},
		},
		{
			description: "two certs present",
			expected:    true,
			objs:        []runtime.Object{secretList(2)},
		},
	}

	for _, test := range tests {
		kubeClient := kubernetes.NewSimpleClientset(test.objs...)
		state, err := CheckCerts(kubeClient.CoreV1(), nil)
		if err != nil {
			t.Errorf("Unexpected error: %s", err)
			return
		}

		if state != test.expected {
			t.Errorf("%v: Expected value doesn't match returned value (%v, %v)", test.description, test.expected, state)
		}
	}
}


text:
package data

import (
	"fmt"
	"time"
)

type Activity struct {
	Type     string `json:"type"`
	Date     string `json:"date"`
	Activity string `json:"activity"`
}

func (n Activity) ToCSVEntry() string {
	return fmt.Sprintf("\t%s, %s, %s", n.Type, n.Date, n.Activity)
}

func NewActivity() *Activity {
	return &Activity{Date: time.Now().Format(time.RFC3339)}
}

repository: callmeradical/worklog

repo_name: callmeradical/worklog


text:
#include <uWS/uWS.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "helpers.h"
#include "spline.h"
#include "json.hpp"

// for convenience
using nlohmann::json;
using std::string;
using std::vector;

int main() {
  uWS::Hub h;

  // Load up map values for waypoint's x,y,s and d normalized normal vectors
  vector<double> map_waypoints_x;
  vector<double> map_waypoints_y;
  vector<double> map_waypoints_s;
  vector<double> map_waypoints_dx;
  vector<double> map_waypoints_dy;

  // Waypoint map to read from
  string map_file_ = "../data/highway_map.csv";
  // The max s value before wrapping around the track back to 0
  double max_s = 6945.554;

  std::ifstream in_map_(map_file_.c_str(), std::ifstream::in);

  string line;
  while (getline(in_map_, line)) {
    std::istringstream iss(line);
    double x;
    double y;
    float s;
    float d_x;
    float d_y;
    iss >> x;
    iss >> y;
    iss >> s;
    iss >> d_x;
    iss >> d_y;
    map_waypoints_x.push_back(x);
    map_waypoints_y.push_back(y);
    map_waypoints_s.push_back(s);
    map_waypoints_dx.push_back(d_x);
    map_waypoints_dy.push_back(d_y);
  }

  int lane = 1;       // start lane
  double ref_vel = 0; // reference velocity at start (mph)

  h.onMessage([&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,
               &map_waypoints_dx,&map_waypoints_dy, &lane, &ref_vel]
              (uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
               uWS::OpCode opCode) {
    // "42" at the start of the message means there's a websocket message event.
    // The 4 signifies a websocket message
    // The 2 signifies a websocket event
    if (length && length > 2 && data[0] == '4' && data[1] == '2') {

      auto s = hasData(data);

      if (s != "") {
        auto j = json::parse(s);

        string event = j[0].get<string>();

        if (event == "telemetry") {
          // j[1] is the data JSON object

          // Main car's localization Data
          double car_x = j[1]["x"];
          double car_y = j[1]["y"];
          double car_s = j[1]["s"];
          double car_d = j[1]["d"];
          double car_yaw = j[1]["yaw"];
          double car_speed = j[1]["speed"];

          // Previous path data given to the Planner
          auto previous_path_x = j[1]["previous_path_x"];
          auto previous_path_y = j[1]["previous_path_y"];
          // Previous path's end s and d values
          double end_path_s = j[1]["end_path_s"];
          double end_path_d = j[1]["end_path_d"];

          // Sensor Fusion Data, a list of all other cars on the same side
          // of the road.
          auto sensor_fusion = j[1]["sensor_fusion"];

 	  int prev_size = previous_path_x.size();

	  // if previous path exists, track the end path point as current
	  if (prev_size > 0)
	    car_s = end_path_s;

          /*
           * define a path made up of (x,y) points that the car will visit
           * sequentially every .02 seconds
           */
	  bool laneChangePrep  = false;
	  bool laneChangePrepL = true;  bool laneChangePrepR = true;
	  bool tooCloseFront   = false; bool tooCloseLR      = false;
	  vector<double> dist;

	  // checking if the preceding vehicle is too close
	  // if not, prepare for lane change
	  for (int i = 0; i < sensor_fusion.size(); i++)
	  {
	    double vx = sensor_fusion[i][3]; // velocity along x in global
	    double vy = sensor_fusion[i][4]; // velocity along y in global
	    double  s = sensor_fusion[i][5]; // long dist in Frenet
	    double  d = sensor_fusion[i][6]; // lat dist in Frenet
	    double sp = sqrt(pow(vx,2) + pow(vy,2)); // speed in global
	    s += prev_size * period * sp; // updated long dist - prev.path
	    double distBtw = s - car_s; // diff in dist btw host and targe

	    // within safety distance threshold -too close -> slowDown Flag
	    // outside the threshold -> prepare for lane change
	    if (inLane(lane, d) && inSafetyDistFront(s, car_s))
	    {
		std::cout << "** Preceding vehicle too close **\n" <<
		"checking for lane change availability\n" << std::endl;
	        tooCloseFront = true;
	        laneChangePrep = true;
	    }
	    if (inLane(lane, d) && distBtw > 0)
	      dist.emplace_back(distBtw);
	  }

	  // if the lane change prep flag is on, check if the vehicle in
	  // the left/right lane is within the safety distance threshold
	  // and set the flag accordingly, simliar to the above
	  if (laneChangePrep)
	  {
	   for (int i = 0; i < sensor_fusion.size(); i++)
	   {
	     double vx = sensor_fusion[i][3]; // velocity along x in global
	     double vy = sensor_fusion[i][4]; // velocity along y in global
	     double  s = sensor_fusion[i][5]; // long dist in Frenet
	     double  d = sensor_fusion[i][6]; // lat dist in Frenet
	     double sp = sqrt(pow(vx,2) + pow(vy,2)); // speed in global
	     s += prev_size * period * sp;// updated long dist - prev.path

	     // left lane
	     if (inLane(lane - 1, d))
	     {
	       if (inSafetyDistLR(s, car_s))
	       {
	         tooCloseLR = true;
   		 laneChangePrepL = false;
	       }
	     }
	     // right Lane
	     else if (inLane(lane + 1, d))
             {
               if (inSafetyDistLR(s, car_s))
	       {
		 tooCloseLR = true;
	 	 laneChangePrepR = false;
	       }
	     }
	   }
	  }

 	  /* Perform lane change feed in added lateral offset in Frenet */
	  if (laneChangePrep && laneChangePrepL && lane > 0)
	  {
	    std::cout << "Perform Lane Change - Left" << std::endl;
	    std::cout << "----------------------------------=" <<std::endl;
	    lane -= 1;
	  }
	  else if (laneChangePrep && laneChangePrepR && lane < 2)
	  {
	    std::cout << "Perform Lane Change - Right" << std::endl;
	    std::cout << "-----------------------------------" <<std::endl;
            lane += 1;
	  }

	  /* simple speed control */
	  // closest vehicle in the host lane < 5m, emergency break
	  if ((dist.size() != 0 &&
	   *std::min_element(dist.begin(), dist.end()) < slowDownDist))
	  {
	     ref_vel -= velIncrement * 3.0;
	  }
	  // keep the speed below the limit
	  else if (car_speed > speedLimit * 0.8)
	  {
	     ref_vel -= velIncrement;
	  }
	  // too-close and speed limit flag, gradually slowing down
	  else if (tooCloseFront && tooCloseLR)
	  {
	     ref_vel -= velIncrement * 2.0;
	  }
	  else if (tooCloseFront || tooCloseLR)
	  {
	    ref_vel -= velIncrement;
	  }
	  // within speed limit, gradually speed up
	  else
	  {
	    ref_vel += velIncrement;
	  }
	  vector<double> ptsx;
	  vector<double> ptsy;
	  // reference x,y, yawrate
	  // either we will reference the starting point as where the car
	  // is or at the previous paths end points
	  double ref_x = car_x;
	  double ref_y = car_y;
	  double ref_yaw = deg2rad(car_yaw);

	  if (prev_size < 2)
	  {
	    // use two points that make the path tangent to the car
	    double prev_car_x = car_x - cos(car_yaw);
	    double prev_car_y = car_y - sin(car_yaw);

	    ptsx.emplace_back(prev_car_x);
	    ptsx.emplace_back(car_x);

	    ptsy.emplace_back(prev_car_y);
	    ptsy.emplace_back(car_y);
	  }
	  // use the previous path's end point as starting reference
	  else
	  {
	    //redefine reference state as previous path end point
	    ref_x = previous_path_x[prev_size-1];
	    ref_y = previous_path_y[prev_size-1];

	    double ref_x_prev = previous_path_x[prev_size-2];
    	    double ref_y_prev = previous_path_y[prev_size-2];
	    ref_yaw = atan2(ref_y - ref_y_prev, ref_x - ref_x_prev);

	    // use two points that make the path tangent to the previous
	    // path's end point
	    ptsx.emplace_back(ref_x_prev);
	    ptsx.emplace_back(ref_x);

	    ptsy.emplace_back(ref_y_prev);
	    ptsy.emplace_back(ref_y);
	  }

	  // In Frenet add evenly 30m spaced points ahead of the starting
	  // reference
	  vector<double> next_wp0 = getXY(car_s+30, 2.0 + 4.0 * lane,
	      map_waypoints_s, map_waypoints_x, map_waypoints_y);

	  vector<double> next_wp1 = getXY(car_s+60, 2.0 + 4.0 * lane,
              map_waypoints_s, map_waypoints_x, map_waypoints_y);

	  vector<double> next_wp2 = getXY(car_s+90, 2.0 + 4.0 * lane,
              map_waypoints_s, map_waypoints_x, map_waypoints_y);

	  ptsx.emplace_back(next_wp0[0]);
	  ptsx.emplace_back(next_wp1[0]);
	  ptsx.emplace_back(next_wp2[0]);

	  ptsy.emplace_back(next_wp0[1]);
	  ptsy.emplace_back(next_wp1[1]);
	  ptsy.emplace_back(next_wp2[1]);

	  for (int i = 0; i < ptsx.size(); i++)
	  {
	    //shift car reference angle to 0 degrees
	    double shift_x = ptsx[i]-ref_x;
	    double shift_y = ptsy[i]-ref_y;

	    ptsx[i] = (shift_x * cos(0-ref_yaw)-shift_y * sin(0-ref_yaw));
	    ptsy[i] = (shift_x * sin(0-ref_yaw)+shift_y * cos(0-ref_yaw));
	  }
	  // create a spline instance
	  tk::spline s;

	  // set (x,y) anchor points to the spline
	  s.set_points(ptsx,ptsy);

	  // define the actual (x,y) points we will use for the planner
	  vector<double> next_x_vals;
	  vector<double> next_y_vals;

	  // start with all of the previous path points from last time
	  // indicating future paths left from the previous paths
	  // for continuity
	  for (int i = 0; i < previous_path_x.size(); i++)
	  {
	    next_x_vals.emplace_back(previous_path_x[i]);
	    next_y_vals.emplace_back(previous_path_y[i]);
	  }

	  // calculate how to break up spline points so that we travel
	  // at our desired reference velocity
	  double target_x = 30.0;
	  double target_y = s(target_x); // f(30) = target_y
	  double target_dist = sqrt(pow(target_x,2)+pow(target_y,2));

	  double x_add_on = 0; // where we start -result from coord shift

	  // fill up the rest of our path planner after filling it with
	  // previuos points, here we will always output 50 points
	  for (int i = 1; i <= 50 - previous_path_x.size(); i++)
	  {
	    double N = (target_dist/(period * ref_vel / 2.24));//2.24:mph-mps
	    double x_point = x_add_on + (target_x) / N;
	    double y_point = s(x_point);

	    x_add_on = x_point;

	    double x_ref = x_point;
	    double y_ref = y_point;

	    // rotate back to global from local coordinate
	    x_point = (x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw));
	    y_point = (x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw));

	    x_point += ref_x;
	    y_point += ref_y;

	    next_x_vals.emplace_back(x_point);
	    next_y_vals.emplace_back(y_point);
	  }

	  // // testing straight line const velocity
	  //double dist_inc = 0.5;
	  //for (int i = 0; i < 50; i++) {
	  //  double next_s = car_s + (i+1)*dist_inc;
	  //  double next_d = 6;
	  //  vector<double> xy = getXY(next_s, next_d, map_waypoints_s, map_waypoints_x, map_waypoints_y);
	  //  next_x_vals.emplace_back(xy[0]);
	  //  next_y_vals.emplace_back(xy[1]);
	  //}

	  json msgJson;
          msgJson["next_x"] = next_x_vals;
          msgJson["next_y"] = next_y_vals;

          auto msg = "42[\"control\","+ msgJson.dump()+"]";

          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
        }  // end "telemetry" if
      } else {
        // Manual driving
        std::string msg = "42[\"manual\",{}]";
        ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
      }
    }  // end websocket if
  }); // end h.onMessage

  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
    std::cout << "Connected!!!" << std::endl;
  });

  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
                         char *message, size_t length) {
    ws.close();
    std::cout << "Disconnected" << std::endl;
  });

  int port = 4567;
  if (h.listen(port)) {
    std::cout << "Listening to port " << port << std::endl;
  } else {
    std::cerr << "Failed to listen to port" << std::endl;
    return -1;
  }

  h.run();
}

repository: himsangseung/SelfDrivingCarNanoDegree

repo_name: himsangseung/SelfDrivingCarNanoDegree

extension: cpp


text:
# Copyright Cam Mannett 2020
#
# See LICENSE file
#

add_executable(malbolge_address_sanitizer EXCLUDE_FROM_ALL ${MAIN_SRCS})
add_dependencies(malbolge_address_sanitizer gen_version malbolge_lib)

target_compile_features(malbolge_address_sanitizer PUBLIC cxx_std_20)
set_target_properties(malbolge_address_sanitizer PROPERTIES CXX_EXTENSIONS OFF)

target_compile_options(malbolge_address_sanitizer PRIVATE
    $<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CXX_COMPILER_ID:GNU>>:
        -Werror -Wall -Wextra>
    $<$<CXX_COMPILER_ID:MSVC>:
        /W4>
)

target_include_directories(malbolge_address_sanitizer
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
)

target_link_libraries(malbolge_address_sanitizer
    PUBLIC Threads::Threads
    PUBLIC malbolge_lib
)

target_compile_options(malbolge_address_sanitizer
    PRIVATE -fsanitize=address -fno-omit-frame-pointer -fsanitize=undefined
)

target_link_options(malbolge_address_sanitizer
    PRIVATE -fsanitize=address -fsanitize=undefined
)

extension: cmake


text:
package main

import (
	"StudentSystem/database"
	"StudentSystem/models"
	"StudentSystem/routers"
)

func main() {
	// 创建数据库
	// sql: CREATE DATABASE StudentSystem;
	// 连接数据库
	err := database.InitMySQL()
	if err != nil {
		panic(err)
	}
	defer database.Close()  // 程序退出关闭数据库连接
	// 模型绑定
	database.DB.AutoMigrate(&models.Student{})
	// 注册路由
	r := routers.SetupRouter()
	r.Run()//默认在127.0.0.1:8080端口运行
}


text:
package syntaxcolor

import "regexp"
import "github.com/nsf/termbox-go"
import "path"
import "fmt"

type Color struct {
	fg, bg termbox.Attribute
}

// SyntaxRule simply maps a regexp to a color.
type SyntaxRule struct {
	re    *regexp.Regexp
	color Color
}

type SyntaxRules []SyntaxRule

func NewSyntaxRules(filename string) *SyntaxRules {

	rules := SyntaxRules{}

	filetype := rules.GetFileType(filename)

	// Filetype specific rules
	switch filetype {
	case "sh", "py", "yaml", "js", "c", "coffee", "html", "rb":
		rules.addSingleQuoteRule(termbox.ColorYellow)
		rules.addDoubleQuoteRule(termbox.ColorYellow)
	case "go":
		rules.addSingleQuoteRule(termbox.ColorRed)
		rules.addDoubleQuoteRule(termbox.ColorYellow)
	}
	switch filetype {
	case "go":
		rules.addLineCommentRule("//", termbox.ColorCyan)
	case "rb", "sh", "py", "yaml", "coffee", "git":
		rules.addLineCommentRule("#", termbox.ColorCyan)
	case "c":
		rules.addLineCommentRule("//", termbox.ColorCyan)
	case "md":
		rules.addRule("^#+.*$", Color{fg: termbox.ColorGreen})
		rules.addRule("^===*$", Color{fg: termbox.ColorGreen})
		rules.addRule("^---*$", Color{fg: termbox.ColorGreen})
	case "js":
		rules.addLineCommentRule("//", termbox.ColorCyan)
	case "html":
		rules.addRule("<!--.*?-->", Color{fg: termbox.ColorCyan})
	}

	// Trailing whitespace
	rules.addRule("[ \t]+$", Color{bg: termbox.ColorYellow})

	return &rules

}

func (rules *SyntaxRules) addRule(reStr string, color Color) {
	re, _ := regexp.Compile(reStr)
	*rules = append(*rules, SyntaxRule{re, color})
}

func (rules *SyntaxRules) addLineCommentRule(commStr string, fg termbox.Attribute) {
	reStr := fmt.Sprintf("%s.*$", commStr)
	rules.addRule(reStr, Color{fg: fg})
}

func (rules *SyntaxRules) addSingleQuoteRule(fg termbox.Attribute) {
	rules.addRule("'.*?'", Color{fg: fg})
}

func (rules *SyntaxRules) addDoubleQuoteRule(fg termbox.Attribute) {
	rules.addRule("\".*?\"", Color{fg: fg})
}

func (rules SyntaxRules) GetFileType(filename string) string {
	ext := path.Ext(filename)
	if len(ext) == 0 {
		basename := path.Base(filename)
		if basename == "COMMIT_EDITMSG" {
			return "git"
		}
		return ""
	}
	ext = ext[1:]
	switch ext {
	case ".c", ".C", ".cpp", ".c++":
		return "c"
	case ".sh", ".csh":
		return "sh"
	case "":
		return ""
	default:
		return ext
	}
}

type LineColor struct {
	Fg, Bg     termbox.Attribute
	Start, End int
}

// Colorize takes in a string and outputs an array of LineColor objects.
// A linecolor object maps a color pair (bg, fg) with start/end indices
// within the string.
func (rules SyntaxRules) Colorize(str string) []LineColor {
	lc := []LineColor{}
	for _, rule := range rules {
		matches := rule.re.FindAllStringIndex(str, -1)
		if matches == nil {
			continue
		}
		for _, startEnd := range matches {
			lc = append(lc, LineColor{Fg: rule.color.fg, Bg: rule.color.bg, Start: startEnd[0], End: startEnd[1]})
		}
	}
	return lc
}

repository: ZenClark/sith

repo_name: ZenClark/sith


text:
@article{Kohe2018,
 abstract = {The rare pediatric embryonal tumors retinoblastoma, medulloblastoma and neuroblastoma derive from neuroectodermal tissue and share similar histopathological features despite different anatomical locations and diverse clinical outcomes. As metabolism can reflect genetic and histological features, we investigated whether the metabolism of embryonal tumors reflects their similar histology, shared developmental and neural origins, or tumor location. We undertook metabolic profiling on 50 retinoblastoma, 39 medulloblastoma and 70 neuroblastoma using high resolution magic angle spinning magnetic resonance spectroscopy (1H-MRS). Mean metabolite concentrations identified several metabolites that were significantly different between the tumor groups including taurine, hypotaurine, glutamate, glutamine, GABA, phosphocholine, N-acetylaspartate, creatine, glycine and myoinositol,   < 0.0017. Unsupervised multivariate analysis found that each tumor group clustered separately, with a unique metabolic profile, influenced by their underlying clinical diversity. Taurine was notably high in all tumors consistent with prior evidence from embryonal tumors. Retinoblastoma and medulloblastoma were more metabolically similar, sharing features associated with the central nervous system (CNS). Neuroblastoma had features consistent with neural tissue, but also contained significantly higher myoinositol and altered glutamate-glutamine ratio, suggestive of differences in the underlying metabolism of embryonal tumors located outside of the CNS. Despite the histological similarities and shared neural metabolic features, we show that individual neuroectodermal derived embryonal tumors can be distinguished by tissue metabolic profile. Pathway analysis suggests the alanine-aspartate-glutamate and taurine-hypotaurine metabolic pathways may be the most pertinent pathways to investigate for novel therapeutic strategies. This work strengthens our understanding of the biology and metabolic pathways underlying neuroectodermal derived embryonal tumors of childhood.},
 author = {Kohe, Sarah E. and Bennett, Christopher D. and Gill, Simrandip K. and Wilson, Martin and McConville, Carmel and Peet, Andrew C.},
 country = {United States},
 doi = {10.18632/oncotarget.24168},
 issn = {1949-2553},
 issn-linking = {1949-2553},
 issue = {13},
 journal = {Oncotarget},
 keywords = {high resolution magnetic resonance spectroscopy; medulloblastoma; neuroblastoma; retinoblastoma; tumor metabolites},
 month = {February},
 nlm-id = {101532965},
 owner = {NLM},
 pages = {11336--11351},
 pii = {24168},
 pmc = {PMC5834290},
 pmid = {29541417},
 pubmodel = {Electronic-eCollection},
 pubstate = {epublish},
 revised = {2019-11-20},
 title = {Metabolic profiling of the three neural derived embryonal pediatric tumors retinoblastoma, neuroblastoma and medulloblastoma, identifies distinct metabolic profiles.},
 volume = {9},
 year = {2018}
}


text:
package proxy

import (
	"path"

	"github.com/pkg/errors"

	pluginapi "github.com/mattermost/mattermost-plugin-api"
	"github.com/mattermost/mattermost-server/v6/model"

	"github.com/mattermost/mattermost-plugin-apps/apps"
	appspath "github.com/mattermost/mattermost-plugin-apps/apps/path"
	"github.com/mattermost/mattermost-plugin-apps/server/config"
	"github.com/mattermost/mattermost-plugin-apps/server/mmclient"
	"github.com/mattermost/mattermost-plugin-apps/utils"
)

func contextForApp(app apps.App, base apps.Context, conf config.Config) apps.Context {
	out := base
	out.ExpandedContext = apps.ExpandedContext{}
	out.MattermostSiteURL = conf.MattermostSiteURL
	out.AppID = app.AppID
	out.AppPath = path.Join(conf.PluginURLPath, appspath.Apps, string(app.AppID))
	out.BotUserID = app.BotUserID
	out.BotAccessToken = app.BotAccessToken
	return out
}

var emptyCC = apps.Context{}

func (p *Proxy) expandContext(in Incoming, app apps.App, base *apps.Context, expand *apps.Expand) (apps.Context, error) {
	if base == nil {
		base = &apps.Context{}
	}
	conf, mm, _ := p.conf.Basic()

	cc := contextForApp(app, *base, conf)
	if expand == nil {
		// nothing more to do
		return cc, nil
	}

	client, err := getExpandClient(app, conf, mm, in)
	if err != nil {
		return emptyCC, err
	}

	var userSession *model.Session
	if expand.AdminAccessToken != "" {
		if !app.GrantedPermissions.Contains(apps.PermissionActAsAdmin) {
			return emptyCC, utils.NewForbiddenError("%s does not have permission to %s", app.AppID, apps.PermissionActAsAdmin)
		}
		err := utils.EnsureSysAdmin(p.conf.MattermostAPI(), cc.ActingUserID)
		if err != nil {
			return emptyCC, utils.NewForbiddenError("user is not a sysadmin")
		}
		// See if we can derive the admin token from the "base" context
		cc.AdminAccessToken = in.AdminAccessToken
		if cc.AdminAccessToken == "" {
			cc.AdminAccessToken = in.ActingUserAccessToken
		}
		// Try to obtain it from the present session
		if cc.AdminAccessToken == "" && in.SessionID != "" {
			userSession, err = utils.LoadSession(p.conf.MattermostAPI(), in.SessionID, in.ActingUserID)
			if err != nil {
				return emptyCC, utils.NewForbiddenError("failed to load user session")
			}
			cc.AdminAccessToken = userSession.Token
		}
		if cc.AdminAccessToken == "" {
			return cc, errors.New("admin access token is not available")
		}
	}

	if expand.ActingUserAccessToken != "" {
		if !app.GrantedPermissions.Contains(apps.PermissionActAsUser) {
			return emptyCC, utils.NewForbiddenError("%s does not have permission to %s", app.AppID, apps.PermissionActAsUser)
		}
		cc.ActingUserAccessToken = in.ActingUserAccessToken
		if cc.ActingUserAccessToken == "" {
			if userSession == nil {
				var err error
				userSession, err = utils.LoadSession(p.conf.MattermostAPI(), in.SessionID, in.ActingUserID)
				if err != nil {
					return emptyCC, utils.NewForbiddenError("failed to load user session")
				}
			}
			cc.ActingUserAccessToken = userSession.Token
		}
		if cc.ActingUserAccessToken == "" {
			return emptyCC, utils.NewForbiddenError("acting user token is not available")
		}
	}

	cc.App = stripApp(app, expand.App)

	if expand.ActingUser != "" && base.ActingUserID != "" && base.ActingUser == nil {
		actingUser, err := client.GetUser(base.ActingUserID)
		if err != nil {
			return emptyCC, errors.Wrapf(err, "failed to expand acting user %s", base.ActingUserID)
		}
		base.ActingUser = actingUser
	}
	cc.ActingUser = stripUser(base.ActingUser, expand.ActingUser)

	if expand.Channel != "" && base.ChannelID != "" && base.Channel == nil {
		ch, err := client.GetChannel(base.ChannelID)
		if err != nil {
			return emptyCC, errors.Wrapf(err, "failed to expand channel %s", base.ChannelID)
		}
		base.Channel = ch
	}
	cc.Channel = stripChannel(base.Channel, expand.Channel)

	if expand.Post != "" && base.PostID != "" && base.Post == nil {
		post, err := client.GetPost(base.PostID)
		if err != nil {
			return emptyCC, errors.Wrapf(err, "failed to expand post %s", base.PostID)
		}
		base.Post = post
	}
	cc.Post = stripPost(base.Post, expand.Post)

	if expand.RootPost != "" && base.RootPostID != "" && base.RootPost == nil {
		post, err := client.GetPost(base.RootPostID)
		if err != nil {
			return emptyCC, errors.Wrapf(err, "failed to expand root post %s", base.RootPostID)
		}
		base.RootPost = post
	}
	cc.RootPost = stripPost(base.RootPost, expand.RootPost)

	if expand.Team != "" && base.TeamID != "" && base.Team == nil {
		team, err := client.GetTeam(base.TeamID)
		if err != nil {
			return emptyCC, errors.Wrapf(err, "failed to expand team %s", base.TeamID)
		}
		base.Team = team
	}
	cc.Team = stripTeam(base.Team, expand.Team)

	// TODO: expand Mentions, maybe replacing User?
	// https://mattermost.atlassian.net/browse/MM-30403

	if expand.User != "" && base.UserID != "" && base.User == nil {
		user, err := client.GetUser(base.UserID)
		if err != nil {
			return emptyCC, errors.Wrapf(err, "failed to expand user %s", base.UserID)
		}
		base.User = user
	}
	cc.User = stripUser(base.User, expand.User)

	cc.OAuth2 = apps.OAuth2Context{}
	if app.GrantedPermissions.Contains(apps.PermissionRemoteOAuth2) {
		if expand.OAuth2App != "" {
			cc.OAuth2.ClientID = app.RemoteOAuth2.ClientID
			cc.OAuth2.ClientSecret = app.RemoteOAuth2.ClientSecret
			cc.OAuth2.ConnectURL = conf.AppURL(app.AppID) + appspath.RemoteOAuth2Connect
			cc.OAuth2.CompleteURL = conf.AppURL(app.AppID) + appspath.RemoteOAuth2Complete
		}

		if expand.OAuth2User != "" && base.OAuth2.User == nil && base.ActingUserID != "" {
			var v interface{}
			err := p.store.OAuth2.GetUser(app.BotUserID, base.ActingUserID, &v)
			if err != nil && !errors.Is(err, utils.ErrNotFound) {
				return emptyCC, errors.Wrapf(err, "failed to expand OAuth user %s", base.UserID)
			}
			cc.ExpandedContext.OAuth2.User = v
		}
	}

	if expand.Locale != "" {
		if cc.ActingUser != nil {
			cc.Locale = utils.GetLocaleWithUser(p.conf.MattermostConfig().Config(), cc.ActingUser)
		} else {
			cc.Locale = utils.GetLocale(p.conf.MattermostAPI(), p.conf.MattermostConfig().Config(), cc.ActingUserID)
		}
	}

	return cc, nil
}

func stripUser(user *model.User, level apps.ExpandLevel) *model.User {
	if user == nil {
		return user
	}
	if level == apps.ExpandAll {
		sanitized := *user
		sanitized.Sanitize(map[string]bool{
			"passwordupdate": true,
			"authservice":    true,
		})
		return &sanitized
	}
	if level != apps.ExpandSummary {
		return nil
	}
	return &model.User{
		BotDescription: user.BotDescription,
		DeleteAt:       user.DeleteAt,
		Email:          user.Email,
		FirstName:      user.FirstName,
		Id:             user.Id,
		IsBot:          user.IsBot,
		LastName:       user.LastName,
		Locale:         user.Locale,
		Nickname:       user.Nickname,
		Roles:          user.Roles,
		Timezone:       user.Timezone,
		Username:       user.Username,
	}
}

func stripChannel(channel *model.Channel, level apps.ExpandLevel) *model.Channel {
	if channel == nil {
		return channel
	}
	if level == apps.ExpandAll {
		return channel
	}
	if level != apps.ExpandSummary {
		return nil
	}
	return &model.Channel{
		Id:          channel.Id,
		DeleteAt:    channel.DeleteAt,
		TeamId:      channel.TeamId,
		Type:        channel.Type,
		DisplayName: channel.DisplayName,
		Name:        channel.Name,
	}
}

func stripTeam(team *model.Team, level apps.ExpandLevel) *model.Team {
	if team == nil {
		return team
	}
	if level == apps.ExpandAll {
		sanitized := *team
		sanitized.Sanitize()
		return &sanitized
	}
	if level != apps.ExpandSummary {
		return nil
	}
	return &model.Team{
		Id:          team.Id,
		DisplayName: team.DisplayName,
		Name:        team.Name,
		Description: team.Description,
		Email:       team.Email,
		Type:        team.Type,
	}
}

func stripPost(post *model.Post, level apps.ExpandLevel) *model.Post {
	if post == nil {
		return post
	}
	if level == apps.ExpandAll {
		sanitized := *post.Clone()
		sanitized.SanitizeProps()
		return &sanitized
	}
	if level != apps.ExpandSummary {
		return nil
	}
	return &model.Post{
		Id:        post.Id,
		Type:      post.Type,
		UserId:    post.UserId,
		ChannelId: post.ChannelId,
		RootId:    post.RootId,
		Message:   post.Message,
	}
}

func stripApp(app apps.App, level apps.ExpandLevel) *apps.App {
	clone := apps.App{
		Manifest: apps.Manifest{
			AppID:   app.AppID,
			Version: app.Version,
		},
		WebhookSecret: app.WebhookSecret,
		BotUserID:     app.BotUserID,
		BotUsername:   app.BotUsername,
	}

	switch level {
	case apps.ExpandAll, apps.ExpandSummary:
		return &clone
	}
	return nil
}

func getExpandClient(app apps.App, conf config.Config, mm *pluginapi.Client, in Incoming) (mmclient.Client, error) {
	switch {
	case app.GrantedPermissions.Contains(apps.PermissionActAsAdmin):
		// If the app has admin permission anyway, use the RPC client for performance reasons
		return mmclient.NewRPCClient(mm), nil

	case app.GrantedPermissions.Contains(apps.PermissionActAsUser) && in.ActingUserID != "":
		// The OAuth2 token should be used here once it's implemented
		err := in.ensureUserToken(mm)
		if err != nil {
			return nil, err
		}
		return mmclient.NewHTTPClient(conf, in.ActingUserAccessToken), nil

	case app.GrantedPermissions.Contains(apps.PermissionActAsBot):
		return mmclient.NewHTTPClient(conf, app.BotAccessToken), nil

	default:
		return nil, utils.NewUnauthorizedError("apps without any ActAs* permission can't expand")
	}
}

repository: xaddison/mattermost-plugin-apps

repo_name: xaddison/mattermost-plugin-apps


text:
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"runtime"
	"strings"
)

func checkAndSaveBody(url string, c chan string) {
	resp, err := http.Get(url)

	if err != nil {

		s := fmt.Sprintf("%s is DOWN!\n", url)
		s += fmt.Sprintf("Error: %v  \n", err)

		// Sending the string over the channel.
		// This is a blocking call, so this goroutine will
		// wait for the main goroutine to receive it on the other part of the channel.
		c <- s
	} else {

		s := fmt.Sprintf("Status Code: %d  \n", resp.StatusCode)

		if resp.StatusCode == 200 {
			bodyBytes, err := ioutil.ReadAll(resp.Body)

			file := strings.Split(url, "//")[1]
			file += ".txt"

			s += fmt.Sprintf("Writing response Body to %s\n", file)

			err = ioutil.WriteFile(file, bodyBytes, 0664)
			if err != nil {

				s += "Error writing to file!\n"

				// sending s over the channel
				c <- s
			}
		}
		s += fmt.Sprintf("%s is UP\n", url)

		// sending s over the channel
		c <- s
	}
}

func main() {
	urls := []string{"https://www.golang.org", "https://www.google.com", "https://www.youtube.com", "https://www.facebook.com"}

	// Declaring a new channel
	c := make(chan string)

	for _, url := range urls {
		// Launching the goroutines
		go checkAndSaveBody(url, c)
	}

	fmt.Println("No. of Goroutines:", runtime.NumGoroutine()) // => 5

	// Receiving the messages from the channel
	for i := 0; i < len(urls); i++ {
		fmt.Println(<-c)
	}
}


text:
package main

import "fmt"

func PrintHelloWorld() string {
	return "Hello, world.\n"
}

func main() {
	fmt.Printf(PrintHelloWorld())
}