text:
@inproceedings{icia2008,
  author={J. Wedekind and B. P. Amavasai and K. Dutton and M. Boissenin},
  year={2008},
  month={20-23 June 2008},
  title={A machine vision extension for the {R}uby programming language},
  booktitle={2008 International Conference on Information and Automation (ICIA)},
  publisher={IEEE},
  address={Piscataway, NJ, USA},
  organization={Microsyst. \& Machine Vision Lab., Sheffield Hallam Univ., Sheffield, UK},
  pages={991-6},
  abstract={Dynamically typed scripting languages have become popular in recent years. Although interpreted languages allow for substantial reduction of software development time, they are often rejected due to performance concerns. In this paper we present an extension for the programming language Ruby, called HornetsEye, which facilitates the development of real-time machine vision algorithms within Ruby. Apart from providing integration of crucial libraries for input and output, HornetsEye provides fast native implementations (compiled code) for a generic set of array operators. Different array operators were compared with equivalent implementations in C++. Not only was it possible to achieve comparable real-time performance, but also to exceed the efficiency of the C++ implementation in several cases. Implementations of several algorithms were given to demonstrate how the array operators can be used to create concise implementations.},
  keywords={authoring languages; C++ language; computer vision; specification languages},
  isbn={978-1-4244-2183-1},
  doi={10.1109/ICINFA.2008.4608143},
  url={http://shura.shu.ac.uk/952/}
}


text:
SUMMARY = "Google Client"
SRC_URI = "git://chromium.googlesource.com/chromium/tools/depot_tools.git;protocol=https"
SRCREV = "9af33fa208fbb6e2212c7f62d55bf644e1f731ae"
PV = "1.0+git${SRCPV}"
S = "${WORKDIR}/git"
LICENSE = "GPLv3"
LIC_FILES_CHKSUM = "file://LICENSE;md5=c2c05f9bdd5fc0b458037c2d1fb8d95e"

inherit native

do_install() {
        mkdir -p ${D}${bindir}
        cp -r ${S} ${D}${bindir}/${PN}
        rm ${D}${bindir}/${PN}/gn
        rm ${D}${bindir}/${PN}/gn.py
}

FILES_${PN}="${bindir}/*"

license: MIT

repository: caneraltinbasak/meta-browser

license_type: permissive

repo_name: caneraltinbasak/meta-browser

branch_name: refs/heads/master

extension: bb


text:
package publisher

import (
	"time"

	sniffer "github.com/RafaelFino/xavier/internal/dns-sniffer"
	pw "github.com/RafaelFino/xavier/internal/process-watcher"
	"github.com/RafaelFino/xavier/internal/storage"
	"github.com/sirupsen/logrus"
)

type DataPublisher struct {
	logger       *logrus.Logger
	interval     int64
	processQueue chan []*pw.ProcessInfo
	dnsMsgsQueue chan *sniffer.DnsMsg
	endSignal    chan bool
	db           *storage.Storage
}

func New(logger *logrus.Logger) *DataPublisher {
	ret := &DataPublisher{
		logger:       logger,
		processQueue: make(chan []*pw.ProcessInfo),
		dnsMsgsQueue: make(chan *sniffer.DnsMsg),
		endSignal:    make(chan bool),
	}

	go ret.start()

	return ret
}

func (d *DataPublisher) ReceiveProcesses(processes []*pw.ProcessInfo) {
	d.processQueue <- processes
}

func (d *DataPublisher) ReceiveDNSMessage(msg *sniffer.DnsMsg) {
	d.dnsMsgsQueue <- msg
}

func (d *DataPublisher) start() {
	loggerContext := d.logger.WithField("Source", "Data-Publisher")
	d.db = storage.New(d.logger)

	for {
		select {
		case <-d.endSignal:
			loggerContext.Infof("Stop requested")
			return
		case dnsMsg := <-d.dnsMsgsQueue:
			loggerContext.WithField("Type", "DnsMSg").WithField("When", dnsMsg.Timestamp.Format("2006-01-02 15:04:05.000")).Debugf("[%s:%s] %s: %s", dnsMsg.Hostname, dnsMsg.Device, dnsMsg.Message, dnsMsg.Query)
			d.db.WriteDnsMessage(dnsMsg)
		case processes := <-d.processQueue:
			loggerContext.WithField("Type", "ProcessInfo").WithField("When", time.Now()).Debugf("Process count: %d", len(processes))
			d.db.WriteProcessEntry(processes)
		}
	}
}

func (d *DataPublisher) Stop() {
	d.endSignal <- true
}

repository: RafaelFino/xavier

repo_name: RafaelFino/xavier

branch_name: refs/heads/main

extension: go


text:
package main

import (
	"net/http"
)

type WikipediaPage struct {
	Common PageCommon
}

func (w WikipediaPage) Render(rw http.ResponseWriter, req *http.Request) {
	RenderPage(w, rw, req, true)
}

func (w WikipediaPage) GetPath() string {
	return w.Common.Path
}

func (w WikipediaPage) GetTplFile() string {
	return w.Common.TplFile
}

repository: tenglvjun/BeanTest

repo_name: tenglvjun/BeanTest


text:
DESCRIPTION = "Netsniff-ng is a fast zero-copy analyzer, pcap capturing and replaying tool"
HOMEPAGE = "http://netsniff-ng.org"
LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=9dd40dfb621eed702c0775577fbb7011"
DEPENDS = "libpcap"

SRCREV = "be3e706f00295024ebc199e70177343fdaebbc9e"
SRC_URI = " \
	git://github.com/netsniff-ng/netsniff-ng.git;protocol=https;branch=master \
	file://0001-Cmds-automatically-create-folder.patch \
	"

S = "${WORKDIR}/git"

inherit pkgconfig

EXTRA_OEMAKE += " TERM='' "

PACKAGECONFIG ??= ""
PACKAGECONFIG[zlib] = ",--disable-zlib,zlib,"
PACKAGECONFIG[libnl] = ",--disable-libnl,libnl,"
PACKAGECONFIG[geoip] = ",--disable-geoip,geoip,"

do_configure() {
    ./configure --prefix=${prefix}
}

do_compile() {
    oe_runmake
}

do_install() {
    oe_runmake DESTDIR=${D} netsniff-ng_install
}

BBCLASSEXTEND = "native nativesdk"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_license_id: MIT

gha_language: BitBake


text:
f%% BibTeX references.
%% References.

%% Opfinder lazy evaluation: Christopher P. Wadsworth, Semantics and Pragmatics of the Lambda Calculus , DPhil thesis, Oxford, 1971.

%%\cite{HuttonMeijer:jfp1998}

@Article{HuttonMeijer:jfp1998,
  author = 	 {G. Hutton and E. Meijer},
  title = 	 {Monadic Parsing in Haskell},
  journal = 	 {Journal of Functional Programming},
  year = 	 1998,
  volume = 	 8,
  number = 	 4,
  pages = 	 {437-444},
  month = 	 {July},
  note = 	 {Cambridge University Press, New York, NY, USA},
  doi     = {10.1017/S0956796898003050}}

@TechReport{haskell10,
  author = 	 {Simon Marlow et al},
  title = 	 {Haskell 2010 Language Report},
  institution =  {http://www.haskell.org},
  year = 	 2010}

@Article{Naur:algol60,
  author = 	 {Peter Naur et al},
  title = 	 {Report on the Algorithmic language ALGOL 60},
  journal = 	 {Communications of the ACM},
  pages = 	 {1-17},
  publisher = {ACM New York, NY, USA},
  year = 	 1963,
  volume = 	 6,
  number = 	 1,
  month = 	 jan,
  doi     = {10.1145/366193.366201}
}

%% Revised report on the algorithm language ALGOL 60...
%%
%% Title Communications of the ACM CACM Homepage table of contents archive
%%  	Volume 6 Issue 1, Jan. 1963
%% Editor 	C. C. Gotlieb Univ. of Toronto, Toronto, Canada
%% Pages	1-17
%% Publication Date	1963-01-01 (yyyy-mm-dd)
%% Publisher	ACM New York, NY, USA
%%	ISSN: 0001-0782 EISSN: 1557-7317 doi>10.1145/366193.366201

@InProceedings{Yang-etal:popl2012,
  author    = {Jean Yang and Kuat Yessenov and Armando Solar-Lezama},
  title     = {A Language for Automatically Enforcing Privacy Policies},
  pages     = {85-96},
  doi       = {10.1145/2103656.2103669},
  crossref  = {popl2012}
}

@Book{Schmidt:1986,
  author    = {David Schmidt},
  title     = {Denotational Semantics},
  publisher = {Allyn and Bacon},
  year      = 1986,
  isbn      = 0205104509,
  url       = {http://people.cis.ksu.edu/~schmidt/text/densem.html}
}

@TechReport{Plotkin:daimi1981,
  author      = {Gordon D. Plotkin},
  title       = {A Structural Approach to Operational Semantics},
  institution = {{DAIMI}, Aarhus University},
  year        = 1981,
  number      = {FN-19},
  address     = {Aarhus, Denmark},
  note        = {Reprinted with corrections in \emph{J. Log. Algebr. Program} \textbf{60-61}: 17-139 (2004).},
  url         = {http://homepages.inf.ed.ac.uk/gdp/publications/sos_jlap.pdf}
}

@InProceedings{Kahn:stacs1987,
  author    = {Gilles Kahn},
  title     = {Natural Semantics},
  year      = 1987,
  pages     = {22-39},
  doi       = {10.1007/BFb0039592},
  crossref  = {stacs1987}
}

@Book{H80:FunctionalP,
  author = {P. Henderson},
  title = {Functional Programming---Application and Implementation},
  publisher = {Prentice-Hall},
  year = 1980
}

@Misc{Rose:github2014,
  author = 	 {Eva Rose},
  title = 	 {Constraint Generation for the Jeeves Privacy Language},
  howpublished = {https://github.com\slash drevarose\slash jeeves-in-haskell/blob/master/jeeves-constraints.lhs},
  year = 	 {2014}
}

@TechReport{HugsHaskell,
  author = 	 {Graham Hutton},
  title = 	 {Hugs system},
  institution =  {Glasgow},
  year = 	 {2000},
}

@book{hutton2007programming,
  added-at = {2011-04-14T08:24:42.000+0200},
  author = {Hutton, Graham},
  biburl = {http://www.bibsonomy.org/bibtex/228fae83a031858b0aa9f75b2cd8a6860/aleator},
  date-added = {2011-04-14 09:20:04 +0300},
  date-modified = {2011-04-14 09:20:04 +0300},
  interhash = {446b576b39de17e4f687013b5c5fff94},
  intrahash = {28fae83a031858b0aa9f75b2cd8a6860},
  isbn = {0521692695},
  keywords = {imported},
  publisher = {Cambridge Univ Press},
  timestamp = {2011-04-14T08:24:42.000+0200},
  title = {Programming in Haskell},
  year = 2007
}

@book{RossiVB06,
          editor    = { Rossi, F. and van Beek, P. and Walsh, T. },
          title     = { Handbook of Constraint Programming },
          publisher = { Elsevier },
          year      = { 2006 }
      }

@inproceedings{conf/dalt/Sakama08,
  added-at = {2009-01-01T00:00:00.000+0100},
  author = {Sakama, Chiaki},
  biburl = {http://www.bibsonomy.org/bibtex/25b36f348876d8d593cc50a649729d921/dblp},
  booktitle = {DALT},
  date = {2009-01-01},
  description = {dblp},
  editor = {Baldoni, Matteo and Son, Tran Cao and van Riemsdijk, M. Birna and Winikoff, Michael},
  ee = {http://dx.doi.org/10.1007/978-3-540-93920-7_10},
  interhash = {634a66a8e6c67381010b45c7bdb18a57},
  intrahash = {5b36f348876d8d593cc50a649729d921},
  isbn = {978-3-540-93919-1},
  keywords = {dblp},
  pages = {143-160},
  publisher = {Springer},
  series = {Lecture Notes in Computer Science},
  timestamp = {2009-01-01T00:00:00.000+0100},
  title = {Inductive Negotiation in Answer Set Programming.},
  url = {http://dblp.uni-trier.de/db/conf/dalt/dalt2008.html#Sakama08},
  volume = 5397,
  year = 2008
}

@article{Antoniou:1999:TDL:344588.344602,
 author = {Antoniou, Grigoris},
 title = {A tutorial on default logics},
 journal = {ACM Comput. Surv.},
 issue_date = {Dec. 1999},
 volume = {31},
 number = {4},
 month = dec,
 year = {1999},
 issn = {0360-0300},
 pages = {337--359},
 numpages = {23},
 url = {http://doi.acm.org/10.1145/344588.344602},
 doi = {10.1145/344588.344602},
 acmid = {344602},
 publisher = {ACM},
 address = {New York, NY, USA},
 keywords = {default logic, nonmonotonic reasoning, operational models},
}

%% Collections.

@Proceedings{stacs1987,
  editor    = {Franz-Josef Brandenburg and Guy Vidal-Naquet and Martin Wirsing},
  title     = {{STACS '87}---4th Annual Symposium on Theoretical Aspects of Computer Science},
  booktitle = {{STACS '87}---4th Annual Symposium on Theoretical Aspects of Computer Science},
  publisher = {Springer},
  series    = {Lecture Notes in Computer Science},
  volume    = {247},
  year      = {1987},
  month     = feb,
  address   = {Passau, Germany},
  isbn      = {3-540-17219-X},
  bibsource = {DBLP, http://dblp.uni-trier.de}
}

@Proceedings{popl2012,
  editor    = {John Field and Michael Hicks},
  title     = {{POPL 2012}---Proceedings of the 39th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages},
  booktitle = {{POPL 2012}---Proceedings of the 39th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages},
  publisher = {ACM},
  year      = {2012},
  month     = jan,
  address   = {Philadelphia, Pennsylvania, USA},
  isbn      = {978-1-4503-1083-3}
}

@inproceedings{Des86lics,
   author = {Jo\"elle Despeyroux},
   title = {Proof of translation in {N}atural {S}emantics},
   booktitle = {proceedings of the first Symp. on Logic In Computer Science,
         {LICS}'86},
   publisher = {IEEE Computer Society},
   note = {Also appears as INRIA Research Report {RR}-514, April 1986},
   location = {Cambridge, MA},
   month = {June},
   year = {1986}
}

@Article{Gom92toplas,
  author = {Carsten K. Gomard},
  title = {A self-applicable partial evaluator for the lambda calculus: correctness and pragmatics.},
  journal = {Transactions on Programming Languages and Systems},
  year = 1992,
  volume = 	 14,
  number = 	 2,
  pages = 	 {147-172}}

@Book{pgmwconstr98,
  author = 	 {Marriott, K. and Stuckey,P.J.},
  title = 	 {Programming with Constraints: An introduction},
  publisher = 	 {MIT Press},
  year = 	 1998,
  isbn=          {0-262-13341-5},
  address = 	 {Cambridge, Massachusetts, USA}}

@book{Milner:1990:DSM:77325,
 author = {Milner, Robin and Tofte, Mads and Harper, Robert},
 title = {The definition of Standard ML},
 year = {1990},
 isbn = {0-262-63132-6},
 publisher = {MIT Press},
 address = {Cambridge, MA, USA},
}

@article{Schrijvers:2009:MCP:1735546.1735549,
 author = {Schrijvers, Tom and Stuckey, Peter and Wadler, Philip},
 title = {Monadic constraint programming},
 journal = {J. Funct. Program.},
 issue_date = {November 2009},
 volume = {19},
 number = {6},
 month = nov,
 year = {2009},
 issn = {0956-7968},
 pages = {663--697},
 numpages = {35},
 url = {http://dx.doi.org/10.1017/S0956796809990086},
 doi = {10.1017/S0956796809990086},
 acmid = {1735549},
 publisher = {Cambridge University Press},
 address = {New York, NY, USA},
}

@article{Wadler:2003:MEM:601775.601776,
 author = {Wadler, Philip and Thiemann, Peter},
 title = {The marriage of effects and monads},
 journal = {ACM Trans. Comput. Logic},
 issue_date = {January 2003},
 volume = {4},
 number = {1},
 month = jan,
 year = {2003},
 issn = {1529-3785},
 pages = {1--32},
 numpages = {32},
 url = {http://doi.acm.org/10.1145/601775.601776},
 doi = {10.1145/601775.601776},
 acmid = {601776},
 publisher = {ACM},
 address = {New York, NY, USA},
 keywords = {Monad, effect, region, type, type reconstruction},
}

@inproceedings{DBLP:conf/tacas/MouraB08,
  author    = {Leonardo Mendon\c{c}a de Moura and
               Nikolaj Bj{\o}rner},
  title     = {Z3: An Efficient SMT Solver},
  booktitle = {TACAS},
  year      = {2008},
  pages     = {337-340},
  doi = {10.1007/978-3-540-78800-3_24},
  bibsource = {DBLP, http://dblp.uni-trier.de}
}

repository: trommler/jeeves-in-haskell

repo_name: trommler/jeeves-in-haskell

extension: bib


text:
package message

import actor "github.com/filecoin-project/specs/systems/filecoin_vm/actor"
import addr "github.com/filecoin-project/specs/systems/filecoin_vm/actor/address"
import filcrypto "github.com/filecoin-project/specs/algorithms/crypto"
import util "github.com/filecoin-project/specs/util"

var IMPL_FINISH = util.IMPL_FINISH

type Serialization = util.Serialization

func UnsignedMessage_Make(
	from addr.Address,
	to addr.Address,
	method actor.MethodNum,
	params actor.MethodParams,
	callSeqNum actor.CallSeqNum,
	value actor.TokenAmount,
	gasPrice GasPrice,
	gasLimit GasAmount,
) UnsignedMessage {
	return &UnsignedMessage_I{
		From_:       from,
		To_:         to,
		Method_:     method,
		Params_:     params,
		CallSeqNum_: callSeqNum,
		Value_:      value,
		GasPrice_:   gasPrice,
		GasLimit_:   gasLimit,
	}
}

func SignedMessage_Make(message UnsignedMessage, signature filcrypto.Signature) SignedMessage {
	return &SignedMessage_I{
		Message_:   message,
		Signature_: signature,
	}
}

func Sign(message UnsignedMessage, keyPair filcrypto.SigKeyPair) (SignedMessage, error) {
	sig, err := filcrypto.Sign(keyPair, util.Bytes(Serialize_UnsignedMessage(message)))
	if err != nil {
		return nil, err
	}
	return SignedMessage_Make(message, sig), nil
}

func SignatureVerificationError() error {
	IMPL_FINISH()
	panic("")
}

func Verify(message SignedMessage, publicKey filcrypto.PublicKey) (UnsignedMessage, error) {
	m := util.Bytes(Serialize_UnsignedMessage(message.Message()))
	sigValid, err := filcrypto.Verify(publicKey, message.Signature(), m)
	if err != nil {
		return nil, err
	}
	if !sigValid {
		return nil, SignatureVerificationError()
	}
	return message.Message(), nil
}

func (x GasAmount) Add(y GasAmount) GasAmount {
	panic("TODO")
}

func (x GasAmount) Subtract(y GasAmount) GasAmount {
	panic("TODO")
}

func (x GasAmount) LessThan(y GasAmount) bool {
	panic("TODO")
}

func GasAmount_Zero() GasAmount {
	panic("TODO")
}

repository: nickboot/specs

repo_name: nickboot/specs


text:
DESCRIPTION = "Lightweight gtk+ browser, enhanced version, with support for SSL, frames, tabs and much more..."
HOMEPAGE = "http://www.dillo.org"
SECTION = "x11/network"
PRIORITY = "optional"
LICENSE = "GPL"
DEPENDS = "gtk+-1.2 libpng openssl"
RCONFLICTS_${PN} = "dillo2"
PR = "r3"
SRC_URI="http://www.dillo.org/download/dillo-${PV}.tar.bz2 \
         file://dillo-i18n.diff \
         file://dillo.desktop \
         file://dillo.png"

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

inherit autotools pkgconfig

FILES_${PN} += " /usr/lib/dillo/ /usr/bin/dpid /usr/bin/dpidc "
FILES_${PN}-dbg += " ${libdir}/dillo/dpi/*/.debug/"

export PNG_CONFIG = "${STAGING_BINDIR_CROSS}/libpng-config"

EXTRA_OECONF = "--disable-dlgui --disable-anti-alias"

do_install_append() {
        install -d ${D}${datadir}/applications
        install -d ${D}${datadir}/pixmaps
        install -m 0644 ${WORKDIR}/dillo.desktop ${D}${datadir}/applications/dillo.desktop
        install -m 0644 ${WORKDIR}/dillo.png ${D}${datadir}/pixmaps/dillo.png
}

SRC_URI[md5sum] = "b65233d368bbd265a55effcf2c17f84b"
SRC_URI[sha256sum] = "47e695a5d370eb656f5e41eeb917ad6281b1559bf60172c9eca89b5518a9f9b9"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package main

import (
	"log"
	"quote_gallery/database"
	"quote_gallery/web"
)

func main() {
	log.Print("Connecting to database")
	database.Connect()
	defer database.CloseAndClearCache()

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

	log.Print("Starting website on :8080")
	web.SetupRoutes()
	web.StartWebserver()
}

gha_language: Go


text:
require ${PN}.inc

PV = "${OPIE_GIT_PV}"
PR = r3

SRC_URI = "${OPIE_GIT};protocol=git;subpath=core/applets/irdaapplet \
           ${OPIE_GIT};protocol=git;subpath=pics \
           ${OPIE_GIT};protocol=git;subpath=sounds \
           ${OPIE_GIT};protocol=git;subpath=apps \
	  "


text:
package path

import "fmt"

// TokenType represents a way to identify an individual token.
type TokenType int

const (
	UNKNOWN TokenType = (iota - 1)
	EOF

	IDENT
	STRING

	EQ     // ==
	NEQ    // !=
	ASSIGN // =
	BANG   // !

	LT // <
	LE // <=
	GT // >
	GE // >=

	BITAND  // &
	BITOR   // |
	CONDAND // &&
	CONDOR  // ||

	LPAREN   // (
	RPAREN   // )
	LBRACKET // [
	RBRACKET // ]

	PERIOD    // .
	SEMICOLON // ;
)

func (t TokenType) String() string {
	switch t {
	case EOF:
		return "<EOF>"
	case IDENT:
		return "<IDENT>"
	case STRING:
		return "<STRING>"
	case ASSIGN:
		return "="
	case BANG:
		return "!"
	case EQ:
		return "=="
	case NEQ:
		return "!="
	case LT:
		return "<"
	case LE:
		return "<="
	case GT:
		return ">"
	case GE:
		return ">="
	case LPAREN:
		return "("
	case RPAREN:
		return ")"
	case LBRACKET:
		return "["
	case RBRACKET:
		return "]"
	case BITAND:
		return "&"
	case BITOR:
		return "|"
	case CONDAND:
		return "&&"
	case CONDOR:
		return "||"
	case PERIOD:
		return "."
	case SEMICOLON:
		return ";"
	default:
		return "<UNKNOWN>"
	}
}

// Position holds the location of the token within the query.
type Position struct {
	Offset int
	Line   int
	Column int
}

func (p Position) String() string {
	return fmt.Sprintf("<:%d:%d>", p.Line, p.Column)
}

// Token defines a token found with in a query, along with the position and what
// type it is.
type Token struct {
	Pos     Position
	Type    TokenType
	Literal string
}

// MakeToken creates a new token value.
func MakeToken(tokenType TokenType, char string) Token {
	return Token{
		Type:    tokenType,
		Literal: char,
	}
}

var (
	// UnknownToken can be used as a sentinel token for a unknown state.
	UnknownToken = Token{
		Type: UNKNOWN,
	}
)

var tokenMap = map[string]TokenType{
	";": SEMICOLON,
	".": PERIOD,
	"&": BITAND,
	"|": BITOR,
	"(": LPAREN,
	")": RPAREN,
	"[": LBRACKET,
	"]": RBRACKET,
	"=": ASSIGN,
	"!": BANG,
	"<": LT,
	">": GT,
}

repository: SimonRichardson/path

repo_name: SimonRichardson/path


text:
package proxy

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"
)

const (
	// timeout for upstream /sync requests (after which it will send back
	// an empty response)
	syncTimeout = 60 * time.Second
)

type MatrixClient struct {
	AccessToken string
	UserId      string

	// base-url for requests (e.g. "http//localhost:8008")
	url string

	Filter        string
	Presence      string
	NextSyncBatch string

	// our client for the upstream connection
	httpClient http.Client
}

func NewClient(url string, accessToken string) *MatrixClient {
	if !strings.HasSuffix(url, "/") {
		url += "/"
	}
	return &MatrixClient{url: url, AccessToken: accessToken}
}

// an error returned when a matrix endpoint returns a non-200 whose body is
// not a matrix error
type HttpError struct {
	StatusCode  int
	ContentType string
	Body        []byte
}

func (s *HttpError) Error() string {
	return string(s.Body)
}

// an error returned when a matrix endpoint returns a standard matrix error
type MatrixError struct {
	HttpError
	Details MatrixErrorDetails
}

func (e *MatrixError) Error() string {
	return fmt.Sprintf("%s (%s)", e.Details.ErrCode, e.Details.Error)
}

type MatrixErrorDetails struct {
	ErrCode string `json:"errcode"`
	Error   string `json:"error"`
}

func (s *MatrixClient) GetUserId() (string, error) {
	if s.UserId != "" {
		return s.UserId, nil
	}

	// make use of http://matrix.org/docs/spec/client_server/r0.2.0.html#m-rule-invite-for-me
	// i know it is hacky but this was the only way I found to determine the user-id via
	// Client-Server-API with just access-token provided

	params := url.Values{
		"access_token": {s.AccessToken},
	}
	resp, err := s.get("_matrix/client/r0/pushrules/global/override/.m.rule.invite_for_me", params)
	if err != nil {
		return "", fmt.Errorf("Error while fetching data to determine user-id")
	}

	type Condition struct {
		Key     string
		Pattern string
		// Kind string
	}
	type PushRuleResponse struct {
		// Rule_ID string
		// Default bool
		// Enabled bool
		Conditions []Condition
	}

	var response PushRuleResponse
	if err := json.Unmarshal(resp, &response); err != nil {
		return "", fmt.Errorf("Could not Unmarshal response:", err)
	}

	for _, condition := range response.Conditions {
		if condition.Key == "state_key" {
			log.Println("Resolved UserID:", condition.Pattern)
			s.UserId = condition.Pattern
			return condition.Pattern, nil
		}
	}
	return "", fmt.Errorf("Error finding state_key in push-rule-conditions (for UserId)")
}

func (s *MatrixClient) UpdatePresence(newPresence string) (string, *MatrixErrorDetails) {
	allowedPresenceTypes := [3]string{"online", "offline", "unavailable"}

	found := false
	for _, val := range allowedPresenceTypes {
		if val == newPresence {
			found = true
			break
		}
	}
	if found {
		s.Presence = newPresence
		return s.Presence, nil
	} else {
		return s.Presence, &MatrixErrorDetails{
			ErrCode: "M_BAD_JSON",
			Error:   "Given presence not allowed",
		}
	}
}

// Sync sends the sync request, and returns the body of the response,
// or an error.
//
// It keeps track of the 'next_batch' from the result, and uses it to se the
// 'since' parameter for the next call.
//
// If 'waitForEvents' is set, we will set a non-zero timeout value so that the
// HTTP request blocks until events are ready to be read. Otherwise the call
// will return immediately, even if there are no new events.
//
// Note that this method is not thread-safe; there should be only one concurrent
// call per MatrixClient.
//
// If /sync returns a non-200 response, the error returned will be a MatrixError.
func (s *MatrixClient) Sync(waitForEvents bool) ([]byte, error) {
	timeout := syncTimeout
	if !waitForEvents {
		timeout = 0
	}
	params := url.Values{
		"access_token": {s.AccessToken},
		"timeout":      {fmt.Sprintf("%d", timeout/time.Millisecond)},
	}
	if s.Filter != "" {
		params.Set("filter", s.Filter)
	}
	if s.Presence != "" {
		params.Set("presence", s.Presence)
	}
	if s.NextSyncBatch != "" {
		params.Set("since", s.NextSyncBatch)
	}

	body, err := s.get("_matrix/client/r0/sync", params)
	if err != nil {
		return nil, err
	}

	// we need the 'next_batch' token, so fish that out
	next_batch, err := extractNextBatch(body)
	if err != nil {
		return nil, err
	}
	log.Println("Got next_batch:", next_batch)
	s.NextSyncBatch = next_batch

	return body, nil
}

// extractNextBatch fishes the 'next_batch' member out of the JSON response from
// /sync.
func extractNextBatch(httpBody []byte) (string, error) {
	type syncResponse struct {
		NextBatch string `json:"next_batch"`
	}
	var sr syncResponse
	if err := json.Unmarshal(httpBody, &sr); err != nil {
		return "", err
	}

	if sr.NextBatch == "" {
		return "", fmt.Errorf("/sync response missing next_batch")
	}

	return sr.NextBatch, nil
}

func (s *MatrixClient) SendMessage(roomID string, eventType string,
	txnID string, content []byte) (string, error) {
	return s.sendMessageOrState(false, roomID, eventType, txnID, content)
}

func (s *MatrixClient) SendPresence(content []byte) ([]byte, error) {
	userID, err := s.GetUserId()
	if err != nil {
		return nil, err
	}

	path := fmt.Sprintf("_matrix/client/r0/presence/%s/status",
		url.QueryEscape(userID))

	params := url.Values{
		"access_token": {s.AccessToken},
	}

	resp, err := s.do("PUT", path, params, content)

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (s *MatrixClient) SendReadMarkers(roomID string, content []byte) ([]byte, error) {
	path := fmt.Sprintf("_matrix/client/r0/rooms/%s/read_markers",
		url.QueryEscape(roomID))

	params := url.Values{
		"access_token": {s.AccessToken},
	}

	resp, err := s.do("POST", path, params, content)

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (s *MatrixClient) SendState(roomID string, eventType string,
	stateKey string, content []byte) (string, error) {
	return s.sendMessageOrState(true, roomID, eventType, stateKey, content)
}

func (s *MatrixClient) SendTyping(roomID string, content []byte) ([]byte, error) {
	userID, err := s.GetUserId()
	if err != nil {
		return nil, err
	}

	path := fmt.Sprintf("_matrix/client/r0/rooms/%s/typing/%s",
		url.QueryEscape(roomID),
		url.QueryEscape(userID))

	params := url.Values{
		"access_token": {s.AccessToken},
	}

	resp, err := s.do("PUT", path, params, content)

	if err != nil {
		if err.(*MatrixError).HttpError.StatusCode == 429 {
			// Message got blocked because of rate-limiting
			// => ignore it (TODO is this intended?)
			log.Println("SendTyping got rate-limited: ignore")
			return []byte("{}"), nil
		}
		return nil, err
	}

	return resp, nil
}

func (s *MatrixClient) sendMessageOrState(state bool,
	roomID string, eventType string, key string, content []byte) (string, error) {
	type Response struct {
		Event_ID string
	}

	requestType := "send"
	if state {
		requestType = "state"
	}
	path := fmt.Sprintf("_matrix/client/r0/rooms/%s/%s/%s/%s",
		url.QueryEscape(roomID),
		requestType,
		url.QueryEscape(eventType),
		url.QueryEscape(key))

	params := url.Values{
		"access_token": {s.AccessToken},
	}
	resp, err := s.do("PUT", path, params, content)

	if err != nil {
		return "", err
	}

	var sr Response
	if err := json.Unmarshal(resp, &sr); err != nil {
		return "", err
	}
	return sr.Event_ID, nil
}

// get makes an HTTP GET request to the given endpoint.
//
// It checks the response code, and if it isn't a 200, returns an HttpError or
// MatrixError.
func (s *MatrixClient) get(path string, queryParams url.Values) ([]byte, error) {
	return s.do("GET", path, queryParams, nil)
}

var accessTokenRegexp = regexp.MustCompile("(access_token=)[^&]+")

// do makes an HTTP request to the given URL.
//
// It checks the response code, and if it isn't a 200, returns a MatrixError or
// HttpError
func (s *MatrixClient) do(method string, path string, queryParams url.Values, body []byte) ([]byte, error) {
	url := s.url + path

	if queryParams != nil {
		url += "?" + queryParams.Encode()
	}
	redactedUrl := accessTokenRegexp.ReplaceAllString(url, "$1<redacted>")
	log.Println("Send request:", method, redactedUrl)

	bodyReader := bytes.NewBuffer(body)
	req, err := http.NewRequest(method, url, bodyReader)
	if err != nil {
		log.Println("HTTP error", err)
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := s.httpClient.Do(req)
	if err != nil {
		log.Println("HTTP error", err)
		return nil, err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading request error response: %v", err)
	}

	log.Println("Response:", resp.StatusCode)
	if resp.StatusCode == 200 {
		return respBody, nil
	}

	contentType := resp.Header.Get("Content-Type")
	httpError := HttpError{resp.StatusCode, contentType, respBody}

	if contentType == "application/json" {
		matrixErr := MatrixError{HttpError: httpError}

		err = json.Unmarshal(respBody, &matrixErr.Details)

		if err == nil {
			return nil, &matrixErr
		}
		log.Println("Unable to unmarshall json error", err)
	}

	return nil, &httpError
}

repository: krombel/matrix-websockets-proxy

repo_name: krombel/matrix-websockets-proxy


text:
@misc{ Manners,
       author = "David Manners",
       title = "Arm's Way",
       year = "1998" }

@misc{ Chisnall,
       author = "David Chisnall",
       title = "Understanding ARM Architectures",
       year = "2010" }

@misc{ Wilson,
       author = "Roger Wilson",
       title = "Some Facts About Acorn RISC Machine",
       year = "1988" }

@misc{ Chattopadhyay,
       author = "Santanu Chattopadhyay",
       title = "Embedded System Design",
       year = "2010" }

@misc{ Power.org,
       title = "PowerPC User Instruction Set Architecture Book I, version 2.02",
       }

@misc{ TechFiles,
       title = "Tech Files Columns",
       year = "1987-1990"
       }

@misc{ ARMltd,
       author = "ARM Ltd and ARM Germany GmbH",
       title = "Device Database",
       year = "2006" }

@misc{ May,
       author = "Cathy May",
       title = "The PowerPC Architecture: A Specification for A New Family of RISC Processors",
       year = "1994" }

@misc{ IBM,
       author = "IBM",
       title = "Book E: Enhanced PowerPC Architecture",
       year = "2000" }

@misc{ IBM2,
       author = "IBM",
       title = "PowerPC Architecture",
       }


text:
package instructions

import (
	"github.com/zxh0/jvm.go/jvmgo/jvm/rtda"
	rtc "github.com/zxh0/jvm.go/jvmgo/jvm/rtda/class"
)

// Fetch field from object
type getfield struct {
	Index16Instruction
	field *rtc.Field
}

func (self *getfield) Execute(frame *rtda.Frame) {
	if self.field == nil {
		cp := frame.Method().Class().ConstantPool()
		kFieldRef := cp.GetConstant(self.index).(*rtc.ConstantFieldref)
		self.field = kFieldRef.InstanceField()
	}

	stack := frame.OperandStack()
	ref := stack.PopRef()
	if ref == nil {
		frame.Thread().ThrowNPE()
		return
	}

	val := self.field.GetValue(ref)
	stack.PushField(val, self.field.IsLongOrDouble)
}


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

package mgrdb

import (
	"errors"
	"time"

	"github.com/cloustone/sentel/pkg/config"
)

const (
	DBNAME = "iotmanager"
)

// Node
type Node struct {
	NodeId     string    `json:"nodeId" bson:"NodeId"`
	NodeIp     string    `json:"nodeIp" bson:"NodeIp"`
	Version    string    `json:"version" bson:"Version"`
	CreatedAt  time.Time `json:"createdAt" bson:"CreatedAt"`
	NodeStatus string    `json:"nodeStatus" bson:"NodeStatus"`
	UpdatedAt  time.Time `json:"updatedAt" bson:"UpdatedAt"`
	Action     string    `json:"action"`
}

// Subscription
type Subscription struct {
	ClientId        string    `json:"clientID" bson:"ClientId"`
	SubscribedTopic string    `json:"topic" bson:"Topic"`
	Qos             int       `json:"qos" bson:"Qos"`
	CreatedAt       time.Time `json:"createdAt" bson:"CreatedAt"`
	Action          string    `json:"action" bson:"Action"`
}

// Client
type Client struct {
	ClientId        string `json:"clientID" bson:"ClientId"`
	UserName        string `json:"userName" bson:"UserName"`
	IpAddress       string `json:"ipAddress" bson:"IpAddress"`
	Port            uint16 `json:"port" bson:"Port"`
	CleanSession    bool   `json:"cleanSession" bson:"CleanSession"`
	ProtocolVersion string `json:"protocolVersion" bson:"ProtocolVersion"`
	Keepalive       uint16 `json:"keepalive" bson:"Keepalive"`
	ConnectedAt     string `json:"connectedAt" bson:"ConnectedAt"`
}

// Session
type Session struct {
	Action             string `json:"action" bson:"Action"`
	ClientId           string `json:"clientID" bson:"ClientId"`
	CleanSession       bool   `json:"cleanSession" bson:"CleanSession"`
	MessageMaxInflight uint64 `json:"messageMaxInflight" bson:"MessageMaxInflight"`
	MessageInflight    uint64 `json:"messageInflight" bson:"MessageInflight"`
	MessageInQueue     uint64 `json:"messageInQueue" bson:"MessageInQueue"`
	MessageDropped     uint64 `json:"messageDropped" bson:"MessageDropped"`
	AwaitingRel        uint64 `json:"awaitingRel" bson:"AwaitingRel"`
	AwaitingComp       uint64 `json:"awaitingComp" bson:"AwaitingComp"`
	AwaitingAck        uint64 `json:"awaitingAck" bson:"AwaitingAck"`
	CreatedAt          string `json:"createdAt" bson:"CreatedAt"`
}

// Tenant & Product
type Tenant struct {
	TenantId         string              `bson:"tenantId"`
	Products         map[string]*Product `bson:"products"`
	ServiceName      string              `bson:"serviceName"`
	ServiceId        string              `bson:"serviceId"`
	ServiceState     string              `bson:"servcieState"`
	InstanceReplicas int32               `bson:"instanceReplicas"`
	NetworkId        string              `bson:"networkId"`
	CreatedAt        time.Time           `bson:"createdAt"`
}

type Product struct {
	ProductId string    `bson:"productId"`
	CreatedAt time.Time `bson:"createdAt"`
}

// Metric
type Metric struct {
	Action     string            `json:"action" bson:"Action"`
	NodeName   string            `json:"nodeName" bson:"NodeName"`
	Service    string            `json:"service" bson:"Service"`
	Values     map[string]uint64 `json:"values" bson:"Values"`
	UpdateTime time.Time         `json:"updateTime" bson:"UpdateTime"`
}

// Stat
type Stats struct {
	NodeName   string            `json:"nodeName" bson:"NodeName"`
	Service    string            `json:"service" bson:"Service"`
	Action     string            `json:"action" bson:"Action"`
	UpdateTime time.Time         `json:"updateTime" bson:"UpdateTime"`
	Values     map[string]uint64 `json:"values" bson:"Values"`
}

// Publish
type Publish struct {
	ClientId        string `json:"clientID" bson:"ClientId"`
	SubscribedTopic string `json:"topic" bson:"SubscribedTopic"`
	ProductId       string `json:"product" bson:"ProductId"`
}

type ManagerDB interface {
	// Node
	// GetAllNodes retrieve all broker nodes info in cluster
	GetAllNodes() []Node
	// GetNode retrieve specified node info
	GetNode(nodeId string) (Node, error)
	// AddNode add new node
	AddNode(n Node) error
	// UpdateNode update existed node
	UpdateNode(n Node) error
	// RemoveNode remove existed node
	RemoveNode(nodeId string) error
	// GetNodeClients retrieve all clients info on specified broker node
	GetNodeClients(nodeId string) []Client
	// GetNodeClients retrieve clients info on specified broker node in duration
	GetNodesClientWithTimeScope(nodeId string, from time.Time, to time.Time) []Client
	// GetClientWithNode return specified client info on specified broker node
	GetClientWithNode(nodeId string, clientID string) (Client, error)

	// Session
	// GetSession return client's session info
	GetSession(clientID string) (Session, error)
	// UpdateSession update session info
	UpdateSession(s Session) error
	// GetNodeSessions retrieve all sessions on specified broker node
	GetNodeSessions(nodeId string) []Session
	// GetSessionWithNode retrieve specifed client session on specifed broker node
	GetSessionWithNode(nodeId string, clientID string) (Session, error)

	// Tenants
	// GetAllTenants retrieve all tenants in cluster
	GetAllTenants() []Tenant
	// AddTenant add tenant into db
	AddTenant(t *Tenant) error
	// RemoveTenant remove tenant from db
	RemoveTenant(tenantId string) error

	// Product
	AddProduct(tenantId string, productId string) error
	RemoveProduct(tenantId string, productId string) error

	// Client
	GetClient(clientID string) (Client, error)
	AddClient(Client) error
	RemoveClient(Client) error
	UpdateClient(Client) error

	// Metrics
	GetMetrics() []Metric
	GetNodeMetric(nodeId string) (Metric, error)
	AddMetricHistory(Metric) error
	UpdateMetric(Metric) error

	// Stats
	AddStatsHistory(Stats) error
	UpdateStats(Stats) error
	GetStats() []Stats

	// Subscription
	AddSubscription(sub Subscription) error
	UpdateSubscription(sub Subscription) error
	RemoveSubscription(sub Subscription) error

	// Publish
	UpdatePublish(Publish) error

	Close()
}

func New(c config.Config) (ManagerDB, error) {
	if _, err := c.String("mongo"); err == nil {
		return newMgrdbMongo(c)
	}
	return nil, errors.New("no valid database")
}

repository: Willwil/sentel

repo_name: Willwil/sentel


text:
package ring

import (
	"bytes"
	"container/list"
	"crypto/sha256"
	"strings"
	"sync"
)

// Hash is the hashing function used to determine a nodes position in the
// ring and to find the appropriate node for a given key.
var Hash func([]byte) []byte = func(bytes []byte) []byte {
	hash := sha256.New()
	hash.Write(bytes)
	return hash.Sum(nil)
}

// lessThan returns true is the hashed value of a is less than the hashed
// value of b. Otherwise it returns false.
func lessThan(a *list.Element, b string) bool {
	return bytes.Compare(Hash([]byte(a.Value.(string))), Hash([]byte(b))) < 1
}

type Ring interface {
	Add(member string)
	Find(key string) (member string)
	FindN(key string, n int) (members map[string]string)
	Fail(member string)
	Revive(member string)
	Adjacent(a, b string) bool
}

// HashRing maintains a list of members and their position in the cluster
// based on a consistent hashing function.
// If a node fails it remains in the list but is marked as failed.
type HashRing struct {
	list   *list.List
	failed map[string]bool
	lock   *sync.Mutex
}

// findElement iterates over the node until it finds a node greater
// than the key.
// If a node isn't found it returns the head of the list.
func (h *HashRing) findElement(key string) *list.Element {
	current := h.list.Front()

	for lessThan(current, key) {
		current = current.Next()

		if current == nil {
			current = h.list.Front()
			break
		}
	}

	return current
}

// String returns a comma separated list of addresses.
func (h *HashRing) String() string {
	current := h.list.Front()
	addresses := []string{}

	for current != nil {
		addresses = append(addresses, current.Value.(string))
		current = current.Next()
	}

	return strings.Join(addresses, ", ")
}

// Add finds the first node that is higher than the address and inserts
// a new node before it.
func (h *HashRing) Add(address string) {
	if h.list.Len() == 0 {
		h.list.PushBack(address)
	} else {
		target := h.findElement(address)

		if lessThan(target, address) {
			h.list.PushBack(address)
		} else {
			h.list.InsertBefore(address, target)
		}
	}
}

// Find returns the node that owns the range the key falls within.
// TODO: Should this return hinted addresses if the node is dead?
func (h *HashRing) Find(key string) string {
	element := h.findElement(key)

	if element != nil {
		address := element.Value.(string)

		for h.failed[address] {
			next := element.Next()

			if next == nil {
				next = h.list.Front()
			}

			address = next.Value.(string)
		}

		return address
	} else {
		return ""
	}
}

// FindN returns n alive nodes starting with the closest to the provided key.
// If a node is dead the next alive node will be returned in its place with a
// hint to the real address.
// Returns a map where keys are addresses and values are hints. If the key and
// value are the same then the node is alive.
func (h *HashRing) FindN(key string, n int) map[string]string {
	target := h.findElement(key)
	ret := map[string]string{}

	if target == nil {
		return ret
	}

	for len(ret) < n {
		address := target.Value.(string)
		hint := address

		for h.failed[address] {
			next := target.Next()

			for i := 0; i < n-1; i++ {
				if next == nil {
					next = h.list.Front()
				} else {
					next = next.Next()
				}
			}

			if next == nil {
				next = h.list.Front()
			}

			address = next.Value.(string)
		}

		ret[address] = hint
		target = target.Next()

		if target == nil {
			target = h.list.Front()
		}
	}

	return ret
}

// Adjacent returns true if the addresses are next to each other in the ring.
func (h *HashRing) Adjacent(a, b string) bool {
	nodeA := h.findElement(a)
	nodeB := h.findElement(b)

	if nodeA != nil {
		next := nodeA.Next()

		if next == nil {
			next = h.list.Front()
		}

		return next == nodeB
	} else {
		return false
	}
}

// Fail marks member as failed, but doesn't remove it from the ring.
func (h *HashRing) Fail(member string) {
	h.failed[member] = true
}

// Revive removes the member from the failed list.
func (h *HashRing) Revive(member string) {
	delete(h.failed, member)
}

func NewHashRing() *HashRing {
	return &HashRing{
		list:   list.New(),
		failed: map[string]bool{},
		lock:   &sync.Mutex{},
	}
}

repository: rlayte/toystore

repo_name: rlayte/toystore


text:
# base recipe: meta/recipes-extended/quota/quota_4.04.bb
# base branch: warrior
# base commit: 811c07db35354bf97e765942f701896a7433f5b7

SUMMARY = "Tools for monitoring & limiting user disk usage per filesystem"
SECTION = "base"
HOMEPAGE = "http://sourceforge.net/projects/linuxquota/"
BUGTRACKER = "http://sourceforge.net/tracker/?group_id=18136&atid=118136"
LICENSE = "BSD & GPLv2+ & LGPLv2.1+"
LIC_FILES_CHKSUM = "file://quota.c;beginline=1;endline=33;md5=331c7d77744bfe0ad24027f0651028ec \
                    file://rquota_server.c;beginline=1;endline=20;md5=fe7e0d7e11c6f820f8fa62a5af71230f \
                    file://svc_socket.c;beginline=1;endline=17;md5=24d5a8792da45910786eeac750be8ceb"

inherit debian-package
require recipes-debian/sources/quota.inc

FILESPATH_append = ":${COREBASE}/meta/recipes-extended/${BPN}/${BPN}:"
SRC_URI += " \
           file://fcntl.patch \
           file://remove_non_posix_types.patch \
          "
SRC_URI_append_libc-musl = " file://replace_getrpcbynumber_r.patch"

CVE_PRODUCT = "linux_diskquota"

DEPENDS = "gettext-native e2fsprogs libnl dbus"

inherit autotools-brokensep gettext pkgconfig

CFLAGS += "${@bb.utils.contains('PACKAGECONFIG', 'rpc', '-I${STAGING_INCDIR}/tirpc', '', d)}"
LDFLAGS += "${@bb.utils.contains('PACKAGECONFIG', 'rpc', '-ltirpc', '', d)}"
ASNEEDED = ""

PACKAGECONFIG ??= "tcp-wrappers rpc bsd"
PACKAGECONFIG_libc-musl = "tcp-wrappers rpc"

PACKAGECONFIG[tcp-wrappers] = "--enable-libwrap,--disable-libwrap,tcp-wrappers"
PACKAGECONFIG[rpc] = "--enable-rpc,--disable-rpc,libtirpc"
PACKAGECONFIG[bsd] = "--enable-bsd_behaviour=yes,--enable-bsd_behaviour=no,"
PACKAGECONFIG[ldapmail] = "--enable-ldapmail,--disable-ldapmail,openldap"

repository: miraclelinux/meta-debian-extended

repo_name: miraclelinux/meta-debian-extended

branch_name: refs/heads/warrior


text:
require qt5-git.inc
require ${PN}.inc

QT_MODULE_BRANCH = "release"
# v5.2.1 + 15 commits
SRCREV = "1c54d411ad6e98c3779a412750aec8b93d587872"


text:
package cloudscale
import (
	"testing"

	"github.com/docker/machine/libmachine/drivers"
	"github.com/stretchr/testify/assert"
)

func TestSetConfigFromFlags(t *testing.T) {
	driver := NewDriver("default", "path")

	checkFlags := &drivers.CheckDriverOptions{
		FlagsValues: map[string]interface{}{
			"cloudscale-token": "TOKEN",
		},
		CreateFlags: driver.GetCreateFlags(),
	}

	err := driver.SetConfigFromFlags(checkFlags)

	assert.NoError(t, err)
	assert.Empty(t, checkFlags.InvalidFlags)

	assert.Equal(t, driver.ResolveStorePath("id_rsa"), driver.GetSSHKeyPath())
}

func TestDefaultSSHUserAndPort(t *testing.T) {
	driver := NewDriver("default", "path")

	checkFlags := &drivers.CheckDriverOptions{
		FlagsValues: map[string]interface{}{
			"cloudscale-token": "TOKEN",
		},
		CreateFlags: driver.GetCreateFlags(),
	}

	err := driver.SetConfigFromFlags(checkFlags)
	assert.NoError(t, err)

	sshPort, err := driver.GetSSHPort()
	assert.Equal(t, "root", driver.GetSSHUsername())
	assert.Equal(t, 22, sshPort)
	assert.NoError(t, err)
}

func TestCustomSSHUserAndPort(t *testing.T) {
	driver := NewDriver("default", "path")

	checkFlags := &drivers.CheckDriverOptions{
		FlagsValues: map[string]interface{}{
			"cloudscale-token": "TOKEN",
			"cloudscale-ssh-user":     "user",
			"cloudscale-ssh-port":     2222,
		},
		CreateFlags: driver.GetCreateFlags(),
	}

	err := driver.SetConfigFromFlags(checkFlags)
	assert.NoError(t, err)

	sshPort, err := driver.GetSSHPort()
	assert.Equal(t, "user", driver.GetSSHUsername())
	assert.Equal(t, 2222, sshPort)
	assert.NoError(t, err)
}

func TestVolumeSizeGB(t *testing.T) {
	driver := NewDriver("default", "path")

	checkFlags := &drivers.CheckDriverOptions{
		FlagsValues: map[string]interface{}{
			"cloudscale-token": "TOKEN",
			"cloudscale-volume-size-gb": 100,
		},
		CreateFlags: driver.GetCreateFlags(),
	}

	err := driver.SetConfigFromFlags(checkFlags)
	assert.NoError(t, err)
	assert.Equal(t, 100, driver.VolumeSizeGB)
}

func TestAntiAffinityWith(t *testing.T) {
	driver := NewDriver("default", "path")

	checkFlags := &drivers.CheckDriverOptions{
		FlagsValues: map[string]interface{}{
			"cloudscale-token": "TOKEN",
			"cloudscale-anti-affinity-with": "some uuid",
		},
		CreateFlags: driver.GetCreateFlags(),
	}

	err := driver.SetConfigFromFlags(checkFlags)
	assert.NoError(t, err)
	assert.Equal(t, "some uuid", driver.AntiAffinityWith)
}

repository: cloudscale-ch/machine

repo_name: cloudscale-ch/machine


text:
REPLACE_STUBS = "0"
CUDA_PKG = "${BPN}-dev"

require cuda-shared-binaries-${PV}.inc

DEVSUM = "c1c55ba59d8a28a7d56800504c65683a4d392893f35d08ec7bddf6b45efda468"
DEVSUM_x86-64 = "4e57a63577872f1b8ae9a65b81b4d015f3c9c7533e81f48655d33ecca611caf3"

ALLOW_EMPTY_${PN} = "1"
PRIVATE_LIBS = "libcuda.so.1"

BBCLASSEXTEND = "native nativesdk"


text:
SUMMARY = "A text-based user interface plugin of dnf for user to manage packages. "
LICENSE = "GPL-2.0-only"

LIC_FILES_CHKSUM = "file://COPYING;md5=b234ee4d69f5fce4486a80fdaf4a4263"

SRC_URI = "git://github.com/ubinux/dnf-plugin-tui.git;branch=master;protocol=https"
SRCREV = "83917a3935ac7ce1d8d96e914d96a6679319a336"
PV = "1.3"

SRC_URI:append:class-target = " file://oe-remote.repo.sample"

inherit setuptools3-base

S = "${WORKDIR}/git"

do_install:append() {
    install -d ${D}${datadir}/dnf
    install -m 0755 ${S}/samples/* ${D}${datadir}/dnf
    install -d ${D}${PYTHON_SITEPACKAGES_DIR}/dnf-plugins/mkimg
    install -m 0755 ${S}/dnf-plugins/mkimg/* ${D}${PYTHON_SITEPACKAGES_DIR}/dnf-plugins/mkimg
    for file in $(ls ${S}/dnf-plugins/ | grep -v mkimg); do
        install -m 0755 ${S}/dnf-plugins/$file ${D}${PYTHON_SITEPACKAGES_DIR}/dnf-plugins
    done
}

do_install:append:class-target() {
    install -d ${D}${sysconfdir}/yum.repos.d
    install -m 0644 ${WORKDIR}/oe-remote.repo.sample ${D}${sysconfdir}/yum.repos.d
}

do_install:append:class-nativesdk() {
    install -d -p ${D}/${SDKPATH}/postinst-intercepts
    cp -r ${COREBASE}/scripts/postinst-intercepts/* ${D}/${SDKPATH}/postinst-intercepts/
    sed -i -e 's/STAGING_DIR_NATIVE/NATIVE_ROOT/g' ${D}/${SDKPATH}/postinst-intercepts/*
}

FILES:${PN} += "${datadir}/dnf"
FILES:${PN} += "${SDKPATH}/postinst-intercepts"

RDEPENDS:${PN} += " \
    bash \
    dnf \
    libnewt-python \
"
DEPENDS:append:class-nativesdk = " file-replacement-nativesdk"
BBCLASSEXTEND = "nativesdk"
SKIP_RECIPE[dnf-plugin-tui] ?= "${@bb.utils.contains('PACKAGE_CLASSES', 'package_rpm', '', 'does not build correctly without package_rpm in PACKAGE_CLASSES', d)}"


text:
package iszero_test

import (
	"fmt"
	"reflect"

	"4d63.com/iszero"
)

func ExampleValue() {
	var s0 string
	s0Zero := iszero.Value(reflect.ValueOf(s0))

	var s1 string = "hello world"
	s1Zero := iszero.Value(reflect.ValueOf(s1))

	fmt.Println("s0", s0Zero)
	fmt.Println("s1", s1Zero)

	// Output:
	// s0 true
	// s1 false
}

repository: leighmcculloch/go-iszero

repo_name: leighmcculloch/go-iszero


text:
package main

import (
	"crypto/sha256"
	"crypto/tls"
	"encoding/pem"
	"flag"
	"fmt"
	"os"
	"strings"
	"path"
	"log"
)

var (
	server      = flag.String("server", "", "The TLS host (name or IP) to connect to")
	port        = flag.Int("port", 443, "The port the TLS service is running on")
	network     = flag.String("net", "tcp", "Connect to this kind of network: tcp, udp, or unix")
	ipv4only    = flag.Bool("4", false, "Only connect via IPv4")
	ipv6only    = flag.Bool("6", false, "Only connect via IPv6")
	verify      = flag.Bool("verify", false, "Verify the provided certificate against trusted CAs")
	fingerprint = flag.Bool("fingerprint", false, "Print the SHA-256 fingerprint instead of the certificate")
)

func main() {
	flag.Usage = func() {
		fmt.Fprintf(
			os.Stderr,
			"Usage: %s [-4|-6] [-net=tcp|udp|unix] [-verify] [-port PORT] -server HOST\n",
			path.Base(os.Args[0]),
		)
		fmt.Fprintf(os.Stderr, "A simple utility to grab just a server's public certificate or fingerprint.\n\n")
		flag.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\n")
	}

	flag.Parse()

	if *server == "" {
		flag.Usage()
		log.Fatal("Need to specify a server.")
	}

	if *network != "tcp" && *network != "udp" && *network != "unix" {
		flag.Usage()
		log.Fatal("Unknown kind of network type! Try tcp.")
	}

	var networkSuffix string = ""
	if *ipv4only && *ipv6only {
		log.Print("Specifying both -4 & -6 is redundant.")
	} else if *ipv4only {
		networkSuffix = "4"
	} else if *ipv6only {
		networkSuffix = "6"
	}

	targetHost := fmt.Sprintf("%s:%d", *server, *port)
	networkType := fmt.Sprintf("%s%s", *network, networkSuffix)

	// Merely connect to the service, do the full handshake and then immediately
	// close the connection. All the information we care about is given in the
	// handshake.
	conn, err := tls.Dial(networkType, targetHost, &tls.Config{
		InsecureSkipVerify: !(*verify),
	})
	if err != nil {
		log.Fatalf("failed to connect: %s", err.Error())
	}
	conn.Close()

	tlsState := conn.ConnectionState()
	remoteCerts := tlsState.PeerCertificates
	for _, cert := range remoteCerts {
		// skip all of the intermediary & root CA certificates provided by the
		// server
		if cert.BasicConstraintsValid {
			if cert.IsCA {
				continue
			}
		} else {
			continue
		}

		if *fingerprint {
			// A certificate's fingerprint is simply the hash of the raw ASN.1 encoded
			// certificate. Super simple.
			fmt.Println(strings.Replace(fmt.Sprintf("% X", sha256.Sum256(cert.Raw)),
				" ", ":", -1))
		} else {
			pem.Encode(os.Stdout, &pem.Block{
				Type:  "CERTIFICATE",
				Bytes: cert.Raw,
			})
		}
	}
}

repository: secsecsec/tls-grab

repo_name: secsecsec/tls-grab


text:
// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package vcs

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/google/syzkaller/pkg/osutil"
)

func init() {
	// Disable sandboxing entirely because we create test repos without sandboxing.
	os.Setenv("SYZ_DISABLE_SANDBOXING", "yes")
}

func TestGitRepo(t *testing.T) {
	baseDir, err := ioutil.TempDir("", "syz-git-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(baseDir)
	repo1 := createTestRepo(t, baseDir, "repo1")
	repo2 := createTestRepo(t, baseDir, "repo2")
	repo := newGit(filepath.Join(baseDir, "repo"))
	{
		com, err := repo.Poll(repo1.dir, "master")
		if err != nil {
			t.Fatal(err)
		}
		if diff := cmp.Diff(com, repo1.commits["master"]["1"]); diff != "" {
			t.Fatal(diff)
		}
	}
	{
		com, err := repo.CheckoutBranch(repo1.dir, "branch1")
		if err != nil {
			t.Fatal(err)
		}
		if diff := cmp.Diff(com, repo1.commits["branch1"]["1"]); diff != "" {
			t.Fatal(diff)
		}
	}
	{
		want := repo1.commits["branch1"]["0"]
		com, err := repo.CheckoutCommit(repo1.dir, want.Hash)
		if err != nil {
			t.Fatal(err)
		}
		if diff := cmp.Diff(com, want); diff != "" {
			t.Fatal(diff)
		}
	}
	{
		commits, err := repo.ListRecentCommits(repo1.commits["branch1"]["1"].Hash)
		if err != nil {
			t.Fatal(err)
		}
		want := []string{"repo1-branch1-1", "repo1-branch1-0", "repo1-master-0"}
		if diff := cmp.Diff(commits, want); diff != "" {
			t.Fatal(diff)
		}
	}
	{
		want := repo2.commits["branch1"]["0"]
		com, err := repo.CheckoutCommit(repo2.dir, want.Hash)
		if err != nil {
			t.Fatal(err)
		}
		if diff := cmp.Diff(com, want); diff != "" {
			t.Fatal(diff)
		}
	}
	{
		want := repo2.commits["branch1"]["1"]
		com, err := repo.CheckoutCommit(repo2.dir, want.Hash)
		if err != nil {
			t.Fatal(err)
		}
		if diff := cmp.Diff(com, want); diff != "" {
			t.Fatal(diff)
		}
	}
	{
		com, err := repo.CheckoutBranch(repo2.dir, "branch2")
		if err != nil {
			t.Fatal(err)
		}
		if diff := cmp.Diff(com, repo2.commits["branch2"]["1"]); diff != "" {
			t.Fatal(diff)
		}
	}
	{
		want := repo2.commits["branch2"]["0"]
		com, err := repo.SwitchCommit(want.Hash)
		if err != nil {
			t.Fatal(err)
		}
		if diff := cmp.Diff(com, want); diff != "" {
			t.Fatal(diff)
		}
	}
}

func createTestRepo(t *testing.T, baseDir, name string) *testRepo {
	repo := makeTestRepo(t, filepath.Join(baseDir, name))
	repo.git("checkout", "-b", "master")
	repo.commitFileChange("master", "0")
	for _, branch := range []string{"branch1", "branch2"} {
		repo.git("checkout", "-b", branch, "master")
		repo.commitFileChange(branch, "0")
		repo.commitFileChange(branch, "1")
	}
	repo.git("checkout", "master")
	repo.commitFileChange("master", "1")
	return repo
}

type testRepo struct {
	t       *testing.T
	dir     string
	name    string
	commits map[string]map[string]*Commit
}

func makeTestRepo(t *testing.T, dir string) *testRepo {
	if err := osutil.MkdirAll(dir); err != nil {
		t.Fatal(err)
	}
	repo := &testRepo{
		t:       t,
		dir:     dir,
		name:    filepath.Base(dir),
		commits: make(map[string]map[string]*Commit),
	}
	repo.git("init")
	return repo
}

func (repo *testRepo) git(args ...string) {
	if _, err := osutil.RunCmd(time.Minute, repo.dir, "git", args...); err != nil {
		repo.t.Fatal(err)
	}
}

func (repo *testRepo) commitFileChange(branch, change string) {
	id := fmt.Sprintf("%v-%v-%v", repo.name, branch, change)
	file := filepath.Join(repo.dir, "file")
	if err := osutil.WriteFile(file, []byte(id)); err != nil {
		repo.t.Fatal(err)
	}
	repo.git("add", file)
	repo.git("commit", "-m", id)
	if repo.commits[branch] == nil {
		repo.commits[branch] = make(map[string]*Commit)
	}
	com, err := newGit(repo.dir).HeadCommit()
	if err != nil {
		repo.t.Fatal(err)
	}
	repo.commits[branch][change] = com
}

repository: amscanne/syzkaller

repo_name: amscanne/syzkaller


text:
@book {ErnGuermond,
    AUTHOR = {Ern, Alexandre and Guermond, Jean-Luc},
     TITLE = {Theory and practice of finite elements},
    SERIES = {Applied Mathematical Sciences},
    VOLUME = {159},
 PUBLISHER = {Springer-Verlag, New York},
      YEAR = {2004},
     PAGES = {xiv+524},
      ISBN = {0-387-20574-8},
   MRCLASS = {65-02 (65M60 65N30 74S05 76M10 78M10)},
  MRNUMBER = {2050138 (2005d:65002)},
MRREVIEWER = {R. S. Anderssen},
       DOI = {10.1007/978-1-4757-4355-5},
       URL = {http://dx.doi.org/10.1007/978-1-4757-4355-5},
}

@book {Yosida,
    AUTHOR = {Yosida, K{\=o}saku},
     TITLE = {Functional analysis},
    SERIES = {Classics in Mathematics},
      NOTE = {Reprint of the sixth (1980) edition},
 PUBLISHER = {Springer-Verlag, Berlin},
      YEAR = {1995},
     PAGES = {xii+501},
      ISBN = {3-540-58654-7},
   MRCLASS = {46-01 (47-01)},
  MRNUMBER = {1336382 (96a:46001)},
}

@book {Braess,
    AUTHOR = {Braess, Dietrich},
     TITLE = {{F}inite {E}lemente},
   EDITION = {Fünfte {A}uflage},
      NOTE = {{T}heorie, {S}chnelle {L}öser und {A}nwendungen in der {E}lastizitätstheorie},
 PUBLISHER = {Springer},
      YEAR = {2013},
     PAGES = {xvi+369},
      ISBN = {978-3-642-34796-2}
}

@book {Grisvard,
    AUTHOR = {Grisvard, Pierre},
     TITLE = {Elliptic problems in nonsmooth domains},
    SERIES = {Monographs and Studies in Mathematics},
    VOLUME = {24},
 PUBLISHER = {Pitman (Advanced Publishing Program), Boston, MA},
      YEAR = {1985},
     PAGES = {xiv+410},
      ISBN = {0-273-08647-2},
   MRCLASS = {35J25 (35-02)},
  MRNUMBER = {775683 (86m:35044)},
MRREVIEWER = {P. Szeptycki},
}

@Book {Evans,
   title = {Partial Differential Equations},
   year = {1998},
   volume = {19},
   publisher = {American Mathematical Society},
   address = {Providence, Rhode Island},
   series = {Graduate Studies in Mathematics},
   ISBN = {0-8218-0772-2},
   in_library = {1},
   author = {Evans, Lawrence C.}
}

@Book{Joly,
    author={Patrick Joly },
    title={Variational methods for time-dependent wave propagation
           problems. },
    publisher={Springer, Berlin },
    year={2003 },
    volume={31 },
    series={Topics in computational wave propagation },
    pages={201--264},
}

repository: ChrisTX/lecture-notes

repo_name: ChrisTX/lecture-notes


text:
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0

package util_test

import (
	"bytes"
	"testing"

	"github.com/stretchr/testify/require"
	"github.com/vmware-tanzu/carvel-imgpkg/pkg/imgpkg/internal/util"
)

func TestLevelLogger(t *testing.T) {
	t.Run("when log level is set to warn only write the warning message", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		subject := util.NewUILevelLogger(util.LogWarn, util.NewBufferLogger(buf))
		subject.Warnf("warning message\n")
		subject.Debugf("debug message\n")
		subject.Tracef("trace message\n")

		require.Equal(t, "Warning: warning message\n", buf.String())
	})

	t.Run("when log level is set to debug only write the warning and debug message", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		subject := util.NewUILevelLogger(util.LogDebug, util.NewBufferLogger(buf))
		subject.Warnf("warning message\n")
		subject.Debugf("debug message\n")
		subject.Tracef("trace message\n")

		require.Equal(t, "Warning: warning message\ndebug message\n", buf.String())
	})

	t.Run("when log level is set to trace only writes all messages", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		subject := util.NewUILevelLogger(util.LogTrace, util.NewBufferLogger(buf))
		subject.Warnf("warning message\n")
		subject.Debugf("debug message\n")
		subject.Tracef("trace message\n")

		require.Equal(t, "Warning: warning message\ndebug message\ntrace message\n", buf.String())
	})
}

func TestIndentedLevelLogger(t *testing.T) {
	t.Run("when base LevelLogger log level is set to warning, the new Indented logger only print warning messages", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		baseLevelLogger := util.NewUILevelLogger(util.LogWarn, util.NewBufferLogger(buf))
		subject := util.NewIndentedLevelLogger(baseLevelLogger)
		subject.Warnf("warning message\n")
		subject.Debugf("debug message\n")
		subject.Tracef("trace message\n")

		require.Equal(t, "  Warning: warning message\n", buf.String())
	})

	t.Run("when base LevelLogger log level is set to debug, the new Indented logger only print warning and debug messages", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		baseLevelLogger := util.NewUILevelLogger(util.LogDebug, util.NewBufferLogger(buf))
		subject := util.NewIndentedLevelLogger(baseLevelLogger)
		subject.Warnf("warning message\n")
		subject.Debugf("debug message\n")
		subject.Tracef("trace message\n")

		require.Equal(t, "  Warning: warning message\n  debug message\n", buf.String())
	})

	t.Run("when base LevelLogger log level is set to trace, the new Indented logger will print all the messages", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		baseLevelLogger := util.NewUILevelLogger(util.LogTrace, util.NewBufferLogger(buf))
		subject := util.NewIndentedLevelLogger(baseLevelLogger)
		subject.Warnf("warning message\n")
		subject.Debugf("debug message\n")
		subject.Tracef("trace message\n")

		require.Equal(t, "  Warning: warning message\n  debug message\n  trace message\n", buf.String())
	})

	t.Run("when indenting 3 times and base logger is set to warning, it the Indented logger only print warning messages", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		baseLevelLogger := util.NewUILevelLogger(util.LogWarn, util.NewBufferLogger(buf))
		firstIndentedLogger := util.NewIndentedLevelLogger(baseLevelLogger)
		secondIndentedLogger := util.NewIndentedLevelLogger(firstIndentedLogger)
		subject := util.NewIndentedLevelLogger(secondIndentedLogger)
		subject.Warnf("warning message\n")
		subject.Debugf("debug message\n")
		subject.Tracef("trace message\n")

		require.Equal(t, "      Warning: warning message\n", buf.String())
	})

	t.Run("calling Logf always print message", func(t *testing.T) {
		buf := bytes.NewBufferString("")
		baseLevelLogger := util.NewUILevelLogger(util.LogWarn, util.NewBufferLogger(buf))
		subject := util.NewIndentedLevelLogger(baseLevelLogger)
		subject.Logf("some message\n")

		require.Equal(t, "  some message\n", buf.String())
	})
}

repository: seanly/imgpkg

repo_name: seanly/imgpkg


text:
#Add sources to the project
sos_sdk_add_subdirectory(SOS_SOURCELIST src)

file(GLOB_RECURSE HEADER_SOURCES ${CMAKE_SOURCE_DIR}/include/*)
list(APPEND SOS_SOURCELIST ${SOURCES} ${HEADER_SOURCES})

set(SOS_OPTION "")
set(SOS_CONFIG release)
set(SOS_ARCH link)
include(${SOS_TOOLCHAIN_CMAKE_PATH}/sos-lib.cmake)

repository: StratifyLabs/ChartAPI

repo_name: StratifyLabs/ChartAPI

extension: cmake


text:
package repository_test

import (
	"bytes"
	"crypto/rand"
	"io"
	"testing"

	"github.com/restic/restic/backend"
	"github.com/restic/restic/pack"
	"github.com/restic/restic/repository"
	. "github.com/restic/restic/test"
)

func randomID() backend.ID {
	id := backend.ID{}
	_, err := io.ReadFull(rand.Reader, id[:])
	if err != nil {
		panic(err)
	}
	return id
}

func TestIndexSerialize(t *testing.T) {
	type testEntry struct {
		id             backend.ID
		pack           backend.ID
		tpe            pack.BlobType
		offset, length uint
	}
	tests := []testEntry{}

	idx := repository.NewIndex()

	// create 50 packs with 20 blobs each
	for i := 0; i < 50; i++ {
		packID := randomID()

		pos := uint(0)
		for j := 0; j < 20; j++ {
			id := randomID()
			length := uint(i*100 + j)
			idx.Store(pack.Data, id, &packID, pos, length)

			tests = append(tests, testEntry{
				id:     id,
				pack:   packID,
				tpe:    pack.Data,
				offset: pos,
				length: length,
			})

			pos += length
		}
	}

	wr := bytes.NewBuffer(nil)
	err := idx.Encode(wr)
	OK(t, err)

	idx2, err := repository.DecodeIndex(wr)
	OK(t, err)
	Assert(t, idx2 != nil,
		"nil returned for decoded index")

	wr2 := bytes.NewBuffer(nil)
	err = idx2.Encode(wr2)
	OK(t, err)

	for _, testBlob := range tests {
		packID, tpe, offset, length, err := idx.Lookup(testBlob.id)
		OK(t, err)

		Equals(t, testBlob.pack, *packID)
		Equals(t, testBlob.tpe, tpe)
		Equals(t, testBlob.offset, offset)
		Equals(t, testBlob.length, length)

		packID, tpe, offset, length, err = idx2.Lookup(testBlob.id)
		OK(t, err)

		Equals(t, testBlob.pack, *packID)
		Equals(t, testBlob.tpe, tpe)
		Equals(t, testBlob.offset, offset)
		Equals(t, testBlob.length, length)
	}

	// add more blobs to idx2
	newtests := []testEntry{}
	for i := 0; i < 10; i++ {
		packID := randomID()

		pos := uint(0)
		for j := 0; j < 10; j++ {
			id := randomID()
			length := uint(i*100 + j)
			idx2.Store(pack.Data, id, &packID, pos, length)

			newtests = append(newtests, testEntry{
				id:     id,
				pack:   packID,
				tpe:    pack.Data,
				offset: pos,
				length: length,
			})

			pos += length
		}
	}

	// serialize idx2, unserialize to idx3
	wr3 := bytes.NewBuffer(nil)
	err = idx2.Encode(wr3)
	OK(t, err)

	idx3, err := repository.DecodeIndex(wr3)
	OK(t, err)
	Assert(t, idx3 != nil,
		"nil returned for decoded index")

	// all old blobs must not be present in the index
	for _, testBlob := range tests {
		_, _, _, _, err := idx3.Lookup(testBlob.id)
		Assert(t, err != nil,
			"found old id %v in serialized index", testBlob.id.Str())
	}

	// all new blobs must be in the index
	for _, testBlob := range newtests {
		packID, tpe, offset, length, err := idx3.Lookup(testBlob.id)
		OK(t, err)

		Equals(t, testBlob.pack, *packID)
		Equals(t, testBlob.tpe, tpe)
		Equals(t, testBlob.offset, offset)
		Equals(t, testBlob.length, length)
	}
}

func TestIndexSize(t *testing.T) {
	idx := repository.NewIndex()

	packs := 200
	blobs := 100
	for i := 0; i < packs; i++ {
		packID := randomID()

		pos := uint(0)
		for j := 0; j < blobs; j++ {
			id := randomID()
			length := uint(i*100 + j)
			idx.Store(pack.Data, id, &packID, pos, length)

			pos += length
		}
	}

	wr := bytes.NewBuffer(nil)

	err := idx.Encode(wr)
	OK(t, err)

	t.Logf("Index file size for %d blobs in %d packs is %d", blobs*packs, packs, wr.Len())
}

// example index serialization from doc/Design.md
var docExample = []byte(`
[ {
  "id": "73d04e6125cf3c28a299cc2f3cca3b78ceac396e4fcf9575e34536b26782413c",
  "blobs": [
    {
      "id": "3ec79977ef0cf5de7b08cd12b874cd0f62bbaf7f07f3497a5b1bbcc8cb39b1ce",
      "type": "data",
      "offset": 0,
      "length": 25
    },{
      "id": "9ccb846e60d90d4eb915848add7aa7ea1e4bbabfc60e573db9f7bfb2789afbae",
      "type": "tree",
      "offset": 38,
      "length": 100
    },
    {
      "id": "d3dc577b4ffd38cc4b32122cabf8655a0223ed22edfd93b353dc0c3f2b0fdf66",
      "type": "data",
      "offset": 150,
      "length": 123
    }
  ]
} ]
`)

var exampleTests = []struct {
	id, packID     backend.ID
	tpe            pack.BlobType
	offset, length uint
}{
	{
		ParseID("3ec79977ef0cf5de7b08cd12b874cd0f62bbaf7f07f3497a5b1bbcc8cb39b1ce"),
		ParseID("73d04e6125cf3c28a299cc2f3cca3b78ceac396e4fcf9575e34536b26782413c"),
		pack.Data, 0, 25,
	}, {
		ParseID("9ccb846e60d90d4eb915848add7aa7ea1e4bbabfc60e573db9f7bfb2789afbae"),
		ParseID("73d04e6125cf3c28a299cc2f3cca3b78ceac396e4fcf9575e34536b26782413c"),
		pack.Tree, 38, 100,
	}, {
		ParseID("d3dc577b4ffd38cc4b32122cabf8655a0223ed22edfd93b353dc0c3f2b0fdf66"),
		ParseID("73d04e6125cf3c28a299cc2f3cca3b78ceac396e4fcf9575e34536b26782413c"),
		pack.Data, 150, 123,
	},
}

func TestIndexUnserialize(t *testing.T) {
	idx, err := repository.DecodeIndex(bytes.NewReader(docExample))
	OK(t, err)

	for _, test := range exampleTests {
		packID, tpe, offset, length, err := idx.Lookup(test.id)
		OK(t, err)

		Equals(t, test.packID, *packID)
		Equals(t, test.tpe, tpe)
		Equals(t, test.offset, offset)
		Equals(t, test.length, length)
	}
}

repository: pombredanne/restic

repo_name: pombredanne/restic


text:
// Copyright 2015 Google Inc.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package uuid

import (
	"database/sql/driver"
	//"encoding/hex"
	"errors"
	"fmt"
)

var DefaultScanner Scanner = &StandardScanner{}

type Scanner interface {
	Scan(interface{}, *UUID) error
	Value(UUID) (driver.Value, error)
}

// StandardScanner implements uuid.Scanner using the original logic from pborman/uuid
type StandardScanner struct{}

func (s *StandardScanner) Scan(src interface{}, uuid *UUID) error {
	if uuid == nil {
		return errors.New("Nil uuid parsed to standard scanner")
	}

	switch src.(type) {
	case string:
		// if an empty UUID comes from a table, we return a null UUID
		if src.(string) == "" {
			return nil
		}

		// see uuid.Parse for required string format
		parsed := Parse(src.(string))

		if parsed == nil {
			return errors.New("Scan: invalid UUID format")
		}

		*uuid = parsed
	case []byte:
		b := src.([]byte)

		// if an empty UUID comes from a table, we return a null UUID
		if len(b) == 0 {
			return nil
		}

		// assumes a simple slice of bytes if 16 bytes
		// otherwise attempts to parse
		if len(b) == 16 {
			*uuid = UUID(b)
		} else {
			u := Parse(string(b))

			if u == nil {
				return errors.New("Scan: invalid UUID format")
			}

			*uuid = u
		}

	default:
		return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
	}

	return nil
}

func (s *StandardScanner) Value(uuid UUID) (driver.Value, error) {
	return uuid.String(), nil
}

// SqlServerScanner implements uuid.Scanner using the logic taken from
// https://github.com/denisenkom/go-mssqldb/blob/7a8f90684760b9ebd0001efcfc0102fcfb47c5d9/uniqueidentifier.go
type SqlServerScanner struct{}

func (s *SqlServerScanner) Scan(val interface{}, uuid *UUID) error {
	if uuid == nil {
		return errors.New("Nil uuid parsed to sql scanner")
	}

	reverse := func(b []byte) {
		for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
			b[i], b[j] = b[j], b[i]
		}
	}

	switch vt := val.(type) {
	case []byte:
		if len(vt) != 16 {
			return errors.New("mssql: invalid UniqueIdentifier length")
		}

		var raw [16]byte

		copy(raw[:], vt)

		reverse(raw[0:4])
		reverse(raw[4:6])
		reverse(raw[6:8])
		return uuid.UnmarshalBinary(raw[:])

	case string:
		return uuid.UnmarshalText([]byte(vt))
	default:
		return fmt.Errorf("mssql: cannot convert %T to UUID, %u", val, vt)
	}
}

func (s *SqlServerScanner) Value(uuid UUID) (driver.Value, error) {
	reverse := func(b []byte) {
		for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
			b[i], b[j] = b[j], b[i]
		}
	}

	var raw [16]byte
	copy(raw[:], uuid[:])

	reverse(raw[0:4])
	reverse(raw[4:6])
	reverse(raw[6:8])

	return raw[:], nil
}

// Scan implements sql.Scanner so UUIDs can be read from databases transparently
// Currently, database types that map to string and []byte are supported. Please
// consult database-specific driver documentation for matching types.
func (uuid *UUID) Scan(src interface{}) error {
	return DefaultScanner.Scan(src, uuid)
}

// Value implements sql.Valuer so that UUIDs can be written to databases
// transparently. Currently, UUIDs map to strings. Please consult
// database-specific driver documentation for matching types.
func (uuid UUID) Value() (driver.Value, error) {
	return DefaultScanner.Value(uuid)
}

repository: womblebob/uuid

repo_name: womblebob/uuid


text:
DESCRIPTION = "A Lightweight Web Application Framework"
SECTION = "devel/python"
PRIORITY = "optional"
LICENSE = "PSF"
PR = "ml1"

SRC_URI = "http://webpy.org/static/web.py-${PV}.tar.gz"
S = "${WORKDIR}/webpy"

inherit distutils

RDEPENDS_${PN} = "\
  python-netserver \
  python-netclient \
  python-pprint \
"

SRC_URI[md5sum] = "439b0700f9f5d422e5db6f28c0f86b11"
SRC_URI[sha256sum] = "01f30f86c9ea41e7fcc9bc4cabb17283de7dbf19c301254161a89dd0a73cb9f3"


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

package serialization // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/dynatraceexporter/internal/serialization"

import (
	"fmt"

	"github.com/dynatrace-oss/dynatrace-metric-utils-go/metric/dimensions"
	"go.opentelemetry.io/collector/pdata/pcommon"
	"go.opentelemetry.io/collector/pdata/pmetric"
	"go.uber.org/zap"

	"github.com/open-telemetry/opentelemetry-collector-contrib/internal/common/ttlmap"
)

func SerializeMetric(logger *zap.Logger, prefix string, metric pmetric.Metric, defaultDimensions, staticDimensions dimensions.NormalizedDimensionList, prev *ttlmap.TTLMap) ([]string, error) {
	var metricLines []string

	ce := logger.Check(zap.DebugLevel, "SerializeMetric")
	var points int

	switch metric.Type() {
	case pmetric.MetricTypeGauge:
		metricLines = serializeGauge(logger, prefix, metric, defaultDimensions, staticDimensions, metricLines)
	case pmetric.MetricTypeSum:
		metricLines = serializeSum(logger, prefix, metric, defaultDimensions, staticDimensions, prev, metricLines)
	case pmetric.MetricTypeHistogram:
		metricLines = serializeHistogram(logger, prefix, metric, defaultDimensions, staticDimensions, metricLines)
	default:
		return nil, fmt.Errorf("metric type %s unsupported", metric.Type().String())
	}

	if ce != nil {
		ce.Write(zap.String("DataType", metric.Type().String()), zap.Int("points", points))
	}

	return metricLines, nil
}

func makeCombinedDimensions(defaultDimensions dimensions.NormalizedDimensionList, dataPointAttributes pcommon.Map, staticDimensions dimensions.NormalizedDimensionList) dimensions.NormalizedDimensionList {
	dimsFromAttributes := make([]dimensions.Dimension, 0, dataPointAttributes.Len())

	dataPointAttributes.Range(func(k string, v pcommon.Value) bool {
		dimsFromAttributes = append(dimsFromAttributes, dimensions.NewDimension(k, v.AsString()))
		return true
	})
	return dimensions.MergeLists(
		defaultDimensions,
		dimensions.NewNormalizedDimensionList(dimsFromAttributes...),
		staticDimensions,
	)
}

repository: DataDog/opentelemetry-collector-contrib

repo_name: DataDog/opentelemetry-collector-contrib


text:
#
#makedepend_1.0.5.bb
#
require xorg-util-common.inc

SUMMARY = "create dependencies in makefiles"

DESCRIPTION = "The makedepend program reads each sourcefile in sequence \
and parses it like a C-preprocessor, processing \
all #include, #define,  #undef, #ifdef, #ifndef, #endif, #if, #elif \
and #else directives so that it can correctly tell which #include, \
directives would be used in a compilation. Any #include, directives \
can reference files having other #include directives, and parsing will \
occur in these files as well."

DEPENDS = "xproto util-macros"
PE = "1"

BBCLASSEXTEND = "native"

LIC_FILES_CHKSUM = "file://COPYING;md5=43a6eda34b48ee821b3b66f4f753ce4f"

SRC_URI[md5sum] = "efb2d7c7e22840947863efaedc175747"
SRC_URI[sha256sum] = "503903d41fb5badb73cb70d7b3740c8b30fe1cc68c504d3b6a85e6644c4e5004"

#
#debian
#
DPR = "0"

repository: takuya-t/meta-debian

repo_name: takuya-t/meta-debian

branch_name: refs/heads/daisy


text:
SUMMARY = "Add TI Gstreamer and DSP support"
HOMEPAGE = "http://www.jumpnowtek.com"
LICENSE = "MIT"

require console-image.bb

PR = "0"

DSP_INSTALL = " \
    gstreamer-ti \
    gst-plugins-base-meta \
    gst-plugins-good-meta \
    gst-plugins-bad-meta \
 "

IMAGE_INSTALL += " \
    ${DSP_INSTALL} \
 "

export IMAGE_BASENAME = "dsp-image"

repository: jumpnow/meta-dsp-overo

repo_name: jumpnow/meta-dsp-overo


text:
# Copyright (c) 2019 Christophe Chapuis <chris.chapuis@gmail.com>
# Copyright (c) 2019 Herman van Hazendonk <github.com@herrie.org>

SUMMARY = "A very simple convenience library for handling properties and signals in C++11."
SECTION = "libs"
LICENSE = "LGPL-3.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=e6a600fd5e1d9cbde2d983680233ad02"

PV = "0.0.1+git${SRCPV}"

SRCREV = "45863e849b39c4921d6553e6d27e267a96ac7d77"
SRC_URI = "git://github.com/lib-cpp/${BPN}.git;branch=master;protocol=https"

S = "${WORKDIR}/git"

do_configure:prepend() {
    echo " " > ${S}/tests/CMakeLists.txt
}

inherit cmake pkgconfig

RDEPENDS:${PN}-dev = ""

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded


text:
@online{Swarm,
	author = {Viktor Trón},
	title = {What is swarm?},
	year = {2015},
	url = {https://github.com/ethersphere/swarm/blob/ac8b54726551d7a590f85d6d377dbcac3ae26794/README.md},
	urldate = {2018-03-16}
}

@online{Whisper,
	author = {Various Authors},
	title = {Ethereum Wiki: Whisper},
	url = {https://github.com/ethereum/wiki/wiki/Whisper},
	urldate = {2018-03-16}
}

@online{Ethereum,
	author = {Various Authors},
	title = {Ethereum Homestead Documentation: What is Ethereum?},
	url = {http://ethdocs.org/en/latest/introduction/what-is-ethereum.html},
	urldate = {2018-03-16}
}

@misc{Bitcoin,
	author = {Satoshi Nakamoto},
	title = {Bitcoin: A Peer-to-Peer Electronic Cash System},
	year = {2009},
	url = {https://bitcoin.org/bitcoin.pdf},
	urldate = {2018-03-16}
}

@online{DLL,
	author = {Stack Exchange User \enquote{o0ragman0o}},
	title = {Can we get all elements stored in a mapping in the contract},
	year = {2017},
	url = {https://ethereum.stackexchange.com/a/15341},
	urlDate = {2018-04-20}
}

@online{TaxicoinGitHub,
	author = {Scott Street},
	title = {Taxicoin on GitHub},
	year = {2018},
	url = {https://github.com/sprusr/taxicoin},
	urlDate = {2018-04-21}
}

@online{Web3Endorsement,
	author = {Various Authors},
	title = {Ethereum Homestead Documentation: Dapps},
	url = {http://www.ethdocs.org/en/latest/contracts-and-transactions/developer-tools.html#developer-tools},
	urlDate = {2018-04-27}
}

@online{WhisperGethWiki,
	author = {Various Authors},
	title = {Go-Ethereum Wiki: Whisper Overview},
	url = {https://github.com/ethereum/go-ethereum/wiki/Whisper-Overview},
	urlDate = {2018-04-27}
}

@misc{IPFS,
	author = {Juan Benet},
	title = {IPFS - Content Addressed, Versioned, P2P File System},
	url = {https://github.com/ipfs/papers/raw/master/ipfs-cap2pfs/ipfs-p2p-file-system.pdf},
	urlDate = {2018-04-27},
	year = {2014}
}

@misc{Status.im,
	url = {https://status.im/whitepaper.pdf},
	urlDate = {2018-04-27},
	year = {2017},
	author = {Various Authors},
	title = {The Status Network: A strategy towards mass adoption of Ethereum}
}

@online{Solidity,
	url = {http://solidity.readthedocs.io/en/latest/},
	urlDate = {2018-04-27},
	title = {Solidity Documentation},
	author = {Various Authors}
}

@online{VueWebpack,
	url = {https://github.com/vuejs-templates/webpack},
	urlDate = {2018-04-27},
	title = {\lstinline{vue-webpack-boilerplate}},
	author = {Various Authors}
}

@online{Truffle,
	url = {http://truffleframework.com/},
	urlDate = {2018-04-27},
	title = {Truffle Framework},
	author = {ConsenSys}
}

@online{NEO,
	url = {https://neo.org/},
	urlDate = {2018-04-27},
	title = {NEO Smart Economy},
	author = {NEO Team}
}

@online{Web3,
	url = {https://github.com/ethereum/web3.js/},
	urlDate = {2018-04-27},
	title = {Ethereum JavaScript API},
	author = {Various Authors}
}

@online{Ganache,
	url = {http://truffleframework.com/ganache/},
	urlDate = {2018-04-27},
	title = {Ganache | Truffle Suite},
	author = {Various Authors}
}

@online{Mocha,
	url = {https://mochajs.org/},
	urlDate = {2018-04-27},
	title = {Mocha - the fun, simple, flexible JavaScript test framework},
	author = {Various Authors}
}

@online{Chai,
	url = {http://chaijs.com/},
	urlDate = {2018-04-27},
	title = {Chai Assertion Library},
	author = {Various Authors}
}

@online{Karma,
	url = {http://karma-runner.github.io/2.0/index.html},
	urlDate = {2018-04-27},
	title = {Karma - Spectacular Test Runner for JavaScript},
	author = {Various Authors}
}

@online{TaxicoinGo,
	url = {https://github.com/taxiproto/taxicoin-go},
	urlDate = {2018-04-27},
	title = {\lstinline{taxicoin-go}},
	author = {Pandelis Zembashis}
}

@online{TaxicoinGo,
	url = {https://infura.io/},
	urlDate = {2018-04-27},
	title = {Infura - Scalable Blockchain Infrastructure},
	author = {ConsenSys}
}

repository: sprusr/taxicoin

repo_name: sprusr/taxicoin


text:
.bottom-bar-container {
    z-index: 999;
    position: fixed;
    bottom: 0px;
    left: 0px;
    width: 100%;
    background: #feefb3;
}
#bottom-bar-table {
    width: 100%;
}
#bottom-bar-message-td {
    width: 60%;
}
#bottom-bar-buttons-td {
    width: 40%
}
#bottom-bar-message-p {
    text-align: left;
    font-size: 13px;
    color: #9f6000;
}
.bottom-bar-message {
    margin-left: 5px;
    text-align: left;
    word-wrap: break-word;
    color: #9f6000;
}
.bottom-bar-buttons {
    margin-top: 5px;
    margin-bottom: 5px;
    text-align: right;
}
#bottom-bar-button-1,
#bottom-bar-button-2,
#bottom-bar-button-3 {
    background: #ffffff;
    border: 1px solid #dcdcdc;
    cursor: pointer;
    color: #9f6000;
    font-family: Verdana, Tahoma, sans-serif;
    font-size: 13px;
    padding: 5px 5px;
    text-decoration: none;
    margin-top: 2px;
    margin-right: 2px;
    width: auto;
    height: auto;
}
#bottom-bar-button-1:hover,
#bottom-bar-button-2:hover,
#bottom-bar-button-3:hover {
    background: #f6f6f6;
}
#bottom-bar-button-1:active,
#bottom-bar-button-2:active,
#bottom-bar-button-3:active {
    position:relative;
    top:1px;
}
.noteWarning {
    color: #990000;
    border: 1px solid #91917f;
    background: #f2efe4 url(/images/alert_warning_bg.gif) left center no-repeat;
    padding: 10px 10px 10px 45px;
    text-align: left;
    font-size:0.9em;
    height: auto;
    width: 445px;
    filter:alpha(opacity=80);
    -moz-opacity:.80;
    opacity:.80;
}
.noteClose {
    position: relative;
    height: 15px;
    width: 15px;
    float: right;
}

extension: css


text:
Automatically generated by Mendeley Desktop 1.19.4
Any changes to this file will be lost if it is regenerated by Mendeley.

BibTeX export options can be customized via Preferences -> BibTeX in Mendeley Desktop

@article{Zhang2020,
abstract = {Background The coronavirus disease 2019 (COVID-19) epidemic, caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), began in Wuhan city, Hubei province, in December, 2019, and has spread throughout China. Understanding the evolving epidemiology and transmission dynamics of the outbreak beyond Hubei would provide timely information to guide intervention policy.},
author = {Zhang, Juanjuan and Litvinova, Maria and Wang, Wei and Wang, Yan and Deng, Xiaowei and Chen, Xinghui and Li, Mei and Zheng, Wen and Yi, Lan and Chen, Xinhua and Wu, Qianhui and Liang, Yuxia and Wang, Xiling and Yang, Juan and Sun, Kaiyuan and Longini, Ira M and Halloran, M Elizabeth and Wu, Peng and Cowling, Benjamin J and Merler, Stefano and Viboud, Cecile and Vespignani, Alessandro and Ajelli, Marco and Yu, Hongjie},
doi = {10.1016/s1473-3099(20)30230-9},
file = {:Users/sepmein/Qsync/Papers//Zhang et al.{\_}2020{\_}Evolving epidemiology and transmission dynamics of coronavirus disease 2019 outside Hubei province, China a descriptiv.pdf:pdf},
issn = {14733099},
journal = {The Lancet Infectious Diseases},
number = {20},
pages = {1--10},
publisher = {Elsevier Ltd},
title = {{Evolving epidemiology and transmission dynamics of coronavirus disease 2019 outside Hubei province, China: a descriptive and modelling study}},
url = {http://dx.doi.org/10.1016/S1473-3099(20)30230-9},
volume = {3099},
year = {2020}
}

license: Unlicense

repository: sepmein/references

repo_name: sepmein/references


text:
html, body{
	font-size: 16px;
}

.link-image{
/*	float: left;
*/	padding-right: 1.5rem;
	padding-bottom: 1.5rem;
}

repository: rommel-rodriguez/booksite

repo_name: rommel-rodriguez/booksite


text:
const { server, channels, roles } = require('../config.json');

// Export event so it can be used
module.exports = async (client, member) => {
    await welcome(member);

    if (client.database) {
        verified(member);
    }
};

// Send welcome message
async function welcome(member) {
    const message = `Welcome to ${server.name}, ${member}! ` +
        `Please read the <#${channels.rules}> and verify yourself to start chatting.`;
    await member.guild.channels.cache.get(channels.welcome)
        .send(message).catch(console.error);
}

// Persistent verification
async function verified(member) {
    const { isVerified, addUsername, getNames } = require('../database/interface.js');
    const user = member.user;

    var addRole = async function (isVerified) {
        if (!isVerified) return;

        // Give verified role to member
        console.log(`Giving role to previously verified member ${user.tag}`);
        await member.roles.add(roles.verified).catch(console.error);

        // Add username to history if different from previous
        var addUser = function (history) {
            const last = history.sort((a, b) => b.name_id - a.name_id).shift();

            if (!last) {
                // This shouldn't happen since we only call this if isVerified() succeeds
                console.error(`No username history found for ${user.tag}`);
            }

            else if (last.username !== user.username ||
                    last.discriminator !== user.discriminator) {
                addUsername(user);
            }
        };
        getNames(user, addUser);
    };

    // Lookup target member from database
    isVerified(user, addRole);
}

repository: mtsev/seba

repo_name: mtsev/seba

gha_language: JavaScript

extension: js


text:
package nmea

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

func TestPSONCMS(t *testing.T) {
	var tests = []struct {
		name string
		raw  string
		err  string
		msg  PSONCMS
	}{
		{
			name: "good sentence",
			raw:  "$PSONCMS,0.0905,0.4217,0.9020,-0.0196,-1.7685,0.3861,-9.6648,-0.0116,0.0065,-0.0080,0.0581,0.3846,0.7421,33.1*76",
			msg: PSONCMS{
				BaseSentence:      BaseSentence{},
				Quaternion0:       0.0905,
				Quaternion1:       0.4217,
				Quaternion2:       0.9020,
				Quaternion3:       -0.0196,
				AccelerationX:     -1.7685,
				AccelerationY:     0.3861,
				AccelerationZ:     -9.6648,
				RateOfTurnX:       -0.0116,
				RateOfTurnY:       0.0065,
				RateOfTurnZ:       -0.0080,
				MagneticFieldX:    0.0581,
				MagneticFieldY:    0.3846,
				MagneticFieldZ:    0.7421,
				SensorTemperature: 33.1,
			},
		},
		{
			name: "invalid Quaternion0",
			raw:  "$PSONCMS,x,0.4217,0.9020,-0.0196,-1.7685,0.3861,-9.6648,-0.0116,0.0065,-0.0080,0.0581,0.3846,0.7421,33.1*1C",
			err:  "nmea: PSONCMS invalid q0 from quaternions: x",
		},
		{
			name: "invalid Quaternion1",
			raw:  "$PSONCMS,0.0905,x,0.9020,-0.0196,-1.7685,0.3861,-9.6648,-0.0116,0.0065,-0.0080,0.0581,0.3846,0.7421,33.1*10",
			err:  "nmea: PSONCMS invalid q1 from quaternions: x",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			m, err := Parse(tt.raw)
			if tt.err != "" {
				assert.Error(t, err)
				assert.EqualError(t, err, tt.err)
			} else {
				assert.NoError(t, err)
				psoncms := m.(PSONCMS)
				psoncms.BaseSentence = BaseSentence{}
				assert.Equal(t, tt.msg, psoncms)
			}
		})
	}
}

repository: adrianmo/go-nmea

repo_name: adrianmo/go-nmea


text:
@Article{stanislawek2013information,
  title = {Information Processing Institute A class ification of the questionnaire of reviewers and app licants},
  author = {Tomasz Stanis{\l}awek and Jaros{\l}aw Protasiewicz and Marek Koz{\l}owski and Agata Kopacz},
  journal = {Zeszyty Naukowe Uniwersytetu Szczeci{\'n}skiego. Ekonomiczne Problemy Us{\l}ug},
  number = {106 E-gospodarka: problemy, metody, aplikacje},
  pages = {321--343},
  year = {2013},
}


text:
package errors

import (
	"encoding/json"
	"errors"
	"reflect"
	"testing"
)

func TestZeroErrorEncoding(t *testing.T) {
	type S struct {
		Err *Error
	}
	var s S
	bytes, err := json.Marshal(s)
	if err != nil {
		t.Fatal(err)
	}
	var s1 S
	err = json.Unmarshal(bytes, &s1)
	if err != nil {
		t.Fatal(err)
	}
	if s1.Err != nil {
		t.Errorf("expected nil in field, but got %+v", s1.Err)
	}
}

func TestErrorEncoding(t *testing.T) {
	errVal := &Error{
		Type: Server,
		Help: "helpful text\nwith linebreaks!",
		Err:  errors.New("underlying error"),
	}
	bytes, err := json.Marshal(errVal)
	if err != nil {
		t.Fatal(err)
	}

	var got Error
	err = json.Unmarshal(bytes, &got)
	if err != nil {
		t.Fatal(err)
	}

	if got.Type != errVal.Type {
		println(string(bytes))
		t.Errorf("error type: expected %q, got %q", errVal.Type, got.Type)
	}
	if got.Help != errVal.Help || got.Err.Error() != errVal.Err.Error() {
		t.Errorf("expected %+v\ngot %+v", errVal, got)
	}
	if !reflect.DeepEqual(errVal, &got) {
		t.Errorf("not deepEqual\nexpected %#v\ngot %#v", errVal, got)
	}
}

repository: fluxcd/flux

repo_name: fluxcd/flux


text:
package security

// TaskInfo 结构体
type TaskInfo struct {
	// 任务唯一标识
	ItemId string `json:"item_id,omitempty" xml:"item_id,omitempty"`
	// 任务处理进度: 1-处理完成 (可立即通过对应的查询接口查询处理结果), 2-异步处理中(需等待app_info.callback_url接收到反向通知后再查询结果) ; 对于app_info.data_type为1目前都是异步处理，此字段返回2; 对于app_info.data_type为2目前都是同步处理，此字段返回1
	Progress int64 `json:"progress,omitempty" xml:"progress,omitempty"`
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao


text:
// Copyright (c) 2021. Quirino Gervacio

package tlib

import (
	"testing"

	"github.com/go-playground/validator/v10"

	"github.com/stretchr/testify/assert"
)

func Test_Db_String(t *testing.T) {
	pgc := &PGConn{
		Host:     "localhost",
		Port:     5432,
		User:     "user",
		Password: "password",
		Dbname:   "dbname",
		Extras:   "sslMode=disable",
	}
	assert.Equal(t,
		"postgres://user:password@localhost:5432/dbname?sslMode=disable",
		pgc.String())
}

func Test_Db_Peek(t *testing.T) {
	pgc := &PGConn{
		Host:     "localhost",
		Port:     5432,
		User:     "user",
		Password: "password",
		Dbname:   "dbname",
		Extras:   "sslMode=disable",
	}
	assert.Equal(t,
		"postgres://user:***@localhost:5432/dbname?sslMode=disable",
		pgc.Peek())
}

func Test_Db_Validate_Pass(t *testing.T) {
	pgc := &PGConn{
		Host:     "localhost",
		Port:     5432,
		User:     "user",
		Password: "password",
		Dbname:   "dbname",
		Extras:   "sslMode=disable",
	}
	assert.Nil(t, pgc.Validate())
}

func Test_Db_Validate_Fail(t *testing.T) {
	pgc := &PGConn{}
	err := pgc.Validate()
	assert.NotNil(t, err)
	assert.Equal(t, 5, len(err.(validator.ValidationErrors)))

	// missing port
	pgc = &PGConn{
		Host:     "localhost",
		User:     "user",
		Password: "password",
		Dbname:   "dbname",
		Extras:   "sslMode=disable",
	}
	err = pgc.Validate()
	assert.NotNil(t, err)
	assert.Equal(t, 1, len(err.(validator.ValidationErrors)))
}

repository: qgervacio/tlib-go

repo_name: qgervacio/tlib-go


text:
DESCRIPTION = "c-ares is a C library that resolves names asynchronously."
HOMEPAGE = "http://daniel.haxx.se/projects/c-ares/"
SECTION = "libs"
SRC_URI = "http://daniel.haxx.se/projects/c-ares/c-ares-${PV}.tar.gz"
LICENSE = "MIT"
S = "${WORKDIR}/c-ares-${PV}"

inherit autotools

do_stage() {
        oe_libinstall -C .libs -a libcares ${STAGING_LIBDIR}
	install -d ${STAGING_INCDIR}/ares
	install -m 0644 ares*.h ${STAGING_INCDIR}/ares/
}


text:
@Manual{R-base,
  title = {R: A Language and Environment for Statistical Computing},
  author = {{R Core Team}},
  organization = {R Foundation for Statistical Computing},
  address = {Vienna, Austria},
  year = {2017},
  url = {https://www.R-project.org/},
}
@Manual{R-bindrcpp,
  title = {bindrcpp: An 'Rcpp' Interface to Active Bindings},
  author = {Kirill Müller},
  year = {2017},
  note = {R package version 0.2},
  url = {https://CRAN.R-project.org/package=bindrcpp},
}
@Manual{R-bookdown,
  title = {bookdown: Authoring Books and Technical Documents with R Markdown},
  author = {Yihui Xie},
  year = {2017},
  note = {R package version 0.4},
  url = {https://github.com/rstudio/bookdown},
}
@Manual{R-dplyr,
  title = {dplyr: A Grammar of Data Manipulation},
  author = {Hadley Wickham and Romain Francois and Lionel Henry and Kirill Müller},
  year = {2017},
  note = {R package version 0.7.2},
  url = {https://CRAN.R-project.org/package=dplyr},
}
@Manual{R-DT,
  title = {DT: A Wrapper of the JavaScript Library 'DataTables'},
  author = {Yihui Xie},
  year = {2016},
  note = {R package version 0.2},
  url = {https://CRAN.R-project.org/package=DT},
}
@Manual{R-knitr,
  title = {knitr: A General-Purpose Package for Dynamic Report Generation in R},
  author = {Yihui Xie},
  year = {2017},
  note = {R package version 1.16},
  url = {https://CRAN.R-project.org/package=knitr},
}
@Manual{R-openair,
  title = {openair: Tools for the Analysis of Air Pollution Data},
  author = {David Carslaw and Karl Ropkins},
  year = {2017},
  note = {R package version 2.1-0},
  url = {https://CRAN.R-project.org/package=openair},
}
@Manual{R-readr,
  title = {readr: Read Rectangular Text Data},
  author = {Hadley Wickham and Jim Hester and Romain Francois},
  year = {2017},
  note = {R package version 1.1.1},
  url = {https://CRAN.R-project.org/package=readr},
}
@Manual{R-rmarkdown,
  title = {rmarkdown: Dynamic Documents for R},
  author = {JJ Allaire and Joe Cheng and Yihui Xie and Jonathan McPherson and Winston Chang and Jeff Allen and Hadley Wickham and Aron Atkins and Rob Hyndman and Ruben Arslan},
  year = {2017},
  note = {R package version 1.6},
  url = {https://CRAN.R-project.org/package=rmarkdown},
}


text:
package master

import "errors"

type status string

const (
	statusInit    status = "init"
	statusRunning status = "running"
	statusIdle    status = "idle"
	statusCancel  status = "cancel"
)

// App states
const (
	jobPending      jobState = "pending"
	jobProvisioning jobState = "provisioning"
	jobRunning      jobState = "running"
	jobFinished     jobState = "finished"
	jobCancel       jobState = "cancel"
	jobError        jobState = "error"
)

// Error
var (
	ErrAppNotRunning = errors.New("application is not running")
	ErrAppIsFinished = errors.New("application is finished already")
	ErrAppIsCanceled = errors.New("application is canceled")
	ErrCantDeleteApp = errors.New("cannot delete a %s application")
)

repository: go-benchmark/gobench

repo_name: go-benchmark/gobench


text:
@inproceedings{basu2012cfbte,
 address = {Paris, France},
 author = {Basu, Anirban and Dwyer, Natasha and Naicken, Stephen},
 booktitle = {Proceedings of the Annual Conference on Privacy, Security and Trust (PST)},
 title = {A concordance framework for building trust evidences},
 year = {2012}
}

gha_language: TeX


text:
package stackplan

import (
	"errors"
	"koding/db/models"

	"gopkg.in/mgo.v2/bson"

	"github.com/koding/logging"
)

// DetachOptions groups parameters for stack detach operation.
type DetachOptions struct {
	Stack *models.ComputeStack
	Log   logging.Logger
}

// Valid implements the kloud.Validator interface.
func (opts *DetachOptions) Valid() error {
	if opts == nil {
		return errors.New("invalid nil options")
	}

	if opts.Stack == nil {
		return errors.New("invalid nil stack")
	}

	return nil
}

// DestroyOptions groups parameters for stack destroy operation.
type DestroyOptions struct {
	Stack *models.ComputeStack
	Log   logging.Logger
}

// Valid implements the kloud.Validator interface.
func (opts *DestroyOptions) Valid() error {
	if opts == nil {
		return errors.New("invalid nil options")
	}

	if opts.Stack == nil {
		return errors.New("invalid nil stack")
	}

	return nil
}

// MigrationStatus describes a migration state.
type MigrationStatus string

const (
	MigrationMigrating = MigrationStatus("Migrating")
	MigrationMigrated  = MigrationStatus("Migrated")
	MigrationAborted   = MigrationStatus("Aborted")
	MigrationError     = MigrationStatus("Error")
)

// UpdateMigrationOptions groups parameters used for marking jMachine as
// migrated or updating partial migration status.
type UpdateMigrationOptions struct {
	MachineID bson.ObjectId // jMachine.objectId
	Meta      interface{}   // jMachine.meta.migration
	Log       logging.Logger
}

// MigrateOptions groups parameters needed to create stacks for
// migrated machines.
type MigrateOptions struct {
	MachineIDs []bson.ObjectId
	Machines   []interface{}
	Provider   string
	Identifier string
	Username   string
	GroupName  string
	StackName  string
	Template   string

	Log logging.Logger
}

// Database describes an interface for stack's database operations.
//
// The stack deletion operation consist of two phases - removing metadata and
// removing actual resources. The first phase is referred to as detach and
// the second - destroy. Removing metadata is removing jRelationships,
// jMachine.users docs and setting proper states on both jMachine and
// jComputeStack. Removing resources is destroying them on terraform part and
// then removing corresponding docs from mongo.
//
// TODO(rjeczalik): move updateMachines from {aws,vagrant}/stackplan.go here
// and merge them to single, generic Update(*UpdateOptions) method.
type Database interface {
	// Detach detaches user from the stack. The operation is performed
	// prior to stack reinit - it allows the stack to be concurrently
	// deleted while enabling user to start building new stack.
	Detach(*DetachOptions) error

	// Destroy removes the stack completely.
	Destroy(*DestroyOptions) error

	// UpdateMigration updates migration metadata - jMachine.migration.
	UpdateMigration(*UpdateMigrationOptions) error

	// Migrate creates a stack from migrated machines.
	Migrate(*MigrateOptions) error
}

// DatabaseBuilder is a decorator for Builder and Database values.
//
// Both are required to be non-nil.
type DatabaseBuilder struct {
	Database
	*Builder
}

// Detach detaches the stack built by the underlying Builder.
//
// Prior to calling Detach, the Builder is required to have
// the stack successfully built with the BuildStack method.
//
// Otherwise the behavior of the method is unspecified.
func (db *DatabaseBuilder) Detach() error {
	opts := &DetachOptions{
		Stack: db.Builder.Stack.Stack,
		Log:   db.log().New(db.Builder.Stack.Stack.Id.Hex()),
	}

	return db.Database.Detach(opts)
}

// Destroy destroys the stack built by the underlying Builder.
//
// Prior to calling Destroy, the Builder is required to have
// the stack successfully built with the BuildStack method.
//
// Otherwise the behavior of the method is unspecified.
func (db *DatabaseBuilder) Destroy() error {
	opts := &DestroyOptions{
		Stack: db.Builder.Stack.Stack,
		Log:   db.log().New(db.Builder.Stack.Stack.Id.Hex()),
	}

	return db.Database.Destroy(opts)
}

// UpdateMigration is responsible for updating migration status
// for the machine with specified ID.
func (db *DatabaseBuilder) UpdateMigration(opts *UpdateMigrationOptions) error {
	optsCopy := *opts

	if optsCopy.Log == nil {
		optsCopy.Log = db.log()
	}

	return db.Database.UpdateMigration(&optsCopy)
}

// Migrate creates template and a stack for the given migrated machines.
func (db *DatabaseBuilder) Migrate(opts *MigrateOptions) error {
	optsCopy := *opts

	if optsCopy.Log == nil {
		optsCopy.Log = db.log()
	}

	return db.Database.Migrate(&optsCopy)
}

func (db *DatabaseBuilder) log() logging.Logger {
	if db.Builder.Log != nil {
		return db.Builder.Log
	}

	return defaultLog
}

repository: f/koding

repo_name: f/koding

gha_language: CoffeeScript