text:
DESCRIPTION = "Convenient dbus api in lua."
LICENSE = "MIT"
HOMEPAGE = "https://github.com/dodo/lua-dbus"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

DEPENDS += "luajit lua5.1 ldbus"

SRC_URI = "git://github.com/dodo/lua-dbus.git;protocol=git \
		   file://ldbus_fixes.patch \
		   "

SRCREV = "cdef26d09aa61d7f1f175675040383f6ae0becbb"
S = "${WORKDIR}/git/"

LUA_MODULEDIR = "${D}/usr/local/share/lua/5.1"
LUAJIT_VERSION = "2.0.4"
LUAJIT_MODULEDIR = "${D}/usr/local/share/luajit-${LUAJIT_VERSION}"

do_install() {
	install -d ${LUA_MODULEDIR}/lua-dbus/awesome
	install -d ${LUAJIT_MODULEDIR}/lua-dbus/awesome

	cp ${S}/awesome/init.lua ${LUA_MODULEDIR}/lua-dbus/awesome
	cp ${S}/awesome/init.lua ${LUAJIT_MODULEDIR}/lua-dbus/awesome

	cp ${S}/awesome/dbus.lua ${LUA_MODULEDIR}/lua-dbus/awesome
	cp ${S}/awesome/dbus.lua ${LUAJIT_MODULEDIR}/lua-dbus/awesome

	cp ${S}/init.lua ${LUA_MODULEDIR}/lua-dbus
	cp ${S}/init.lua ${LUAJIT_MODULEDIR}/lua-dbus

	cp ${S}/interface.lua ${LUA_MODULEDIR}/lua-dbus
	cp ${S}/interface.lua ${LUAJIT_MODULEDIR}/lua-dbus
}

FILES_${PN} += "${prefix}"

repository: chandu-tmba/MORF-OpenBMC

repo_name: chandu-tmba/MORF-OpenBMC


text:
@phdthesis{mastalli17phd,
  author={Mastalli, Carlos},
  title={{Planning and Execution of Dynamic Whole-Body Locomotion on Challenging Terrain}},
  school={Istituto Italiano di Tecnologia (IIT) and University of Genova},
  year={2017}
}

license: Unlicense,MIT

detected_licenses: Unlicense MIT

license_type: permissive

branch_name: refs/heads/master

extension: bib


text:
inherit esw_examples features_check

REQUIRED_DISTRO_FEATURES = "axiethernet"

ESW_COMPONENT_SRC = "/XilinxProcessorIPLib/drivers/axiethernet/examples/"

license: MIT

repository: fullstackfpga/meta-xilinx

repo_name: fullstackfpga/meta-xilinx

gha_license_id: MIT

extension: bb


text:
// Package cachedrander provides a reader designed to cache random data for the
// creation of random UUIDs.  Using rand.Reader as the source of random data
// (the default for github.com/google/uuid) requires a mutex operation per newly
// minted version 4 (random) UUID.  This package typically only requires a
// single atomic.AddUint64 per newly minted UUID.
//
// This package works by having two pages of cached random data.  The first page
// is read when the CachedReader is created.  Once that page has been exhausted
// Read calls will block on a mutex while the second page is being loaded.
//
// This package has a theoretical race condition:
//
// Caller A reads the index of its data in the current page and is prempted.
// Prior to resuming a sufficent number of calls to Read are made to exhaust the
// current page and the next loaded page.  It is now possible for caller A to
// return the same data as another caller.
//
// to mitigate this condition the CachedReader should use a sufficiently large
// cache that the probability of this happening is essentially 0.
package cachedrander

import (
	"crypto/rand"
	"io"
	"sync"
	"sync/atomic"
)

// A CachedReader caches chunks of data from a reader and then provides that
// data to calls to its Read method.
//
// The Max value determines the maximum size read that will be honored.  This
// defaults to 16 (the size of a UUID).  Max should only be set prior to the
// first Read of the CachedReader.  Max should be multiple times smaller than
// the size of the cache.
type CachedReader struct {
	Max int

	mu    sync.Mutex
	pages [2][]byte
	size  uint64
	index uint64
	r     io.Reader
}

// NewUUIDReader returns a CachedReader that caches n UUID's worth of data from
// rand.Reader at a time.  The value of n should be sufficiently large to
// prevent the theoretical race conditioned mentioned above (e.g., 100 or 1000)
func NewUUIDReader(n int) (*CachedReader, error) {
	return New(rand.Reader, n*16)
}

// New returns a new CachedReader that caches size bytes from r at a time.  An
// error is returned if filling the initial cache from r returns an error.
func New(r io.Reader, size int) (*CachedReader, error) {
	nr := &CachedReader{
		Max:   16,
		size:  uint64(size),
		pages: [2][]byte{make([]byte, size), make([]byte, size)},
		r:     r,
	}
	// Fill the first cache buffer
	if _, err := io.ReadFull(r, nr.pages[0]); err != nil {
		return nil, err
	}
	return nr, nil
}

const (
	indexBits = 63
	indexMask = (1 << indexBits) - 1
)

// Read fills buf with cached data
func (r *CachedReader) Read(buf []byte) (int, error) {
	if len(buf) > r.Max {
		buf = buf[:r.Max]
	}
	blen := uint64(len(buf))
	for {
		ai := atomic.AddUint64(&r.index, blen)
		page := int(ai >> indexBits)
		i := ai & indexMask
		if i-blen <= r.size {
			return copy(buf, r.pages[page][i-blen:]), nil
		}
		if err := r.fill(); err != nil {
			return 0, err
		}
	}
}

// fill fills in the cache page we are currently not reading from.
func (r *CachedReader) fill() error {
	r.mu.Lock()
	ai := atomic.LoadUint64(&r.index)
	var err error
	if (ai & indexMask) > r.size {
		page := (ai >> indexBits) ^ 1
		_, err = io.ReadFull(r.r, r.pages[page])
		atomic.StoreUint64(&r.index, uint64(page)<<indexBits)
	}
	r.mu.Unlock()
	return err
}

repository: pborman/cachedrander

repo_name: pborman/cachedrander

extension: go


text:
package design

import (
	"net/http"
	"os"

	// . "github.com/goadesign/goa/design"
	. "github.com/goadesign/goa/design/apidsl"
)

var _ = API("URL shortner API", func() {
	Title("The URL Shortner API")
	Description("An API for a URL shortner")
	Contact(func() {
		Name(os.Getenv("DEV_NAME"))
		Email(os.Getenv("DEV_EMAIL"))
	})
	Host(os.Getenv("HOST"))
	Scheme("http")
	BasePath("/api/")
	Origin("*", func() {
		Headers("Content-Type")
		Methods(
			http.MethodGet,
			http.MethodPost,
			http.MethodPatch,
			http.MethodDelete,
			http.MethodPut,
			http.MethodOptions,
		)
	})
	Consumes("application/json")
	Produces("application/json")
})

repository: nikhil-thomas/technik-dojo

repo_name: nikhil-thomas/technik-dojo

gha_language: Go


text:
inherit ti-pdk

COMPATIBLE_MACHINE_append = "|c66x"

require rm-lld.inc

PR = "${INC_PR}.2"

PACKAGE_ARCH = "${MACHINE_ARCH}"

# HTML doc link params
PDK_COMP_LINK_TEXT = "RM LLD"

repository: bjornwilliam/meta-ti

repo_name: bjornwilliam/meta-ti


text:
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	utls "github.com/ulixee/utls"
)

func main() {
	var socketPath = os.Args[1]
	var connectArgs = ConnectArgs{}
	var uTlsConn *utls.UConn

	// also make a signals channel
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		_, err := fmt.Scanf("disconnect")
		if err != nil {
			panic(err)
		}
		sigc <- syscall.SIGINT
	}()

	json.Unmarshal([]byte(os.Args[2]), &connectArgs)

	debug := connectArgs.Debug

	domainSocketPiper := &DomainSocketPiper{
		Path:  socketPath,
		debug: connectArgs.Debug,
		keepAlive: connectArgs.KeepAlive,
	}

	if debug {
		fmt.Printf("Serving at socket path %+s. ConnectArgs %#v\n", socketPath, connectArgs)
	}

	domainSocketPiper.Listen()

	addr := fmt.Sprintf("%s:%s", connectArgs.Host, connectArgs.Port)
	dialConn, err := Dial(addr, connectArgs)

	if err != nil {
		log.Fatalf("Dial (proxy/remote) Error: %+v\n", err)
	}

	fmt.Printf("[DomainSocketPiper.Dialed] Remote: %s, Local: %s\n", dialConn.RemoteAddr(), dialConn.LocalAddr())

	defer dialConn.Close()

	if connectArgs.IsSsl {
		uTlsConn = EmulateTls(dialConn, addr, connectArgs)
		if debug {
			fmt.Printf("SSL Connected %s\n", addr)
		}
	}

	fmt.Println("[DomainSocketPiper.ReadyForConnect]")
	domainSocketPiper.WaitForClient()

	var protocol string
	if uTlsConn != nil {
		protocol = uTlsConn.ConnectionState().NegotiatedProtocol
	}
	// print message for listening creator to handle
	fmt.Printf("[DomainSocketPiper.Connected] ALPN: %s\n", protocol)

	if uTlsConn != nil {
		domainSocketPiper.Pipe(uTlsConn, sigc)
	} else {
		domainSocketPiper.Pipe(dialConn, sigc)
	}
}

type ConnectArgs struct {
	Host               string
	Port               string
	IsSsl              bool
	Servername         string
	RejectUnauthorized bool
	ProxyUrl           string
	ClientHelloId      string
	TcpTtl             int
	TcpWindowSize      int
	Debug              bool
	KeepAlive          bool
}

gha_language: TypeScript


text:
package entity

import "github.com/globalsign/mgo/bson"

type Payment struct {
	ID      bson.ObjectId `bson:"_id,omitempty"`
	OrderID bson.ObjectId `bson:"order_id"`
	UserID  string        `bson:"user_id"`
	Status  string        `bson:"status"`
}

const (
	PaymentStatusNew      = "new"
	PaymentStatusPaid     = "paid"
	PaymentStatusCanceled = "canceled"
)

repository: spplatform/kazan-backend

repo_name: spplatform/kazan-backend


text:
package v2

import (
	"errors"
	"net/http"
	"strings"

	"github.com/RTradeLtd/Temporal/eh"
	"github.com/RTradeLtd/database/v2/models"
	nexus "github.com/RTradeLtd/grpc/nexus"
	"github.com/gin-gonic/gin"
)

// these API calls are used to handle management of private IPFS networks

// CreateIPFSNetwork is used to create an entry in the database for a private ipfs network
func (api *API) createIPFSNetwork(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	// extract network name
	networkName, exists := c.GetPostForm("network_name")
	if !exists {
		FailWithMissingField(c, "network_name")
		return
	}
	// make sure the name is something other than public
	if strings.ToLower(networkName) == "public" {
		Fail(c, errors.New("network name can't be public, or PUBLIC"))
	}
	// retrieve parameters - thse are all optional
	swarmKey, _ := c.GetPostForm("swarm_key")
	bPeers, _ := c.GetPostFormArray("bootstrap_peers")
	users := c.PostFormArray("users")
	if users == nil {
		users = []string{username}
	} else {
		users = append(users, username)
	}
	// create the network in our database
	network, err := api.nm.CreateHostedPrivateNetwork(networkName, swarmKey, bPeers, models.NetworkAccessOptions{Users: users, Owner: username})
	if err != nil {
		api.LogError(c, err, eh.NetworkCreationError)(http.StatusBadRequest)
		return
	}
	// request orchestrator to start up network and create it after registering it in the database
	resp, err := api.orch.StartNetwork(c, &nexus.NetworkRequest{
		Network: networkName,
	})
	if err != nil {
		api.LogError(c, err, "failed to start private network",
			"network_name", networkName,
		)(http.StatusBadRequest)
		return
	}
	logger := api.l.With("user", username, "network_name", networkName)
	logger.Info("network creation request received")
	logger.With("db_id", network.ID).Info("database entry created")
	// update allows users who can access the network
	if len(users) > 0 {
		for _, v := range users {
			if err := api.um.AddIPFSNetworkForUser(v, networkName); err != nil && err.Error() != "network already configured for user" {
				api.LogError(c, err, eh.NetworkCreationError)(http.StatusBadRequest)
				return
			}
			api.l.With("user", v).Info("network added to user)")
		}
	}
	api.l.With("response", resp).Info("network node started")
	// respond with network details
	Respond(c, http.StatusOK, gin.H{
		"response": gin.H{
			"id":           network.ID,
			"peer_id":      resp.GetPeerId(),
			"network_name": networkName,
			"swarm_key":    resp.GetSwarmKey(),
			"users":        network.Users,
		},
	})
}

func (api *API) startIPFSPrivateNetwork(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	// get network name
	networkName, exists := c.GetPostForm("network_name")
	if !exists {
		FailWithMissingField(c, "network_name")
		return
	}
	logger := api.l.With("user", username, "network_name", networkName)
	logger.Info("private ipfs network start requested")
	if err := api.isNetworkOwner(networkName, username); err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusUnauthorized)
		return
	}
	if _, err := api.orch.StartNetwork(c, &nexus.NetworkRequest{
		Network: networkName}); err != nil {
		api.LogError(c, err, "failed to start network")(http.StatusBadRequest)
		return
	}
	// log and return
	logger.Info("network started")
	Respond(c, http.StatusOK, gin.H{
		"response": gin.H{
			"network_name": networkName,
			"state":        "started",
		},
	})
}

func (api *API) stopIPFSPrivateNetwork(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	// get network name
	networkName, exists := c.GetPostForm("network_name")
	if !exists {
		FailWithMissingField(c, "network_name")
		return
	}
	logger := api.l.With("user", username, "network_name", networkName)
	logger.Info("private ipfs network shutdown requested")
	// verify admin access to network
	if err := api.isNetworkOwner(networkName, username); err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusUnauthorized)
		return
	}
	// send a stop network request
	if _, err := api.orch.StopNetwork(c, &nexus.NetworkRequest{
		Network: networkName}); err != nil {
		api.LogError(c, err, "failed to stop network")(http.StatusBadRequest)
		return
	}
	// log and return
	logger.Info("network stopped")
	Respond(c, http.StatusOK, gin.H{
		"response": gin.H{
			"network_name": networkName,
			"state":        "stopped",
		},
	})
}

func (api *API) removeIPFSPrivateNetwork(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	// get the network name
	networkName, exists := c.GetPostForm("network_name")
	if !exists {
		FailWithMissingField(c, "network_name")
		return
	}
	logger := api.l.With("user", username, "network_name", networkName)
	logger.Info("private ipfs network shutdown requested")
	// verify admin access to network
	network, err := api.nm.GetNetworkByName(networkName)
	if err != nil {
		api.LogError(c, err, eh.NetworkSearchError)(http.StatusInternalServerError)
		return
	}
	if err := api.isNetworkOwner(networkName, username); err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusUnauthorized)
		return
	}
	// send node removal request, removing all data stored
	// this is a DESTRUCTIVE action
	if _, err = api.orch.RemoveNetwork(c, &nexus.NetworkRequest{
		Network: networkName}); err != nil {
		api.LogError(c, err, "failed to remove network assets")(http.StatusBadRequest)
		return
	}
	// remove network from database
	if err = api.nm.Delete(networkName); err != nil {
		api.LogError(c, err, "failed to remove network from database")(http.StatusBadRequest)
		return
	}
	// remove network from users authorized networks
	for _, v := range network.Users {
		if err = api.um.RemoveIPFSNetworkForUser(v, networkName); err != nil {
			api.LogError(c, err, "failed to remove network from users")(http.StatusBadRequest)
			return
		}
	}
	// log and return
	logger.Info("network removed")
	Respond(c, http.StatusOK, gin.H{
		"response": gin.H{
			"network_name": networkName,
			"state":        "removed",
		},
	})
}

// GetIPFSPrivateNetworkByName is used to private ipfs network information
func (api *API) getIPFSPrivateNetworkByName(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	// get the network name
	netName := c.Param("name")
	// get all networks user has access to
	networks, err := api.um.GetPrivateIPFSNetworksForUser(username)
	if err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusBadRequest)
		return
	}
	// ensure they can access this network
	var found bool
	for _, v := range networks {
		if v == netName {
			found = true
			break
		}
	}
	if !found {
		Fail(c, errors.New(eh.PrivateNetworkAccessError))
		return
	}
	logger := api.l.With("user", username, "network_name", netName)
	logger.Info("private ipfs network by name requested")
	// get network details from database
	net, err := api.nm.GetNetworkByName(netName)
	if err != nil {
		api.LogError(c, err, eh.NetworkSearchError)(http.StatusBadRequest)
		return
	}
	// retrieve additional stats if requested
	// otherwise send generic information from the database directly
	if c.Param("stats") == "true" {
		logger.Info("retrieving additional stats from orchestrator")
		stats, err := api.orch.NetworkStats(c, &nexus.NetworkRequest{Network: netName})
		if err != nil {
			api.LogError(c, err, eh.NetworkSearchError)(http.StatusBadRequest)
			return
		}
		// return
		Respond(c, http.StatusOK, gin.H{"response": gin.H{
			"database":      net,
			"network_stats": stats,
		}})
	} else {
		// return
		Respond(c, http.StatusOK, gin.H{"response": gin.H{
			"database": net,
		}})
	}
}

// GetAuthorizedPrivateNetworks is used to retrieve authorized private networks
// an authorized private network is defined as a network a user has API access to
func (api *API) getAuthorizedPrivateNetworks(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	// get all networks the user has access too
	networks, err := api.um.GetPrivateIPFSNetworksForUser(username)
	if err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusBadRequest)
		return
	}
	// log and return
	api.l.Infow("authorized private ipfs network listing requested", "user", username)
	Respond(c, http.StatusOK, gin.H{"response": networks})
}

// addUsersToNetwork is used to add a user to the list of authorized users
// for a given private network.
func (api *API) addUsersToNetwork(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	networkName, exists := c.GetPostForm("network_name")
	if !exists {
		FailWithMissingField(c, "network_name")
		return
	}
	users, exists := c.GetPostFormArray("users")
	if !exists {
		FailWithMissingField(c, "users")
		return
	}
	network, err := api.nm.GetNetworkByName(networkName)
	if err != nil {
		api.LogError(c, err, eh.NetworkSearchError)(http.StatusInternalServerError)
		return
	}
	if err := api.isNetworkOwner(networkName, username); err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusUnauthorized)
		return
	}
	// make sure the user accounts exist
	for _, user := range users {
		if _, err := api.um.FindByUserName(user); err != nil {
			api.LogError(c, err, eh.UserSearchError)(http.StatusInternalServerError)
			return
		}
	}
	// combine both the currrent list of authorized users, and the list of users to add
	network.Users = append(network.Users, users...)
	// update the users field of the database model only
	if err := api.nm.UpdateNetworkByName(networkName, map[string]interface{}{"users": network.Users}); err != nil {
		api.LogError(c, err, "failed to update authorized users for network")
		return
	}
	for _, user := range users {
		if err := api.um.AddIPFSNetworkForUser(user, networkName); err != nil {
			api.LogError(c, err, "failed to update network for user")(http.StatusInternalServerError)
			return
		}
	}
	Respond(c, http.StatusOK, gin.H{"response": "authorized user list updated"})
}

// removeUsersFromNetwork is used to remove a user from being able
// to access a network.
func (api *API) removeUsersFromNetwork(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	networkName, exists := c.GetPostForm("network_name")
	if !exists {
		FailWithMissingField(c, "network_name")
		return
	}
	users, exists := c.GetPostFormArray("users")
	if !exists {
		FailWithMissingField(c, "users")
		return
	}
	network, err := api.nm.GetNetworkByName(networkName)
	if err != nil {
		api.LogError(c, err, eh.NetworkSearchError)(http.StatusInternalServerError)
		return
	}
	if err := api.isNetworkOwner(networkName, username); err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusUnauthorized)
		return
	}
	var (
		usersToRemove = make(map[string]bool)
		newUsers      []string
	)
	for _, user := range users {
		usersToRemove[user] = true
	}
	// iterate over all current users
	// and compare against users to remove list
	// if they aren't found, then we add them
	// to the new users list.
	for _, user := range network.Users {
		if !usersToRemove[user] {
			newUsers = append(newUsers, user)
		}
	}
	if err := api.nm.UpdateNetworkByName(networkName, map[string]interface{}{"users": newUsers}); err != nil {
		api.LogError(c, err, "failed to update authorized users for network")
		return
	}
	for user := range usersToRemove {
		if err := api.um.RemoveIPFSNetworkForUser(user, networkName); err != nil {
			api.LogError(c, err, "failed to remove network from user")
			return
		}
	}
	Respond(c, http.StatusOK, gin.H{"response": "authorized user list updated"})
}

func (api *API) addOwnersToNetwork(c *gin.Context) {
	if !dev {
		Fail(c, errors.New("private networks not supported in production, please use https://dev.api.temporal.cloud"))
		return
	}
	username, err := GetAuthenticatedUserFromContext(c)
	if err != nil {
		api.LogError(c, err, eh.NoAPITokenError)(http.StatusBadRequest)
		return
	}
	networkName, exists := c.GetPostForm("network_name")
	if !exists {
		FailWithMissingField(c, "network_name")
		return
	}
	owners, exists := c.GetPostFormArray("owners")
	if !exists {
		FailWithMissingField(c, "owners")
		return
	}
	if err := api.isNetworkOwner(networkName, username); err != nil {
		api.LogError(c, err, eh.PrivateNetworkAccessError)(http.StatusUnauthorized)
		return
	}
	// make sure the user accounts exist
	for _, owner := range owners {
		if _, err := api.um.FindByUserName(owner); err != nil {
			api.LogError(c, err, eh.UserSearchError)(http.StatusInternalServerError)
			return
		}
	}
	network, err := api.nm.GetNetworkByName(networkName)
	if err != nil { // remove network from users authorized networks
		api.LogError(c, err, eh.NetworkSearchError)(http.StatusInternalServerError)
		return
	}
	network.Owners = append(network.Owners, owners...)
	if err := api.nm.UpdateNetworkByName(networkName, map[string]interface{}{"owners": network.Owners}); err != nil {
		api.LogError(c, err, "failed to update network owners")
		return
	}
	Respond(c, http.StatusOK, gin.H{"response": "network owners updated"})
}

func (api *API) isNetworkOwner(network, username string) error {
	n, err := api.nm.GetNetworkByName(network)
	if err != nil {
		return err
	}
	for _, owner := range n.Owners {
		if owner == username {
			return nil
		}
	}
	return errors.New("user is not owner")
}

repository: xiegeo/Temporal

repo_name: xiegeo/Temporal


text:
DESCRIPTION = "This module has only one function, which is also exported by default:"

SECTION = "libs"
LICENSE = "Artisticv1 | GPLv1+"
PR = "r0"

MAINTAINER=	"Poky <poky@yoctoproject.org>"
HOMEPAGE=	"https://metacpan.org/release/Sub-Name"

LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/Artistic-1.0;md5=cda03bbdc3c1951996392b872397b798 \
file://${COMMON_LICENSE_DIR}/GPL-1.0;md5=e9e36a9de734199567a4d769498f743d"

SRC_URI = "https://cpan.metacpan.org/authors/id/E/ET/ETHER/Sub-Name-0.21.tar.gz"

SRC_URI[md5sum] = "7e7a181e30b3249d0b81585f55e36621"
SRC_URI[sha256sum] = "bd32e9dee07047c10ae474c9f17d458b6e9885a6db69474c7a494ccc34c27117"

S = "${WORKDIR}/Sub-Name-${PV}"

inherit cpan

BBCLASSEXTEND = "native"

repository: CELLINKAB/meta-cpan

repo_name: CELLINKAB/meta-cpan


text:
require x-load.inc

#FILESPATHPKG_prepend = "x-load-git:x-load-git/${MACHINE}"

PV = "1.5.1"
PR ="r3"
PE = "1"

SRCREV_pn-${PN} = "c4289f1bee035dea41536c5ba5e1bc36c7d493c4"
SRC_URI = "git://gitorious.org/x-loader/x-loader.git;branch=master;protocol=git \
"

S = "${WORKDIR}/git"

XLOAD_MACHINE_beagleboard = "omap3530beagle_config"
CONFIG_HEADER_beagleboard = "1"
XLOAD_MACHINE_omap3-touchbook = "omap3530beagle_config"

PACKAGE_ARCH = "${MACHINE_ARCH}"

repository: Angstrom-distribution/meta-ti

repo_name: Angstrom-distribution/meta-ti

gha_language: BlitzBasic


text:
package captcha

import (
	"strings"

	"github.com/dchest/captcha"
	"github.com/labstack/echo"
)

type Config struct {
	SkipLogging bool
	CaptchaPath string
	StdWidth    int
	StdHeight   int
}

var (
	DefaultConfig = Config{
		SkipLogging: true,
		CaptchaPath: "/captcha/",
		StdWidth:    captcha.StdWidth,
		StdHeight:   captcha.StdHeight,
	}
)

func Captcha(conf Config) echo.MiddlewareFunc {
	//Defaults
	if conf.CaptchaPath == "" {
		conf.CaptchaPath = DefaultConfig.CaptchaPath
	}
	if conf.StdWidth == 0 {
		conf.StdWidth = DefaultConfig.StdWidth
	}
	if conf.StdHeight == 0 {
		conf.StdHeight = DefaultConfig.StdHeight
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			request := c.Request()
			method := request.Method
			if method != "GET" {
				return next(c)
			}

			url := request.URL.Path
			if strings.HasPrefix(url, conf.CaptchaPath) {
				if !conf.SkipLogging {
					c.Logger().Debugf("Captcha server, url:%v", url)
				}
				//@TODO 验证码尺寸支持Query参数
				captcha.Server(conf.StdWidth, conf.StdHeight).ServeHTTP(c.Response(), c.Request())
				return nil
			} else {
				return next(c)
			}

		}
	}
}

repository: hb-go/echo-mw

repo_name: hb-go/echo-mw


text:
@Article{Iyengar2012,
  title = {Affect, not ideology: A social identity perspective on polarization},
  author = {Shanto Iyengar and Gaurav Sood and Yphtach Lelkes},
  journal = {Public Opinion Quarterly},
  pages = {405--431},
  year = {2012},
  volume = {76},
  number = {3},
  isbn = {1146488491},
  doi = {10.1093/poq/nfs038},
  keywords = {mypubs},
  url = {https://www.dropbox.com/s/caupbbxpxf8ei9l/nfs038.pdf?dl=1},
  abstract = {The current debate over the extent of polarization in the American mass public focuses on the extent to which partisans' policy preferences have moved. Whereas maximalists claim that partisans' views on policies have become more extreme over time (Abramowitz 2010), minimalists (Fiorina and Abrams 2009) contend that the majority of Americans remain centrist, and that what little centrifugal movement has occurred reflects sorting, i.e., the increased association between partisanship and ideology. We argue in favor of an alternative definition of polarization, based on the classic concept of social distance (Bogardus 1947). Using data from a variety of sources, we demonstrate that both Republicans and Democrats increasingly dislike, even loathe, their opponents. We also find that partisan affect is inconsistently (and perhaps artifactually) founded in policy attitudes. The more plausible account lies in the nature of political campaigns; exposure to messages attacking the out-group reinforces partisans' biased views of their opponents.},
  issn = {0033362X},
  mendeley.tags = {mypubs},
  journaltitle = {Public Opinion Quarterly},
  pubtype = {2},
}

repository: ylelkes/academic-kickstart

repo_name: ylelkes/academic-kickstart


text:
@article{Ruder2017AnOO,
  title={An Overview of Multi-Task Learning in Deep Neural Networks},
  author={Sebastian Ruder},
  journal={CoRR},
  year={2017},
  volume={abs/1706.05098}
}

url: https://raw.githubusercontent.com/Hugh-Shi/DL-NLP-Readings/924e4d189e5660c5b5d4854278f3df755ae2231d/Bibtex/An Overview of Multi-Task Learning in Deep Neural Networks.bib

repository: Hugh-Shi/DL-NLP-Readings

repo_name: Hugh-Shi/DL-NLP-Readings


text:
LICENSE = "LGPL"
DESCRIPTION = "Library for parsing CORBA IDL files"
SECTION = "gnome/libs"
DEPENDS = "glib-2.0"
PR = "r1"

SRC_URI = "http://ftp.gnome.org/pub/GNOME/sources/libIDL/0.8/libIDL-${PV}.tar.bz2"
S = "${WORKDIR}/libIDL-${PV}"

inherit autotools pkgconfig

do_stage() {
	oe_runmake install \
		prefix=${STAGING_DIR} \
		bindir=${STAGING_BINDIR} \
		includedir=${STAGING_INCDIR} \
		libdir=${STAGING_LIBDIR} \
		datadir=${STAGING_DATADIR} \
		infodir=${STAGING_INFODIR}
}

FILES_${PN} = "${libdir}/*.so.*"
FILES_${PN}-dev += " ${bindir}"

repository: Terentyev/familiar-linux

repo_name: Terentyev/familiar-linux


text:
@inproceedings{Wilbur2019,
 author = {Michael Wilbur and Abhishek Dubey and Bruno Leão and Shameek Bhattacharjee},
 bibsource = {dblp computer science bibliography, https://dblp.org},
 biburl = {https://dblp.org/rec/bib/conf/smartcomp/WilburDLB19},
 booktitle = {IEEE International Conference on Smart Computing, SMARTCOMP 2019, Washington, DC, USA},
 category = {selectiveconference},
 doi = {10.1109/SMARTCOMP.2019.00063},
 file = {:Wilbur2019-A_Decentralized_Approach_for_Real_Time_Anomaly_Detection_in_Transportation_Networks.pdf:PDF},
 keywords = {},
 month = {June},
 oldkeywords = {transit, reliability},
 pages = {274--282},
 project = {cps-reliability,smart-transit,smart-cities},
 tag = {ai4cps,platform,decentralization,incident,transit},
 timestamp = {Wed, 16 Oct 2019 14:14:54 +0200},
 title = {A Decentralized Approach for Real Time Anomaly Detection in Transportation Networks},
 url = {https://doi.org/10.1109/SMARTCOMP.2019.00063},
 year = {2019}
}


text:
@inproceedings{LangeY17,
  author    = {Julien Lange and
               Nobuko Yoshida},
  title     = {On the Undecidability of Asynchronous Session Subtyping},
  booktitle = {Foundations of Software Science and Computation Structures - 20th
               International Conference, {FOSSACS} 2017, Held as Part of the European
               Joint Conferences on Theory and Practice of Software, {ETAPS} 2017,
               Uppsala, Sweden, April 22-29, 2017, Proceedings},
  pages     = {441--457},
  year      = {2017},
  crossref  = {DBLP:conf/fossacs/2017},
  url       = {https://doi.org/10.1007/978-3-662-54458-7_26},
  doi       = {10.1007/978-3-662-54458-7_26},
  timestamp = {Sat, 16 Sep 2017 12:09:21 +0200},
  biburl    = {http://dblp.org/rec/bib/conf/fossacs/LangeY17},
  bibsource = {dblp computer science bibliography, http://dblp.org}
}
@proceedings{DBLP:conf/fossacs/2017,
  editor    = {Javier Esparza and
               Andrzej S. Murawski},
  title     = {Foundations of Software Science and Computation Structures - 20th
               International Conference, {FOSSACS} 2017, Held as Part of the European
               Joint Conferences on Theory and Practice of Software, {ETAPS} 2017,
               Uppsala, Sweden, April 22-29, 2017, Proceedings},
  series    = {Lecture Notes in Computer Science},
  volume    = {10203},
  year      = {2017},
  url       = {https://doi.org/10.1007/978-3-662-54458-7},
  doi       = {10.1007/978-3-662-54458-7},
  isbn      = {978-3-662-54457-0},
  timestamp = {Tue, 23 May 2017 01:08:04 +0200},
  biburl    = {http://dblp.org/rec/bib/conf/fossacs/2017},
  bibsource = {dblp computer science bibliography, http://dblp.org}
}

@inproceedings{LangeNTY17,
  author    = {Julien Lange and
               Nicholas Ng and
               Bernardo Toninho and
               Nobuko Yoshida},
  title     = {Fencing off go: liveness and safety for channel-based programming},
  booktitle = {Proceedings of the 44th {ACM} {SIGPLAN} Symposium on Principles of
               Programming Languages, {POPL} 2017, Paris, France, January 18-20,
               2017},
  pages     = {748--761},
  year      = {2017},
  crossref  = {DBLP:conf/popl/2017},
  url       = {http://dl.acm.org/citation.cfm?id=3009847},
  timestamp = {Wed, 28 Dec 2016 13:22:29 +0100},
  biburl    = {http://dblp.org/rec/bib/conf/popl/LangeNTY17},
  bibsource = {dblp computer science bibliography, http://dblp.org}
}
@proceedings{DBLP:conf/popl/2017,
  editor    = {Giuseppe Castagna and
               Andrew D. Gordon},
  title     = {Proceedings of the 44th {ACM} {SIGPLAN} Symposium on Principles of
               Programming Languages, {POPL} 2017, Paris, France, January 18-20,
               2017},
  publisher = {{ACM}},
  year      = {2017},
  url       = {http://doi.acm.org/10.1145/3009837},
  doi       = {10.1145/3009837},
  isbn      = {978-1-4503-4660-3},
  timestamp = {Wed, 28 Dec 2016 13:17:00 +0100},
  biburl    = {http://dblp.org/rec/bib/conf/popl/2017},
  bibsource = {dblp computer science bibliography, http://dblp.org}
}

repository: Radiateurs/KentThesis

path: /Workshop/Assessment 4/biblio(1).bib

repo_name: Radiateurs/KentThesis


text:
SUMMARY = "bash-completions for opkg"
LICENSE = "MIT"

PR = "r1"

LIC_FILES_CHKSUM = "file://${COREBASE}/meta/COPYING.MIT;md5=3da9cfbcb788c80a0384361b4de20420"

SRC_URI = "file://opkg-bash-completion"

do_install() {
    install -d ${D}${datadir}/bash-completion/completions
    install -m 0644 ${WORKDIR}/opkg-bash-completion \
                    ${D}${datadir}/bash-completion/completions/opkg
}

FILES:${PN} = "${datadir}/bash-completion/completions/opkg"
RDEPENDS:${PN} = "bash-completion"

repository: rcn-ee/meta-arago

repo_name: rcn-ee/meta-arago


text:
package db

import (
	"log"

	"gopkg.in/mgo.v2"
)

// GOCAML Database Access Object
var GOCAML *mgo.Database

var (
	// UsersCollection contains users
	UsersCollection = "users"
)

// Connect to MongoDB
func Connect(server string, database string) {
	session, err := mgo.Dial(server)

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

	GOCAML = session.DB(database)
	log.Println("Database authenticated")
}

repository: aureleoules/gocaml

repo_name: aureleoules/gocaml


text:
// Types infers source locations and types from Go expressions.
// and allows enumeration of the type's method or field members.
package types

import (
	"bytes"
	"container/list"
	"fmt"
	"go/build"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"

	"github.com/npat-efault/godef/exp-go/ast"
	"github.com/npat-efault/godef/exp-go/parser"
	"github.com/npat-efault/godef/exp-go/printer"
	"github.com/npat-efault/godef/exp-go/scanner"
	"github.com/npat-efault/godef/exp-go/token"
)

// Type represents the type of a Go expression.
// It can represent a Go package and a Go type as well as the
// usual expression types.
//
type Type struct {
	// Parse-tree representation of the expression's type.
	Node ast.Node

	// The kind of the expression.
	Kind ast.ObjKind

	// The path of the package that the type is relative to.
	Pkg string
}

// MultiValue represents a multiple valued Go
// expression - the result of a function that returns
// more than one value.
type MultiValue struct {
	Types []ast.Expr
}

func (MultiValue) Pos() token.Pos {
	return token.NoPos
}
func (MultiValue) End() token.Pos {
	return token.NoPos
}

var badType = Type{Kind: ast.Bad}

var makeIdent = predecl("make")
var newIdent = predecl("new")
var falseIdent = predecl("false")
var trueIdent = predecl("true")
var iotaIdent = predecl("iota")
var boolIdent = predecl("bool")
var intIdent = predecl("int")
var floatIdent = predecl("float")
var stringIdent = predecl("string")

func predecl(name string) *ast.Ident {
	return &ast.Ident{Name: name, Obj: parser.Universe.Lookup(name)}
}

type Importer func(path string) *ast.Package

// When DefaultImporter is called, it adds any files to FileSet.
var FileSet = token.NewFileSet()

// GoPath is used by DefaultImporter to find packages.
var GoPath = []string{filepath.Join(os.Getenv("GOROOT"), "src", "pkg")}

// DefaultGetPackage looks for the package; if it finds it,
// it parses and returns it. If no package was found, it returns nil.
func DefaultImporter(path string) *ast.Package {
	bpkg, err := build.Default.Import(path, "", 0)
	if err != nil {
		return nil
	}
	pkgs, err := parser.ParseDir(FileSet, bpkg.Dir, isGoFile, 0)
	if err != nil {
		if Debug {
			switch err := err.(type) {
			case scanner.ErrorList:
				for _, e := range err {
					debugp("\t%v: %s", e.Pos, e.Msg)
				}
			default:
				debugp("\terror parsing %s: %v", bpkg.Dir, err)
			}
		}
		return nil
	}
	if pkg := pkgs[bpkg.Name]; pkg != nil {
		return pkg
	}
	if Debug {
		debugp("package not found by ParseDir!")
	}
	return nil
}

// isGoFile returns true if we will consider the file as a
// possible candidate for parsing as part of a package.
// Including _test.go here isn't quite right, but what
// else can we do?
//
func isGoFile(d os.FileInfo) bool {
	return strings.HasSuffix(d.Name(), ".go") &&
		!strings.HasSuffix(d.Name(), "_test.go") &&
		!strings.HasPrefix(d.Name(), ".") &&
		goodOSArch(d.Name())
}

// When Debug is true, log messages will be printed.
var Debug = false

// String is for debugging purposes.
func (t Type) String() string {
	return fmt.Sprintf("Type{%v %q %T %v}", t.Kind, t.Pkg, t.Node, pretty{t.Node})
}

var Panic = true

// Member looks for a member with the given name inside
// the type. For packages, the member can be any exported
// top level declaration inside the package.
func (t Type) Member(name string, importer Importer) *ast.Object {
	debugp("member %v '%s' {", t, name)
	if t.Pkg != "" && !ast.IsExported(name) {
		return nil
	}
	c := make(chan *ast.Object)
	go func() {
		if !Panic {
			defer func() {
				if err := recover(); err != nil {
					log.Printf("panic: %v", err)
					c <- nil
				}
			}()
		}
		doMembers(t, name, importer, func(obj *ast.Object) {
			if obj.Name == name {
				c <- obj
				runtime.Goexit()
			}
		})
		c <- nil
	}()
	m := <-c
	debugp("} -> %v", m)
	return m
}

// Iter returns a channel, sends on it
// all the members of the type, then closes it.
// Members at a shallower depth will be
// sent first.
//
func (t Type) Iter(importer Importer) <-chan *ast.Object {
	// TODO avoid sending members with the same name twice.
	c := make(chan *ast.Object)
	go func() {
		internal := t.Pkg == ""
		doMembers(t, "", importer, func(obj *ast.Object) {
			if internal || ast.IsExported(obj.Name) {
				c <- obj
			}
		})
		close(c)
	}()
	return c
}

// ExprType returns the type for the given expression,
// and the object that represents it, if there is one.
// All variables, methods, top level functions, packages, struct and
// interface members, and types have objects.
// The returned object can be used with DeclPos to find out
// the source location of the definition of the object.
//
func ExprType(e ast.Expr, importer Importer) (obj *ast.Object, typ Type) {
	return exprType(e, false, "", importer)
}

func exprType(n ast.Node, expectTuple bool, pkg string, importer Importer) (xobj *ast.Object, typ Type) {
	debugp("exprType tuple:%v pkg:%s %T %v [", expectTuple, pkg, n, pretty{n})
	defer func() {
		debugp("] -> %p, %v", xobj, typ)
	}()
	switch n := n.(type) {
	case nil:
	case *ast.Ident:
		obj := n.Obj
		if obj == nil || obj.Kind == ast.Bad {
			break
		}
		// A type object represents itself.
		if obj.Kind == ast.Typ {
			// Objects in the universal scope don't live
			// in any package.
			if parser.Universe.Lookup(obj.Name) == obj {
				pkg = ""
			}
			return obj, Type{n, obj.Kind, pkg}
		}
		expr, typ := splitDecl(obj, n)
		switch {
		case typ != nil:
			_, t := exprType(typ, false, pkg, importer)
			if t.Kind != ast.Bad {
				t.Kind = obj.Kind
			}
			return obj, t

		case expr != nil:
			_, t := exprType(expr, false, pkg, importer)
			if t.Kind == ast.Typ {
				debugp("expected value, got type %v", t)
				t = badType
			}
			return obj, t

		default:
			switch n.Obj {
			case falseIdent.Obj, trueIdent.Obj:
				return obj, Type{boolIdent, ast.Con, ""}
			case iotaIdent.Obj:
				return obj, Type{intIdent, ast.Con, ""}
			default:
				return obj, Type{}
			}
		}
	case *ast.LabeledStmt:
		return n.Label.Obj, Type{n, ast.Lbl, pkg}

	case *ast.ImportSpec:
		return nil, Type{n, ast.Pkg, ""}

	case *ast.ParenExpr:
		return exprType(n.X, expectTuple, pkg, importer)

	case *ast.CompositeLit:
		return nil, certify(n.Type, ast.Var, pkg, importer)

	case *ast.FuncLit:
		return nil, certify(n.Type, ast.Var, pkg, importer)

	case *ast.SelectorExpr:
		_, t := exprType(n.X, false, pkg, importer)
		// TODO: method expressions. when t.Kind == ast.Typ,
		// 	mutate a method declaration into a function with
		//	the receiver as first argument
		if t.Kind == ast.Bad {
			break
		}
		obj := t.Member(n.Sel.Name, importer)
		if obj == nil {
			return nil, badType
		}
		if t.Kind == ast.Pkg {
			eobj, et := exprType(&ast.Ident{Name: obj.Name, Obj: obj}, false, t.Pkg, importer)
			et.Pkg = litToString(t.Node.(*ast.ImportSpec).Path)
			return eobj, et
		}
		// a method turns into a function type;
		// the number of formal arguments depends
		// on the class of the receiver expression.
		if fd, ismethod := obj.Decl.(*ast.FuncDecl); ismethod {
			if t.Kind == ast.Typ {
				return obj, certify(methodExpr(fd), ast.Fun, t.Pkg, importer)
			}
			return obj, certify(fd.Type, ast.Fun, t.Pkg, importer)
		} else if obj.Kind == ast.Typ {
			return obj, certify(&ast.Ident{Name: obj.Name, Obj: obj}, ast.Typ, t.Pkg, importer)
		}
		_, typ := splitDecl(obj, nil)
		return obj, certify(typ, obj.Kind, t.Pkg, importer)

	case *ast.FuncDecl:
		return nil, certify(methodExpr(n), ast.Fun, pkg, importer)

	case *ast.IndexExpr:
		_, t0 := exprType(n.X, false, pkg, importer)
		t := t0.Underlying(true, importer)
		switch n := t.Node.(type) {
		case *ast.ArrayType:
			return nil, certify(n.Elt, ast.Var, t.Pkg, importer)
		case *ast.MapType:
			t := certify(n.Value, ast.Var, t.Pkg, importer)
			if expectTuple {
				return nil, Type{MultiValue{[]ast.Expr{t.Node.(ast.Expr), predecl("bool")}}, ast.Var, t.Pkg}
			}
			return nil, t
		}

	case *ast.SliceExpr:
		_, typ := exprType(n.X, false, pkg, importer)
		return nil, typ

	case *ast.CallExpr:
		switch exprName(n.Fun) {
		case makeIdent.Obj:
			if len(n.Args) > 0 {
				return nil, certify(n.Args[0], ast.Var, pkg, importer)
			}
		case newIdent.Obj:
			if len(n.Args) > 0 {
				t := certify(n.Args[0], ast.Var, pkg, importer)
				if t.Kind != ast.Bad {
					return nil, Type{&ast.StarExpr{n.Pos(), t.Node.(ast.Expr)}, ast.Var, t.Pkg}
				}
			}
		default:
			if _, fntype := exprType(n.Fun, false, pkg, importer); fntype.Kind != ast.Bad {
				// A type cast transforms a type expression
				// into a value expression.
				if fntype.Kind == ast.Typ {
					fntype.Kind = ast.Var
					// Preserve constness if underlying expr is constant.
					if len(n.Args) == 1 {
						_, argtype := exprType(n.Args[0], false, pkg, importer)
						if argtype.Kind == ast.Con {
							fntype.Kind = ast.Con
						}
					}
					return nil, fntype
				}
				// A function call operates on the underlying type,
				t := fntype.Underlying(true, importer)
				if fn, ok := t.Node.(*ast.FuncType); ok {
					return nil, certify(fields2type(fn.Results), ast.Var, t.Pkg, importer)
				}
			}
		}

	case *ast.StarExpr:
		if _, t := exprType(n.X, false, pkg, importer); t.Kind != ast.Bad {
			if t.Kind == ast.Typ {
				return nil, Type{&ast.StarExpr{n.Pos(), t.Node.(ast.Expr)}, ast.Typ, t.Pkg}
			}
			if n, ok := t.Node.(*ast.StarExpr); ok {
				return nil, certify(n.X, ast.Var, t.Pkg, importer)
			}
		}

	case *ast.TypeAssertExpr:
		t := certify(n.Type, ast.Var, pkg, importer)
		if expectTuple && t.Kind != ast.Bad {
			return nil, Type{MultiValue{[]ast.Expr{t.Node.(ast.Expr), predecl("bool")}}, ast.Var, t.Pkg}
		}
		return nil, t

	case *ast.UnaryExpr:
		if _, t := exprType(n.X, false, pkg, importer); t.Kind != ast.Bad {
			u := t.Underlying(true, importer)
			switch n.Op {
			case token.ARROW:
				if ct, ok := u.Node.(*ast.ChanType); ok {
					t := certify(ct.Value, ast.Var, u.Pkg, importer)
					if expectTuple && t.Kind != ast.Bad {
						return nil, Type{MultiValue{[]ast.Expr{t.Node.(ast.Expr), predecl("bool")}}, ast.Var, t.Pkg}
					}
					return nil, certify(ct.Value, ast.Var, u.Pkg, importer)
				}
			case token.RANGE:
				switch n := u.Node.(type) {
				case *ast.ArrayType:
					if expectTuple {
						return nil, Type{MultiValue{[]ast.Expr{predecl("int"), n.Elt}}, ast.Var, u.Pkg}
					}

					return nil, Type{predecl("bool"), ast.Var, ""}

				case *ast.MapType:
					if expectTuple {
						return nil, Type{MultiValue{[]ast.Expr{n.Key, n.Value}}, ast.Var, u.Pkg}
					}
					return nil, certify(n.Key, ast.Var, u.Pkg, importer)

				case *ast.ChanType:
					return nil, certify(n.Value, ast.Var, u.Pkg, importer)
				}

			case token.AND:
				if t.Kind == ast.Var {
					return nil, Type{&ast.StarExpr{n.Pos(), t.Node.(ast.Expr)}, ast.Var, t.Pkg}
				}

			case token.NOT:
				return nil, Type{predecl("bool"), t.Kind, ""}

			default:
				return nil, t
			}
		}

	case *ast.BinaryExpr:
		switch n.Op {
		case token.LSS, token.EQL, token.GTR, token.NEQ, token.LEQ, token.GEQ, token.ARROW, token.LOR, token.LAND:
			_, t := exprType(n.X, false, pkg, importer)
			if t.Kind == ast.Con {
				_, t = exprType(n.Y, false, pkg, importer)
			}
			return nil, Type{predecl("bool"), t.Kind, ""}

		case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.AND_NOT, token.XOR:
			_, tx := exprType(n.X, false, pkg, importer)
			_, ty := exprType(n.Y, false, pkg, importer)
			switch {
			case tx.Kind == ast.Bad || ty.Kind == ast.Bad:

			case !isNamedType(tx, importer):
				return nil, ty
			case !isNamedType(ty, importer):
				return nil, tx
			}
			// could check type equality
			return nil, tx

		case token.SHL, token.SHR:
			_, typ := exprType(n.X, false, pkg, importer)
			return nil, typ
		}

	case *ast.BasicLit:
		var id *ast.Ident
		switch n.Kind {
		case token.STRING:
			id = stringIdent

		case token.INT, token.CHAR:
			id = intIdent

		case token.FLOAT:
			id = floatIdent

		default:
			debugp("unknown constant type %v", n.Kind)
		}
		if id != nil {
			return nil, Type{id, ast.Con, ""}
		}

	case *ast.StructType, *ast.ChanType, *ast.MapType, *ast.ArrayType, *ast.InterfaceType, *ast.FuncType:
		return nil, Type{n.(ast.Node), ast.Typ, pkg}

	case MultiValue:
		return nil, Type{n, ast.Typ, pkg}

	case *exprIndex:
		_, t := exprType(n.x, true, pkg, importer)
		if t.Kind != ast.Bad {
			if ts, ok := t.Node.(MultiValue); ok {
				if n.i < len(ts.Types) {
					return nil, certify(ts.Types[n.i], ast.Var, t.Pkg, importer)
				}
			}
		}
	case *ast.Ellipsis:
		t := certify(n.Elt, ast.Var, pkg, importer)
		if t.Kind != ast.Bad {
			return nil, Type{&ast.ArrayType{n.Pos(), nil, t.Node.(ast.Expr)}, ast.Var, t.Pkg}
		}

	default:
		panic(fmt.Sprintf("unknown type %T", n))
	}
	return nil, badType
}

// litToString converts from a string literal to a regular string.
func litToString(lit *ast.BasicLit) (v string) {
	if lit.Kind != token.STRING {
		panic("expected string")
	}
	v, err := strconv.Unquote(string(lit.Value))
	if err != nil {
		panic("cannot unquote")
	}
	return v
}

// doMembers iterates through a type's members, calling
// fn for each member. If name is non-empty, it looks
// directly for members with that name when possible.
// It uses the list q as a queue to perform breadth-first
// traversal, as per the Go specification.
func doMembers(typ Type, name string, importer Importer, fn func(*ast.Object)) {
	switch t := typ.Node.(type) {
	case nil:
		return

	case *ast.ImportSpec:
		path := litToString(t.Path)
		if pkg := importer(path); pkg != nil {
			doScope(pkg.Scope, name, fn, path)
		}
		return
	}

	q := list.New()
	q.PushBack(typ)
	for e := q.Front(); e != nil; e = q.Front() {
		doTypeMembers(e.Value.(Type), name, importer, fn, q)
		q.Remove(e)
	}
}

// doTypeMembers calls fn for each member of the given type,
// at one level only. Unnamed members are pushed onto the queue.
func doTypeMembers(t Type, name string, importer Importer, fn func(*ast.Object), q *list.List) {
	// strip off single indirection
	// TODO: eliminate methods disallowed when indirected.
	if u, ok := t.Node.(*ast.StarExpr); ok {
		_, t = exprType(u.X, false, t.Pkg, importer)
	}
	if id, _ := t.Node.(*ast.Ident); id != nil && id.Obj != nil {
		if scope, ok := id.Obj.Type.(*ast.Scope); ok {
			doScope(scope, name, fn, t.Pkg)
		}
	}
	u := t.Underlying(true, importer)
	switch n := u.Node.(type) {
	case *ast.StructType:
		doStructMembers(n.Fields.List, t.Pkg, importer, fn, q)

	case *ast.InterfaceType:
		doInterfaceMembers(n.Methods.List, t.Pkg, importer, fn)
	}
}

func doInterfaceMembers(fields []*ast.Field, pkg string, importer Importer, fn func(*ast.Object)) {
	// Go Spec: An interface may contain an interface type name T in place of a method
	// specification. The effect is equivalent to enumerating the methods of T explicitly
	// in the interface.

	for _, f := range fields {
		if len(f.Names) > 0 {
			for _, fname := range f.Names {
				fn(fname.Obj)
			}
		} else {
			_, typ := exprType(f.Type, false, pkg, importer)
			typ = typ.Underlying(true, importer)
			switch n := typ.Node.(type) {
			case *ast.InterfaceType:
				doInterfaceMembers(n.Methods.List, typ.Pkg, importer, fn)
			default:
				debugp("unknown anon type in interface: %T\n", n)
			}
		}
	}
}

func doStructMembers(fields []*ast.Field, pkg string, importer Importer, fn func(*ast.Object), q *list.List) {
	// Go Spec: For a value x of type T or *T where T is not an interface type, x.f
	// denotes the field or method at the shallowest depth in T where there
	// is such an f.
	// Thus we traverse shallower fields first, pushing anonymous fields
	// onto the queue for later.

	for _, f := range fields {
		if len(f.Names) > 0 {
			for _, fname := range f.Names {
				fn(fname.Obj)
			}
		} else {
			m := unnamedFieldName(f.Type)
			fn(m.Obj)
			// The unnamed field's Decl points to the
			// original type declaration.
			_, typeNode := splitDecl(m.Obj, nil)
			obj, typ := exprType(typeNode, false, pkg, importer)
			if typ.Kind == ast.Typ {
				q.PushBack(typ)
			} else {
				debugp("unnamed field kind %v (obj %v) not a type; %v", typ.Kind, obj, typ.Node)
			}
		}
	}
}

// unnamedFieldName returns the field name for
// an unnamed field with its type given by ast node t.
//
func unnamedFieldName(t ast.Node) *ast.Ident {
	switch t := t.(type) {
	case *ast.Ident:
		return t

	case *ast.SelectorExpr:
		return t.Sel

	case *ast.StarExpr:
		return unnamedFieldName(t.X)
	}

	panic("no name found for unnamed field")
}

// doScope iterates through all the functions in the given scope, at
// the top level only.
func doScope(s *ast.Scope, name string, fn func(*ast.Object), pkg string) {
	if s == nil {
		return
	}
	if name != "" {
		if obj := s.Lookup(name); obj != nil {
			fn(obj)
		}
		return
	}
	for _, obj := range s.Objects {
		if obj.Kind == ast.Bad || pkg != "" && !ast.IsExported(obj.Name) {
			continue
		}
		fn(obj)
	}
}

// If typ represents a named type, Underlying returns
// the type that it was defined as. If all is true,
// it repeats this process until the type is not
// a named type.
func (typ Type) Underlying(all bool, importer Importer) Type {
	for {
		id, _ := typ.Node.(*ast.Ident)
		if id == nil || id.Obj == nil {
			break
		}
		_, typNode := splitDecl(id.Obj, id)
		_, t := exprType(typNode, false, typ.Pkg, importer)
		if t.Kind != ast.Typ {
			return badType
		}
		typ.Node = t.Node
		typ.Pkg = t.Pkg
		if !all {
			break
		}
	}
	return typ
}

func noParens(typ interface{}) interface{} {
	for {
		if n, ok := typ.(*ast.ParenExpr); ok {
			typ = n.X
		} else {
			break
		}
	}
	return typ
}

// make sure that the type is really a type expression
func certify(typ ast.Node, kind ast.ObjKind, pkg string, importer Importer) Type {
	_, t := exprType(typ, false, pkg, importer)
	if t.Kind == ast.Typ {
		return Type{t.Node, kind, t.Pkg}
	}
	return badType
}

// If n represents a single identifier, exprName returns its object.
func exprName(typ interface{}) *ast.Object {
	switch t := noParens(typ).(type) {
	case *ast.Ident:
		return t.Obj
	case *ast.Object:
		return t
	}
	return nil
}

// exprIndex represents the selection of one member
// of a multiple-value expression, as in
// _, err := fd.Read(...)
type exprIndex struct {
	i int
	x ast.Expr
}

func (e *exprIndex) Pos() token.Pos {
	return token.NoPos
}
func (e *exprIndex) End() token.Pos {
	return token.NoPos
}

// splitDecl splits obj.Decl and returns the expression part and the type part.
// Either may be nil, but not both if the declaration is value.
//
// If id is non-nil, it gives the referring identifier. This is only used
// to determine which node in a type switch is being referred to.
//
func splitDecl(obj *ast.Object, id *ast.Ident) (expr, typ ast.Node) {
	switch decl := obj.Decl.(type) {
	case nil:
		return nil, nil
	case *ast.ValueSpec:
		return splitVarDecl(obj.Name, decl.Names, decl.Values, decl.Type)

	case *ast.TypeSpec:
		return nil, decl.Type

	case *ast.FuncDecl:
		if decl.Recv != nil {
			return decl, decl.Type
		}
		return decl.Body, decl.Type

	case *ast.Field:
		return nil, decl.Type

	case *ast.LabeledStmt:
		return decl, nil

	case *ast.ImportSpec:
		return nil, decl

	case *ast.AssignStmt:
		return splitVarDecl(obj.Name, exprsToIdents(decl.Lhs), decl.Rhs, nil)

	case *ast.GenDecl:
		if decl.Tok == token.CONST {
			return splitConstDecl(obj.Name, decl)
		}
	case *ast.TypeSwitchStmt:
		expr := decl.Assign.(*ast.AssignStmt).Rhs[0].(*ast.TypeAssertExpr).X
		for _, stmt := range decl.Body.List {
			tcase := stmt.(*ast.CaseClause)
			for _, stmt := range tcase.Body {
				if containsNode(stmt, id) {
					if len(tcase.List) == 1 {
						return expr, tcase.List[0]
					}
					return expr, nil
				}
			}
		}
		return expr, nil
	}
	debugp("unknown decl type %T %v", obj.Decl, pretty{obj.Decl})
	return nil, nil
}

// splitVarDecl finds the declaration expression and type from a
// variable declaration (short form or long form).
func splitVarDecl(name string, names []*ast.Ident, values []ast.Expr, vtype ast.Expr) (expr, typ ast.Node) {
	if len(names) == 1 && len(values) == 1 {
		return values[0], vtype
	}
	p := 0
	for i, aname := range names {
		if aname != nil && aname.Name == name {
			p = i
			break
		}
	}
	if len(values) > 1 {
		return values[p], vtype
	}
	if len(values) == 0 {
		return nil, vtype
	}
	return &exprIndex{p, values[0]}, vtype
}

func exprsToIdents(exprs []ast.Expr) []*ast.Ident {
	idents := make([]*ast.Ident, len(exprs))
	for i, e := range exprs {
		idents[i], _ = e.(*ast.Ident)
	}
	return idents
}

// Constant declarations can omit the type, so the declaration for
// a const may be the entire GenDecl - we find the relevant
// clause and infer the type and expression.
func splitConstDecl(name string, decl *ast.GenDecl) (expr, typ ast.Node) {
	var lastSpec *ast.ValueSpec // last spec with >0 values.
	for _, spec := range decl.Specs {
		vspec := spec.(*ast.ValueSpec)
		if len(vspec.Values) > 0 {
			lastSpec = vspec
		}
		for i, vname := range vspec.Names {
			if vname.Name == name {
				if i < len(lastSpec.Values) {
					return lastSpec.Values[i], lastSpec.Type
				}
				return nil, lastSpec.Type
			}
		}
	}
	return nil, nil
}

// funcVisitor allows an ast.Visitor to be implemented
// by a single function.
type funcVisitor func(n ast.Node) bool

func (f funcVisitor) Visit(n ast.Node) ast.Visitor {
	if f(n) {
		return f
	}
	return nil
}

// constainsNode returns true if x is found somewhere
// inside node.
func containsNode(node, x ast.Node) (found bool) {
	ast.Walk(funcVisitor(func(n ast.Node) bool {
		if !found {
			found = n == x
		}
		return !found
	}),
		node)
	return
}

func isNamedType(typ Type, importer Importer) bool {
	return typ.Underlying(false, importer).Node != typ.Node
}

func fields2type(fields *ast.FieldList) ast.Node {
	if fields == nil {
		return MultiValue{nil}
	}
	n := 0
	for _, f := range fields.List {
		j := len(f.Names)
		if j == 0 {
			j = 1
		}
		n += j
	}
	switch n {
	case 0:
		return nil
	case 1:
		return fields.List[0].Type
	}
	elist := make([]ast.Expr, n)
	i := 0
	for _, f := range fields.List {
		j := len(f.Names)
		if j == 0 {
			j = 1
		}
		for ; j > 0; j-- {
			elist[i] = f.Type
			i++
		}
	}
	return MultiValue{elist}
}

// TODO
func methodExpr(fd *ast.FuncDecl) *ast.FuncType {
	return fd.Type
}

// XXX  the following stuff is for debugging - remove later.

func debugp(f string, a ...interface{}) {
	if Debug {
		log.Printf(f, a...)
	}
}

type pretty struct {
	n interface{}
}

func (p pretty) String() string {
	var b bytes.Buffer
	printer.Fprint(&b, FileSet, p.n)
	return b.String()
}

repository: npat-efault/godef

repo_name: npat-efault/godef


text:
///bin/true ; exec /usr/bin/env go run "$0" "$@"
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package main

import (
	"archive/tar"
	"bufio"
	"compress/gzip"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"runtime"
	"strings"
)

var archive = flag.Bool("archive", true, "Whether to archive the output")
var output = flag.String("output", "fuchsia-sdk.tgz", "Name of the archive")
var outDir = flag.String("out-dir", "", "Output directory")
var toolchain = flag.Bool("toolchain", false, "Include toolchain")
var toolchainLibs = flag.Bool("toolchain-lib", true, "Include toolchain libraries in SDK. Typically used when --toolchain is false")
var sysroot = flag.Bool("sysroot", true, "Include sysroot")
var kernelImg = flag.Bool("kernel-img", true, "Include kernel image")
var kernelDebugObjs = flag.Bool("kernel-dbg", true, "Include kernel objects with debug symbols")
var bootdata = flag.Bool("bootdata", true, "Include bootdata")
var qemu = flag.Bool("qemu", true, "Include QEMU binary")
var tools = flag.Bool("tools", true, "Include additional tools")
var verbose = flag.Bool("v", false, "Verbose output")
var dryRun = flag.Bool("n", false, "Dry run - print what would happen but don't actually do it")

type compType int

const (
	dirType compType = iota
	fileType
	customType
)

const x64BuildDir = "out/release-x64"
const armBuildDir = "out/release-arm64"

type component struct {
	flag      *bool  // Flag controlling whether this component should be included
	srcPrefix string // Source path prefix relative to the fuchsia root
	dstPrefix string // Destination path prefix relative to the SDK root
	t         compType
	f         func(src, dst string) error // When t is 'custom', function to run to copy
}

type dir struct {
	flag     *bool
	src, dst string
}

type file struct {
	flag     *bool
	src, dst string
}

var (
	hostOs      string
	hostCpu     string
	components  []component
	privateDirs []string
)

func init() {
	hostCpu = runtime.GOARCH
	if hostCpu == "amd64" {
		hostCpu = "x64"
	}
	hostOs = runtime.GOOS
	if hostOs == "darwin" {
		hostOs = "mac"
	}

	zxBuildDir := "out/build-zircon"
	x64ZxBuildDir := path.Join(zxBuildDir, "build-x64")
	armZxBuildDir := path.Join(zxBuildDir, "build-arm64")
	qemuDir := fmt.Sprintf("buildtools/%s-%s/qemu/", hostOs, hostCpu)

	dirs := []dir{
		{
			qemu,
			qemuDir,
			"qemu",
		},
		{
			tools,
			"out/build-zircon/tools",
			"tools",
		},
		{
			toolchain,
			fmt.Sprintf("buildtools/%s-%s/clang", hostOs, hostCpu),
			"clang",
		},
		{
			// TODO(https://crbug.com/724204): Remove this once Chromium starts using upstream compiler-rt builtins.
			toolchainLibs,
			fmt.Sprintf("buildtools/%s-%s/clang/lib/clang/7.0.0/lib/fuchsia", hostOs, hostCpu),
			"toolchain_libs/clang/7.0.0/lib/fuchsia",
		},
	}

	files := []file{
		{
			kernelImg,
			"out/build-zircon/build-arm64/qemu-zircon.bin",
			"target/aarch64/zircon.bin",
		},
		{
			kernelImg,
			path.Join(armBuildDir, "bootdata-blob-qemu.bin"),
			"target/aarch64/bootdata-blob.bin",
		},
		{
			kernelImg,
			path.Join(armBuildDir, "images/fvm.blk"),
			"target/aarch64/fvm.blk",
		},

		{
			kernelImg,
			"out/build-zircon/build-x64/zircon.bin",
			"target/x86_64/zircon.bin",
		},
		{
			kernelImg,
			path.Join(x64BuildDir, "bootdata-blob-pc.bin"),
			"target/x86_64/bootdata-blob.bin",
		},
		{
			kernelImg,
			path.Join(x64BuildDir, "images/local-pc.esp.blk"),
			"target/x86_64/local.esp.blk",
		},
		{
			kernelImg,
			path.Join(x64BuildDir, "images/zircon-pc.vboot"),
			"target/x86_64/zircon.vboot",
		},
		{
			kernelImg,
			path.Join(x64BuildDir, "images/fvm.blk"),
			"target/x86_64/fvm.blk",
		},
		{
			kernelImg,
			path.Join(x64BuildDir, "images/fvm.sparse.blk"),
			"target/x86_64/fvm.sparse.blk",
		},
		{
			sysroot,
			path.Join(x64BuildDir, "obj/build/images/system_image.manifest.stripped/lib/libc++.so.2"),
			"arch/x64/dist/libc++.so.2",
		},
		{
			sysroot,
			path.Join(armBuildDir, "obj/build/images/system_image.manifest.stripped/lib/libc++.so.2"),
			"arch/arm64/dist/libc++.so.2",
		},
		{
			sysroot,
			path.Join(x64BuildDir, "obj/build/images/system_image.manifest.stripped/lib/libc++abi.so.1"),
			"arch/x64/dist/libc++abi.so.1",
		},
		{
			sysroot,
			path.Join(armBuildDir, "obj/build/images/system_image.manifest.stripped/lib/libc++abi.so.1"),
			"arch/arm64/dist/libc++abi.so.1",
		},
		{
			sysroot,
			path.Join(x64BuildDir, "obj/build/images/system_image.manifest.stripped/lib/libunwind.so.1"),
			"arch/x64/dist/libunwind.so.1",
		},
		{
			sysroot,
			path.Join(armBuildDir, "obj/build/images/system_image.manifest.stripped/lib/libunwind.so.1"),
			"arch/arm64/dist/libunwind.so.1",
		},
		{
			tools,
			path.Join(x64BuildDir, "host_x64/far"),
			"tools/far",
		},
		{
			tools,
			path.Join(x64BuildDir, "host_x64/pm"),
			"tools/pm",
		},
	}

	components = []component{
		{
			kernelDebugObjs,
			x64ZxBuildDir,
			"sysroot/x86_64-fuchsia/debug",
			customType,
			copyKernelDebugObjs,
		},
		{
			kernelDebugObjs,
			x64BuildDir,
			"sysroot/x86_64-fuchsia/debug",
			customType,
			copyIdsTxt,
		},
		{
			kernelDebugObjs,
			armZxBuildDir,
			"sysroot/aarch64-fuchsia/debug",
			customType,
			copyKernelDebugObjs,
		},
		{
			kernelDebugObjs,
			armBuildDir,
			"sysroot/aarch64-fuchsia/debug",
			customType,
			copyIdsTxt,
		},
	}
	for _, d := range dirs {
		components = append(components, component{d.flag, d.src, d.dst, dirType, nil})
	}
	for _, f := range files {
		components = append(components, component{f.flag, f.src, f.dst, fileType, nil})
	}
	privateDirs = []string{
		"arch/arm64/sysroot/include/zircon/device",
		"arch/x64/sysroot/include/zircon/device",
		"sysroot/aarch64-fuchsia/include/zircon/device",
		"sysroot/x86_64-fuchsia/include/zircon/device",
	}
}

func createLayout(manifest, fuchsiaRoot, outDir string) {
	for idx, buildDir := range []string{x64BuildDir, armBuildDir} {
		manifestPath := filepath.Join(fuchsiaRoot, buildDir, "sdk-manifests", manifest)
		cmd := filepath.Join(fuchsiaRoot, "scripts", "sdk", "foundation", "generate.py")
		args := []string{"--manifest", manifestPath, "--output", outDir}
		if idx > 0 {
			args = append(args, "--overlay")
		}
		if *verbose || *dryRun {
			fmt.Println("createLayout", cmd, args)
		}
		if *dryRun {
			return
		}
		out, err := exec.Command(cmd, args...).CombinedOutput()
		if err != nil {
			log.Fatal("create_layout.py failed with output", string(out), "error", err)
		}
	}
}

func copyKernelDebugObjs(src, dstPrefix string) error {
	// The kernel debug information lives in many .elf files in the out directory
	return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() && filepath.Ext(path) == ".elf" {
			if err := copyFile(path, filepath.Join(dstPrefix, path[len(src):])); err != nil {
				return err
			}
		}
		return nil
	})
}

func copyIdsTxt(src, dstPrefix string) error {
	// The ids.txt file has absolute paths but relative paths within the SDK are
	// more useful to users.
	srcIds, err := os.Open(filepath.Join(src, "ids.txt"))
	if err != nil {
		return fmt.Errorf("could not open ids.txt", err)
	}
	defer srcIds.Close()
	if *dryRun {
		return nil
	}
	dstIds, err := os.Create(filepath.Join(dstPrefix, "ids.txt"))
	if err != nil {
		return fmt.Errorf("could not create ids.txt", err)
	}
	defer dstIds.Close()
	scanner := bufio.NewScanner(srcIds)
	cwd, _ := os.Getwd()
	absBase := filepath.Join(cwd, src)
	for scanner.Scan() {
		s := strings.Split(scanner.Text(), " ")
		id, absPath := s[0], s[1]
		relPath, err := filepath.Rel(absBase, absPath)
		if err != nil {
			log.Println("could not create relative path from absolute path", absPath, "and base", absBase, "skipping entry")
		} else {
			fmt.Fprintln(dstIds, id, relPath)
		}
	}
	return nil
}

func copyFile(src, dst string) error {
	if *dryRun {
		return nil
	}

	if err := os.MkdirAll(filepath.Dir(dst), os.ModePerm); err != nil {
		return err
	}

	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	fi, err := in.Stat()
	if err != nil {
		return err
	}

	out, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE, fi.Mode())
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	if err != nil {
		return err
	}

	return nil
}

func copyDir(src, dst string) error {
	if *dryRun {
		return nil
	}

	if err := os.MkdirAll(dst, os.ModePerm); err != nil {
		return err
	}

	infos, err := ioutil.ReadDir(src)
	if err != nil {
		return err
	}

	for _, info := range infos {
		var err error
		if info.IsDir() {
			err = copyDir(filepath.Join(src, info.Name()), filepath.Join(dst, info.Name()))

		} else {
			err = copyFile(filepath.Join(src, info.Name()), filepath.Join(dst, info.Name()))
		}
		if err != nil {
			return err
		}
	}

	return nil
}

func createTar(src, dst string) error {
	if *verbose || *dryRun {
		fmt.Println("Archiving", src, "to", dst)
	}
	if *dryRun {
		return nil
	}

	file, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer file.Close()

	gw := gzip.NewWriter(file)
	defer gw.Close()
	tw := tar.NewWriter(gw)
	defer tw.Close()

	return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		header, err := tar.FileInfoHeader(info, info.Name())
		if err != nil {
			return err
		}

		name, err := filepath.Rel(src, path)
		if err != nil {
			return err
		}
		header.Name = name
		if err := tw.WriteHeader(header); err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}

		file, err := os.Open(path)
		if err != nil {
			return err
		}
		defer file.Close()
		_, err = io.Copy(tw, file)
		return err
	})
}

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, `Usage: ./makesdk.go [flags] /path/to/fuchsia/root

This script creates a Fuchsia SDK containing the specified features and places it into a tarball.

To use, first build a release mode Fuchsia build with the 'runtime' module configured as the
only module.
`)
		flag.PrintDefaults()
	}
	flag.Parse()
	fuchsiaRoot := flag.Arg(0)
	if _, err := os.Stat(fuchsiaRoot); os.IsNotExist(err) {
		flag.Usage()
		log.Fatalf("Fuchsia root not found at \"%v\"\n", fuchsiaRoot)
	}
	if *outDir == "" {
		var err error
		*outDir, err = ioutil.TempDir("", "fuchsia-sdk")
		if err != nil {
			log.Fatal("Could not create temporary directory: ", err)
		}
		defer os.RemoveAll(*outDir)
	} else if _, err := os.Stat(*outDir); os.IsNotExist(err) {
		if err := os.MkdirAll(*outDir, os.ModePerm); err != nil {
			log.Fatalf("Could not create directory %s: %v", *outDir, err)
		}
	}

	createLayout("garnet", fuchsiaRoot, *outDir)

	for _, c := range components {
		if *c.flag {
			src := filepath.Join(fuchsiaRoot, c.srcPrefix)
			dst := filepath.Join(*outDir, c.dstPrefix)
			switch c.t {
			case dirType:
				if err := copyDir(src, dst); err != nil {
					log.Fatalf("failed to copy directory %s to %s: %v", src, dst, err)
				}
			case fileType:
				if err := copyFile(src, dst); err != nil {
					log.Fatalf("failed to copy file %s to %s: %v", src, dst, err)
				}
			case customType:
				if err := c.f(src, dst); err != nil {
					log.Fatalf("failed to copy %s to %s: %v", src, dst, err)
				}
			}
		}
	}
	for _, d := range privateDirs {
		os.RemoveAll(filepath.Join(*outDir, d))
	}
	if *archive {
		if err := createTar(*outDir, *output); err != nil {
			log.Fatalf("failed to compress %s: %v", *outDir, err)
		}
	}
}

repository: jpcoding/scripts

repo_name: jpcoding/scripts


text:
@article{Wilcox-2019-Tundra,
    title = "Tundra shrub expansion may amplify permafrost thaw by advancing snowmelt timing",
    author = "Wilcox, Evan J.  and
      Keim, Dawn  and
      de Jong, Tyler  and
      Walker, Branden  and
      Sonnentag, Oliver  and
      Sniderhan, Anastasia E.  and
      Mann, Philip  and
      Marsh, Philip",
    journal = "Arctic Science, Volume 5, Issue 4",
    volume = "5",
    number = "4",
    year = "2019",
    publisher = "Canadian Science Publishing",
    url = "https://aclanthology.org/G19-181001",
    doi = "10.1139/as-2018-0028",
    pages = "202--217",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

branch_name: refs/heads/main

gha_language: Python


text:
SRC_URI = "file://*"

DESCRIPTION = "Hoeba settings Ziggo/Casema West"

MAINTAINER ?= "Mike Looijmans"
PACKAGE_ARCH = "all"

#keep SRCDATE here rather than in the distro file, as the setting files reside in a local subdirectory
SRCDATE = "20110326"
PV = "${SRCDATE}"
PR = "r0"
PN = "enigma2-plugin-settings-ziggo-casema-west"
PACKAGES = "${PN}"
PROVIDES="virtual/enigma2-settings"

FILES_${PN} = "/etc/enigma2/*"
S="${WORKDIR}"

do_install() {
	install -d ${D}/etc/enigma2
	for f in services bouquets* userbouquet*
	do
		install -m 644 ${f} ${D}/etc/enigma2/${f}
	done
}

gha_language: C


text:
package strutil

import (
	"regexp"
	"strings"
	"unicode"
)

/*************************************************************
 * change string case
 *************************************************************/

// methods aliases
var (
	UpWords = UpperWord
	LoFirst = LowerFirst
	UpFirst = UpperFirst

	Snake = SnakeCase
)

// Title alias of the strings.ToTitle()
func Title(s string) string { return strings.ToTitle(s) }

// Lower alias of the strings.ToLower()
func Lower(s string) string { return strings.ToLower(s) }

// Lowercase alias of the strings.ToLower()
func Lowercase(s string) string { return strings.ToLower(s) }

// Upper alias of the strings.ToUpper()
func Upper(s string) string { return strings.ToUpper(s) }

// Uppercase alias of the strings.ToUpper()
func Uppercase(s string) string { return strings.ToUpper(s) }

// UpperWord Change the first character of each word to uppercase
func UpperWord(s string) string {
	if len(s) == 0 {
		return s
	}

	if len(s) == 1 {
		return strings.ToUpper(s)
	}

	inWord := true
	buf := make([]byte, 0, len(s))

	i := 0
	rs := []rune(s)
	if RuneIsLower(rs[i]) {
		buf = append(buf, []byte(string(unicode.ToUpper(rs[i])))...)
	} else {
		buf = append(buf, []byte(string(rs[i]))...)
	}

	for j := i + 1; j < len(rs); j++ {
		if !RuneIsWord(rs[i]) && RuneIsWord(rs[j]) {
			inWord = false
		}

		if RuneIsLower(rs[j]) && !inWord {
			buf = append(buf, []byte(string(unicode.ToUpper(rs[j])))...)
			inWord = true
		} else {
			buf = append(buf, []byte(string(rs[j]))...)
		}

		if RuneIsWord(rs[j]) {
			inWord = true
		}

		i++
	}

	return string(buf)
}

// LowerFirst lower first char
func LowerFirst(s string) string {
	if len(s) == 0 {
		return s
	}

	rs := []rune(s)
	f := rs[0]

	if 'A' <= f && f <= 'Z' {
		return string(unicode.ToLower(f)) + string(rs[1:])
	}
	return s
}

// UpperFirst upper first char
func UpperFirst(s string) string {
	if len(s) == 0 {
		return s
	}

	rs := []rune(s)
	f := rs[0]

	if 'a' <= f && f <= 'z' {
		return string(unicode.ToUpper(f)) + string(rs[1:])
	}
	return s
}

// SnakeCase convert. eg "RangePrice" -> "range_price"
func SnakeCase(s string, sep ...string) string {
	sepChar := "_"
	if len(sep) > 0 {
		sepChar = sep[0]
	}

	str := toSnakeReg.ReplaceAllStringFunc(s, func(s string) string {
		return sepChar + LowerFirst(s)
	})

	return strings.TrimLeft(str, sepChar)
}

// Camel alias of the CamelCase
func Camel(s string, sep ...string) string { return CamelCase(s, sep...) }

// CamelCase convert string to camel case.
//
// Support:
//
//	"range_price" -> "rangePrice"
//	"range price" -> "rangePrice"
//	"range-price" -> "rangePrice"
func CamelCase(s string, sep ...string) string {
	sepChar := "_"
	if len(sep) > 0 {
		sepChar = sep[0]
	}

	// Not contains sep char
	if !strings.Contains(s, sepChar) {
		return s
	}

	// Get regexp instance
	rgx, ok := toCamelRegs[sepChar]
	if !ok {
		rgx = regexp.MustCompile(regexp.QuoteMeta(sepChar) + "+[a-zA-Z]")
	}

	return rgx.ReplaceAllStringFunc(s, func(s string) string {
		s = strings.TrimLeft(s, sepChar)
		return UpperFirst(s)
	})
}

//
// Indent format multi line text
// from package: github.com/kr/text
//

// Indent inserts prefix at the beginning of each non-empty line of s. The
// end-of-line marker is NL.
func Indent(s, prefix string) string {
	return string(IndentBytes([]byte(s), []byte(prefix)))
}

// IndentBytes inserts prefix at the beginning of each non-empty line of b.
// The end-of-line marker is NL.
func IndentBytes(b, prefix []byte) []byte {
	if len(b) == 0 {
		return b
	}

	bol := true
	res := make([]byte, 0, len(b)+len(prefix)*4)

	for _, c := range b {
		if bol && c != '\n' {
			res = append(res, prefix...)
		}
		res = append(res, c)
		bol = c == '\n'
	}
	return res
}

repository: gookit/goutil

repo_name: gookit/goutil


text:
require gnome-keyring.inc
SRC_URI[archive.md5sum] = "e78cb39f006022a50ccfce1e0806c34e"
SRC_URI[archive.sha256sum] = "d17c996f0917d9fb9d86492d8ff6e834fe76e3231ec355f7016b29d2f960bd63"

repository: nicepixels/citadel

repo_name: nicepixels/citadel


text:
package ascp

// Long 结构体
type Long struct {
	// 币种
	DistributeCurrency string `json:"distribute_currency,omitempty" xml:"distribute_currency,omitempty"`
	// 币种
	RetailCurrency string `json:"retail_currency,omitempty" xml:"retail_currency,omitempty"`
	// 【必传】分销商sellerId
	DistributorShopUserId int64 `json:"distributor_shop_user_id,omitempty" xml:"distributor_shop_user_id,omitempty"`
	// 【必传】分销价
	DistributePrice int64 `json:"distribute_price,omitempty" xml:"distribute_price,omitempty"`
	// 建议零售价
	RetailPrice int64 `json:"retail_price,omitempty" xml:"retail_price,omitempty"`
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao


text:
---
---

@string{aps = {American Physical Society,}}

@article{quantum2023hines,
  doi = {10.48550/ARXIV.2303.08805},
  abbr={arXiv},
  html = {https://arxiv.org/abs/2303.08805},
  pdf = {https://arxiv.org/pdf/2303.08805.pdf},
  author = {Hines, J. A. and Rajagopal, S. V. and Moreau, G. L. and Wahrman, M. D. and Lewis, N. A. and Marković, O. and Schleier-Smith, M.},
  title = {Spin Squeezing by Rydberg Dressing in an Array of Atomic Ensembles},
  journal = {{arXiv}:2303.08805 [quant-ph]},
  year = {2023},
  copyright = {Creative Commons Attribution 4.0 International},
  bibtex_show={true},
  selected={true}
}

@phdthesis{markovic2021quantum,
  abbr={thesis},
	title = {Quantum engineering by Rydberg dressing in a cold atomic gas},
	numpages = {167},
	school =  {Stanford University},
  year = {2021},
	author = {Marković, O.},
	langid = {english},
	url = {https://purl.stanford.edu/tj863pj7694},
  html = {https://purl.stanford.edu/tj863pj7694},
	urldate = {2022-04-30},
  bibtex_show={true},
  selected={true},
}

@article{number2021anikeeva,
  abbr={PRX Quantum},
  title = {Number Partitioning With Grover's Algorithm in Central Spin Systems},
  author = {Anikeeva, G. and Marković, O. and Borish, V. and Hines, J. A. and Rajagopal, S. V. and Cooper, E. S. and Periwal, A. and Safavi-Naeini, A. and Davis, E. J. and Schleier-Smith, M.},
  journal = {PRX Quantum},
  volume = {2},
  issue = {2},
  pages = {020319},
  numpages = {24},
  year = {2021},
  month = {May},
  publisher = {American Physical Society},
  doi = {10.1103/PRXQuantum.2.020319},
  url = {https://link.aps.org/doi/10.1103/PRXQuantum.2.020319},
  html = {https://link.aps.org/doi/10.1103/PRXQuantum.2.020319},
  bibtex_show={true},
  selected={true}
}

@article{transverse-field2020borish,
  abbr={PRL},
  title = {Transverse-Field Ising Dynamics in a Rydberg-Dressed Atomic Gas},
  author = {Borish, V. and Marković, O. and Hines, J. A. and Rajagopal, S. V. and Schleier-Smith, M.},
  journal = {Phys. Rev. Lett.},
  volume = {124},
  issue = {6},
  pages = {063601},
  numpages = {6},
  year = {2020},
  month = {Feb},
  publisher = {American Physical Society},
  doi = {10.1103/PhysRevLett.124.063601},
  url = {https://link.aps.org/doi/10.1103/PhysRevLett.124.063601},
  html = {https://link.aps.org/doi/10.1103/PhysRevLett.124.063601},
  bibtex_show={true},
  selected={true}
}

gha_language: HTML


text:
package testutils

import (
	"google.golang.org/protobuf/types/known/wrapperspb"

	"github.com/limpidchart/lc-api/internal/render/github.com/limpidchart/lc-proto/render/v0"
)

type ChartScale struct {
	*render.ChartScale
}

func NewBandChartScale() *ChartScale {
	// nolint: gomnd
	return &ChartScale{
		&render.ChartScale{
			Kind:       render.ChartScale_BAND,
			RangeStart: &wrapperspb.Int32Value{Value: 0},
			RangeEnd:   &wrapperspb.Int32Value{Value: 100},
			Domain: &render.ChartScale_DomainCategories{
				DomainCategories: &render.DomainCategories{Categories: []string{"A", "B", "C"}},
			},
			NoBoundariesOffset: false,
			InnerPadding:       &wrapperspb.FloatValue{Value: 0.2},
			OuterPadding:       &wrapperspb.FloatValue{Value: 0.2},
		},
	}
}

func NewLinearChartScale() *ChartScale {
	// nolint: gomnd
	return &ChartScale{
		&render.ChartScale{
			Kind:       render.ChartScale_LINEAR,
			RangeStart: &wrapperspb.Int32Value{Value: 11},
			RangeEnd:   &wrapperspb.Int32Value{Value: 111},
			Domain: &render.ChartScale_DomainNumeric{
				DomainNumeric: &render.DomainNumeric{
					Start: 0,
					End:   100,
				},
			},
			NoBoundariesOffset: false,
			InnerPadding:       nil,
			OuterPadding:       nil,
		},
	}
}

func (s *ChartScale) Unembed() *render.ChartScale {
	return s.ChartScale
}

func (s *ChartScale) SetNoBoundariesOffset() *ChartScale {
	s.NoBoundariesOffset = true

	return s
}

func (s *ChartScale) SetRanges(rangeStart, rangeEnd int32) *ChartScale {
	s.RangeStart = &wrapperspb.Int32Value{Value: rangeStart}
	s.RangeEnd = &wrapperspb.Int32Value{Value: rangeEnd}

	return s
}

func (s *ChartScale) UnsetRanges() *ChartScale {
	s.RangeStart = nil
	s.RangeEnd = nil

	return s
}

func (s *ChartScale) UnsetKind() *ChartScale {
	s.Kind = render.ChartScale_UNSPECIFIED_SCALE

	return s
}

func (s *ChartScale) SetNumericDomain() *ChartScale {
	// nolint: gomnd
	s.Domain = &render.ChartScale_DomainNumeric{
		DomainNumeric: &render.DomainNumeric{
			Start: 20,
			End:   40,
		},
	}

	return s
}

func (s *ChartScale) UnsetDomain() *ChartScale {
	s.Domain = nil

	return s
}

func (s *ChartScale) SetPaddings() *ChartScale {
	// nolint: gomnd
	s.InnerPadding = &wrapperspb.FloatValue{Value: 0.1}

	// nolint: gomnd
	s.OuterPadding = &wrapperspb.FloatValue{Value: 0.1}

	return s
}

func (s *ChartScale) InvertRanges() *ChartScale {
	s.RangeStart, s.RangeEnd = s.RangeEnd, s.RangeStart

	return s
}

func (s *ChartScale) SetCategoriesDomain() *ChartScale {
	s.Domain = &render.ChartScale_DomainCategories{
		DomainCategories: &render.DomainCategories{Categories: []string{"a1", "a2"}},
	}

	return s
}

repository: limpidchart/lc-api

repo_name: limpidchart/lc-api


text:
@article{alsentzer2018extractive,
 author = {Alsentzer, Emily and Kim, Anne},
 journal = {arXiv preprint arXiv:1810.12085},
 title = {Extractive Summarization of EHR Discharge Notes},
 year = {2018}
}

repository: EmilyAlsentzer/academic-kickstart

repo_name: EmilyAlsentzer/academic-kickstart

gha_language: Jupyter Notebook


text:
package formatter

import (
	"fmt"
	"testing"

	qt "github.com/frankban/quicktest"
)

func TestLexer(t *testing.T) {
	c := qt.New(t)

	parse := func(c *qt.C, input string) []item {
		items, err := parseTemplate([]byte(input))
		c.Assert(err, qt.IsNil)
		c.Assert(items, qt.Not(qt.IsNil))
		return items
	}

	assertTypes := func(c *qt.C, got []item, expect ...itemType) {
		c.Helper()
		var expectStr string
		var gotStr string
		for _, it := range expect {
			expectStr += fmt.Sprint(it) + ","
		}
		for _, it := range got {
			gotStr += fmt.Sprint(it.typ) + ","
		}
		c.Assert(gotStr, qt.Equals, expectStr)

	}

	c.Run("One define", func(c *qt.C) {
		items := parse(c, `{{ define "main" }}<div>Main</div>{{ end }}`)
		assertTypes(c, items, tActionStart, tBracketOpen, tOther, tBracketClose, tOther,
			tBracketOpen, tOther, tBracketClose, tActionEnd, tEOF)
	})

	c.Run("Two define", func(c *qt.C) {
		items := parse(c, "{{ define \"main\" }}
Main
{{ end }}\n\n{{ define \"other\" }}
Other
{{ end }}")

		assertTypes(c, items,
			tActionStart, tBracketOpen, tOther, tBracketClose, tOther, tBracketOpen, tOther, tBracketClose, tActionEnd,
			tNewline, tNewline,
			tActionStart, tBracketOpen, tOther, tBracketClose, tOther, tBracketOpen, tOther, tBracketClose, tActionEnd, tEOF,
		)
	})

	c.Run("Whitespace", func(c *qt.C) {
		items := parse(c, " \n \n{{ range .Foo }}{{ end }}")

		assertTypes(c, items,
			tSpace,
			tNewline,
			tSpace,
			tNewline,
			tActionStart,
			tActionEnd,
			tEOF)
	})

	c.Run("Template comment", func(c *qt.C) {
		items := parse(c, "{{/* Comment */}}{{ range .Foo }}{{ end }}")

		assertTypes(c, items,
			tComment,
			tActionStart,
			tActionEnd,
			tEOF)
	})

	c.Run("else", func(c *qt.C) {
		items := parse(c, "{{ if .Foo }}FOO{{ else }}BAR{{ end }}")

		assertTypes(c, items,
			tActionStart,
			tOther,
			tActionEndStart,
			tOther,
			tActionEnd,
			tEOF)
	})

	c.Run("else if", func(c *qt.C) {
		items := parse(c, "{{ if .Foo }}FOO{{ else if .Bar }}BAR{{ end }}")

		assertTypes(c, items,
			tActionStart,
			tOther,
			tActionEndStart,
			tOther,
			tActionEnd,
			tEOF)
	})

	c.Run("nested blocks", func(c *qt.C) {
		items := parse(c, `{{ with .Enum }}
Enum:
{{ range . }}
{{ end }}
{{ end }}`)

		assertTypes(c, items,
			tActionStart,
			tNewline,
			tOther,
			tNewline,
			tActionStart,
			tNewline,
			tActionEnd,
			tNewline,
			tActionEnd,
			tEOF)
	})

	c.Run("Template blocks inside HTML attribute", func(c *qt.C) {
		items := parse(c, `<body {{ with .Type }}{{ . }}{{ end }}>`)

		assertTypes(c, items,
			tBracketOpen, tOther, tSpace, tAction, tAction, tAction, tBracketClose, tEOF,
		)
	})

	c.Run("Brackets in text", func(c *qt.C) {
		items := parse(c, `32 < 52 a > b`)

		assertTypes(c, items,
			tOther, tSpace, tOther, tSpace, tOther, tSpace, tOther, tSpace, tOther, tSpace, tOther, tEOF,
		)
	})

	c.Run("Template commands with trim markers", func(c *qt.C) {
		items := parse(c, `{{- with .Type .}}{{ . }}{{- else -}}{{ . }}{{- end -}}`)

		assertTypes(c, items,
			tActionStart, tAction, tActionEndStart, tAction, tActionEnd, tEOF,
		)
	})

	c.Run("block keyword", func(c *qt.C) {
		items := parse(c, `{{ block "title" . }}Title{{ end }}`)

		assertTypes(c, items,
			tActionStart, tOther, tActionEnd, tEOF,
		)
	})

}

repository: bep/gotfmt

repo_name: bep/gotfmt


text:
DESCRIPTION = "Objects of the "HTML::Parser" class will recognize markup and separate it \
from plain text (alias data content) in HTML documents. As different kinds \
of markup and text are recognized, the corresponding event handlers are \
invoked."

SECTION = "libs"
LICENSE = "Artisticv1 | GPLv1+"
PR = "r0"

MAINTAINER=	"Poky <poky@yoctoproject.org>"
HOMEPAGE=	"https://metacpan.org/release/HTML-Parser"

LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/Artistic-1.0;md5=cda03bbdc3c1951996392b872397b798 \
file://${COMMON_LICENSE_DIR}/GPL-1.0;md5=e9e36a9de734199567a4d769498f743d"

SRC_URI = "https://cpan.metacpan.org/authors/id/G/GA/GAAS/HTML-Parser-3.72.tar.gz"

SRC_URI[md5sum] = "eb7505e5f626913350df9dd4a03d54a8"
SRC_URI[sha256sum] = "ec28c7e1d9e67c45eca197077f7cdc41ead1bb4c538c7f02a3296a4bb92f608b"
RDEPENDS_${PN} += "html-tagset-perl"
RRECOMMENDS_${PN} += "http-message-perl"

S = "${WORKDIR}/HTML-Parser-${PV}"

inherit cpan

do_compile() {
       export LIBC="$(find ${STAGING_DIR_TARGET}/${base_libdir}/ -name 'libc-*.so')"
       cpan_do_compile
}

BBCLASSEXTEND = "native"

repository: CELLINKAB/meta-cpan

repo_name: CELLINKAB/meta-cpan


text:
// Code generated by go-swagger; DO NOT EDIT.

package terms

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"

	"github.com/go-openapi/runtime"

	"github.com/Clever/clever-go/models"
)

// GetSectionsForTermOKCode is the HTTP code returned for type GetSectionsForTermOK
const GetSectionsForTermOKCode int = 200

/*GetSectionsForTermOK OK Response

swagger:response getSectionsForTermOK
*/
type GetSectionsForTermOK struct {

	/*
	  In: Body
	*/
	Payload *models.SectionsResponse `json:"body,omitempty"`
}

// NewGetSectionsForTermOK creates GetSectionsForTermOK with default headers values
func NewGetSectionsForTermOK() *GetSectionsForTermOK {

	return &GetSectionsForTermOK{}
}

// WithPayload adds the payload to the get sections for term o k response
func (o *GetSectionsForTermOK) WithPayload(payload *models.SectionsResponse) *GetSectionsForTermOK {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get sections for term o k response
func (o *GetSectionsForTermOK) SetPayload(payload *models.SectionsResponse) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetSectionsForTermOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

// GetSectionsForTermNotFoundCode is the HTTP code returned for type GetSectionsForTermNotFound
const GetSectionsForTermNotFoundCode int = 404

/*GetSectionsForTermNotFound Entity Not Found

swagger:response getSectionsForTermNotFound
*/
type GetSectionsForTermNotFound struct {

	/*
	  In: Body
	*/
	Payload *models.NotFound `json:"body,omitempty"`
}

// NewGetSectionsForTermNotFound creates GetSectionsForTermNotFound with default headers values
func NewGetSectionsForTermNotFound() *GetSectionsForTermNotFound {

	return &GetSectionsForTermNotFound{}
}

// WithPayload adds the payload to the get sections for term not found response
func (o *GetSectionsForTermNotFound) WithPayload(payload *models.NotFound) *GetSectionsForTermNotFound {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get sections for term not found response
func (o *GetSectionsForTermNotFound) SetPayload(payload *models.NotFound) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetSectionsForTermNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(404)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

repository: Clever/clever-go

repo_name: Clever/clever-go


text:
// Copyright 2019 Migwi Ndung'u.
// License that can be found in the LICENSE file.

// Package types defines the data structures and regular expressions that helps
// to unmarshal commits history string into data to be shared with the outside world.
package types

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

const (
	// DefaultRepo is the default github repository name where Politea Votes
	// are stored.
	DefaultRepo = "mainnet"

	// DefaultRepoOwner is the owner of the default github repository where
	// Politeia votes are stored.
	DefaultRepoOwner = "decred-proposals"

	// DefaultVotesCommitMsg defines the message of the commits that holds
	// the votes data for the various proposal token(s).
	DefaultVotesCommitMsg = "Flush vote journals"

	// CmdDateFormat defines the date format of the time returned by git commandline
	// interface. Time format is known as RFC2822.
	CmdDateFormat = "Mon Jan 2 15:04:05 2006 -0700"

	// journalActionFormat is the format of the journal action struct appended
	// to all votes. Its a struct with the version and the journal action.
	journalActionFormat = `{"version":"[[:digit:]]*","action":"(add)?(del)?(addlike)?"}`
)

var proposalToken string

// semVer defines the semantic version structure.
type semVer struct {
	Major int
	Minor int
	Patch int
}

// minGitVersion defines the minimum supported git version. This version
// allows git log -p --reverse to be run. Here are the release notes:
// https://github.com/git/git/blob/53f9a3e157dbbc901a02ac2c73346d375e24978c/Documentation/RelNotes/1.5.1.txt
var minGitVersion = semVer{1, 5, 1}

// ErrGitVersion is the default error returned if an invalid git version was found.
var ErrGitVersion = errors.New("invalid git version found. A minimum of v" +
	minGitVersion.String() + " was expected")

// String() is the default stringer for the semVer data type.
func (s semVer) String() string {
	return fmt.Sprintf("%d.%d.%d", s.Major, s.Minor, s.Patch)
}

// Confirm that Votes implements the unmarshalling interface.
var _ json.Unmarshaler = (*Votes)(nil)

// History defines the standard single commit history contents to be shared
// with the outside world.
type History struct {
	Author    string
	CommitSHA string
	Date      time.Time
	Patch     []*File
}

// File defines the votes cast for a single token in a commit. A commit can
// votes cast for several commits joined together.
type File struct {
	Token     string
	VotesInfo Votes
}

// Votes defines a slice type of votes cast data.
type Votes []CastVoteData

// CastVoteData defines the struct of a cast vote and the reciept response.
type CastVoteData struct {
	*PiVote `json:"castvote"`
	// Receipt string `json:"receipt"`
}

// PiVote defines the ticket hash and vote bit type details about a vote.
type PiVote struct {
	// Token     string  `json:"token"`
	Ticket  string  `json:"ticket"`
	VoteBit bitCast `json:"votebit"`
	// Signature string  `json:"signature"`
}

// bitCast defines the votebit cast.
type bitCast string

// UnmarshalJSON defines the bitCast unmarshaller that sets the vote id of the
// vote bit cast.
func (b *bitCast) UnmarshalJSON(d []byte) error {
	// bitCast data mapping.
	var data = map[bitCast]string{
		`"1"`: "No",
		`"2"`: "Yes",
		`"3"`: "Unknown", // invalid entry. Wherever its found something went wrong.
	}
	vote, ok := data[bitCast(d)]
	if !ok {
		vote = "Unknown"
	}

	*b = bitCast(vote)
	return nil
}

// ToBitcast casts the vote Id bitCast type.
func ToBitcast(in string) bitCast {
	return bitCast(in)
}

// UnmarshalJSON defines the default unmarshaller for Votes.
func (v *Votes) UnmarshalJSON(b []byte) error {
	// create a custom unmarshalling type to avoid being trapped in
	// an endless loop.
	type votes2 Votes
	var v2 votes2

	err := json.Unmarshal(b, &v2)
	if err != nil {
		return err
	}

	*v = Votes(v2)

	return nil
}

// CustomUnmashaller unmarshals the string argument passed. Its not in a JSON
// format. History unmarshalling happens ONLY for the set proposal token and
// for all proposal tokens available if otherwise (not set).
func CustomUnmashaller(h *History, str string, since ...time.Time) error {
	// If no votes data detected, ignore the current str payload.
	if isMatched := IsMatching(str, DefaultVotesCommitMsg); !isMatched {
		return nil
	}

	date, err := RetrieveCMDDate(str)
	if err != nil {
		return err // Missing Date
	}

	if len(since) > 0 && date.Equal(since[0]) {
		// If this date matches the date in the record being unmarshalled
		// then it already existed earlier on thus ignore it.
		return nil
	}

	commit, err := RetrieveCMDCommit(str)
	if err != nil {
		return err // Missing commit SHA
	}

	author, err := RetrieveCMDAuthor(str)
	if err != nil {
		return err // Missing Author
	}

	var changes []*File

	for _, filePatch := range SplitCommitDiff(str) {

		// If the proposal token has been set, check if this payload has the required
		// proposal token data. If it exists proceed otherwise ignore it.
		if isMatched := IsMatching(filePatch, VotesJSONSignature()); !isMatched {
			continue
		}

		proposalToken, err := RetrieveProposalToken(filePatch)
		if err != nil {
			return err // Missing proposal token
		}

		filePatch = RetrieveAllPatchSelection(filePatch)

		filePatch = ReplaceJournalSelection(filePatch, "")

		// Drop any special characters left.
		filePatch = ReplaceAny(filePatch, `\s`, "")

		// Add the square brackets and commas to complete the JSON string array format.
		filePatch = "[" + ReplaceAny(filePatch, "}{", "},{") + "]"

		var v Votes

		if err = json.Unmarshal([]byte(filePatch), &v); err != nil {
			panic(err)
			return fmt.Errorf("Unmarshalling File failed: %v %s", err, filePatch)
		}

		// If votes data was found, append it the File patch data else ignore it.
		if len(v) > 0 {
			changes = append(changes, &File{proposalToken, v})
		}
	}

	if len(changes) == 0 {
		return nil
	}

	h.Author = author
	h.CommitSHA = commit
	h.Date = date
	h.Patch = changes

	return nil
}

// SetProposalToken sets the current proposal token string whose data is being
// unmarshalled.
func SetProposalToken(token string) error {
	if len(token) == 0 {
		return fmt.Errorf("empty token hash string found")
	}

	proposalToken = token
	return nil
}

// GetProposalToken returns the current proposal token value set.
func GetProposalToken() string {
	return proposalToken
}

// ClearProposalToken deletes the current proposal token value.
func ClearProposalToken() {
	proposalToken = ""
}

license: ISC

repository: dmigwi/go-piparser

repo_name: dmigwi/go-piparser

gha_license_id: ISC


text:
vcpkg_from_github(
    OUT_SOURCE_PATH SOURCE_PATH
    REPO open-source-parsers/jsoncpp
    REF 9059f5cad030ba11d37818847443a53918c327b1 # 1.9.4
    SHA512 8062c83cad9dc453f1eb4886e63e054570e0f29dcd6594330d3b3628ba994915e26e08690cd28118805a766be200ac99ad4fbc131db3af895122a8d1bd87ef31
    HEAD_REF master
)

string(COMPARE EQUAL "${VCPKG_LIBRARY_LINKAGE}" "static" JSONCPP_STATIC)

vcpkg_configure_cmake(
    SOURCE_PATH ${SOURCE_PATH}
    PREFER_NINJA
    OPTIONS
        -DJSONCPP_WITH_CMAKE_PACKAGE=ON
        -DBUILD_STATIC_LIBS=${JSONCPP_STATIC}
        -DJSONCPP_WITH_PKGCONFIG_SUPPORT=OFF
        -DJSONCPP_WITH_POST_BUILD_UNITTEST=OFF
        -DJSONCPP_WITH_TESTS=OFF
        -DJSONCPP_WITH_EXAMPLE=OFF
)

vcpkg_install_cmake()

vcpkg_fixup_cmake_targets(CONFIG_PATH lib/cmake/jsoncpp)

file(REMOVE_RECURSE ${CURRENT_PACKAGES_DIR}/debug/include)

vcpkg_copy_pdbs()

file(INSTALL ${SOURCE_PATH}/LICENSE DESTINATION ${CURRENT_PACKAGES_DIR}/share/${PORT} RENAME copyright)

gha_license_id: NOASSERTION

extension: cmake


text:
package store

import (
	"encoding/json"
	"github.com/crawlerclub/x/types"
	"io/ioutil"
	"reflect"
	"testing"
)

func TestUtil(t *testing.T) {
	var conf types.CrawlerConf
	bytes, err := ioutil.ReadFile("www.newsmth.net.json")
	if err != nil {
		t.Error(err)
	}
	err = json.Unmarshal(bytes, &conf)
	if err != nil {
		t.Error(err)
	}

	ret1, err := ObjectToBytes(conf)
	if err != nil {
		t.Error(err)
	}

	var object types.CrawlerConf
	err = BytesToObject(ret1, &object)
	if err != nil {
		t.Error(err)
	}

	if !reflect.DeepEqual(object, conf) {
		t.Error("object:", object)
	}
}

repository: liuzl/store

repo_name: liuzl/store


text:
package magic

import (
	"fmt"
	"testing"
)

func TestMagic2(t *testing.T) {
	res := Magic(2)
	if !res {
		t.Error("2 should be the magic numer")
	}
}

func TestMagic3(t *testing.T) {
	res := Magic(3)
	if !res {
		t.Error("3 should be the magic numer")
	}
}
func TestMagic6(t *testing.T) {
	res := Magic(6)
	if res {
		t.Error("6 should not be the magic numer")
	}
}

func ExampleMagic() {
	fmt.Println(Magic(5, 6, 7))
	// Output:
	// true
}

func ExampleMagic_second() {
	fmt.Println(Magic(10))
	// Output:
	// false
}

func BenchmarkMagic(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Magic(111, 1111, 1111, 111231, 123, 123, 123, 1231, 24, 455, 41, 231, 45, 123, 123, 1234)
	}
}

repository: taylorzhangyx/golearning

repo_name: taylorzhangyx/golearning


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"

	_ "github.com/gsempe/apns/core"
	"github.com/streadway/amqp"
)

// MsgPushNotification is the message send from the cli to the apns standalone client
// It is also defined in the counterpart file (apns/apns/main.go apns/cli/main.go)
type MsgPushNotification struct {
	Text  string `json:"text"`
	Token string `json:"token"`
}

var (
	text  = flag.String("text", "Push notification text", "The text of the push notification")
	token = flag.String("token", "6f3031f2828aa1a369c78d3216be4b7c40ca7a8728a6a8d3e6229afc437b4ef1", "The token used to send the push notification")
)

func init() {
	flag.Parse()
}

func main() {

	pn := MsgPushNotification{Text: *text, Token: *token}
	body, err := json.Marshal(pn)
	if err != nil {
		log.Fatalf("Failed to encode the push notification: %s", err)
	}
	send(body)
}

func send(body []byte) {

	failOnError := func(err error, msg string) {
		if err != nil {
			log.Fatalf("%s: %s", msg, err)
			panic(fmt.Sprintf("%s: %s", msg, err))
		}
	}

	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"pushnotif", // name
		true,        // durable
		false,       // delete when usused
		false,       // exclusive
		false,       // no-wait
		nil,         // arguments
	)
	failOnError(err, "Failed to declare a queue")

	err = ch.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        body,
		})
	failOnError(err, "Failed to publish a message")
}

repository: gsempe/apns

repo_name: gsempe/apns