text:
package events_test

import (
	"errors"
	"testing"

	. "github.com/petergtz/pegomock"
	"github.com/runatlantis/atlantis/server/core/config/valid"
	runtime_mocks "github.com/runatlantis/atlantis/server/core/runtime/mocks"
	runtimematchers "github.com/runatlantis/atlantis/server/core/runtime/mocks/matchers"
	"github.com/runatlantis/atlantis/server/events"
	"github.com/runatlantis/atlantis/server/events/command"
	"github.com/runatlantis/atlantis/server/events/mocks"
	"github.com/runatlantis/atlantis/server/events/models"
	"github.com/runatlantis/atlantis/server/events/models/testdata"
	vcsmocks "github.com/runatlantis/atlantis/server/events/vcs/mocks"
	"github.com/runatlantis/atlantis/server/logging"
	. "github.com/runatlantis/atlantis/testing"
)

var preWh events.DefaultPreWorkflowHooksCommandRunner
var preWhWorkingDir *mocks.MockWorkingDir
var preWhWorkingDirLocker *mocks.MockWorkingDirLocker
var whPreWorkflowHookRunner *runtime_mocks.MockPreWorkflowHookRunner
var preCommitStatusUpdater *mocks.MockCommitStatusUpdater

func preWorkflowHooksSetup(t *testing.T) {
	RegisterMockTestingT(t)
	vcsClient := vcsmocks.NewMockClient()
	preWhWorkingDir = mocks.NewMockWorkingDir()
	preWhWorkingDirLocker = mocks.NewMockWorkingDirLocker()
	whPreWorkflowHookRunner = runtime_mocks.NewMockPreWorkflowHookRunner()
	preCommitStatusUpdater = mocks.NewMockCommitStatusUpdater()
	preWorkflowHookURLGenerator := mocks.NewMockPreWorkflowHookURLGenerator()

	preWh = events.DefaultPreWorkflowHooksCommandRunner{
		VCSClient:             vcsClient,
		WorkingDirLocker:      preWhWorkingDirLocker,
		WorkingDir:            preWhWorkingDir,
		PreWorkflowHookRunner: whPreWorkflowHookRunner,
		CommitStatusUpdater:   preCommitStatusUpdater,
		Router:                preWorkflowHookURLGenerator,
	}
}

func newBool(b bool) *bool {
	return &b
}

func TestRunPreHooks_Clone(t *testing.T) {

	log := logging.NewNoopLogger(t)

	var newPull = testdata.Pull
	newPull.BaseRepo = testdata.GithubRepo

	ctx := &command.Context{
		Pull:     newPull,
		HeadRepo: testdata.GithubRepo,
		User:     testdata.User,
		Log:      log,
	}

	testHook := valid.WorkflowHook{
		StepName:   "test",
		RunCommand: "some command",
	}

	repoDir := "path/to/repo"
	result := "some result"
	runtimeDesc := ""

	pCtx := models.WorkflowHookCommandContext{
		BaseRepo: testdata.GithubRepo,
		HeadRepo: testdata.GithubRepo,
		Pull:     newPull,
		Log:      log,
		User:     testdata.User,
		Verbose:  false,
	}

	t.Run("success hooks in cfg", func(t *testing.T) {
		preWorkflowHooksSetup(t)

		var unlockCalled = newBool(false)
		unlockFn := func() {
			unlockCalled = newBool(true)
		}

		globalCfg := valid.GlobalCfg{
			Repos: []valid.Repo{
				{
					ID: testdata.GithubRepo.ID(),
					PreWorkflowHooks: []*valid.WorkflowHook{
						&testHook,
					},
				},
			},
		}

		preWh.GlobalCfg = globalCfg

		When(preWhWorkingDirLocker.TryLock(testdata.GithubRepo.FullName, newPull.Num, events.DefaultWorkspace, events.DefaultRepoRelDir)).ThenReturn(unlockFn, nil)
		When(preWhWorkingDir.Clone(log, testdata.GithubRepo, newPull, events.DefaultWorkspace, []string{})).ThenReturn(repoDir, false, nil)
		When(whPreWorkflowHookRunner.Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))).ThenReturn(result, runtimeDesc, nil)

		err := preWh.RunPreHooks(ctx, nil)

		Ok(t, err)
		whPreWorkflowHookRunner.VerifyWasCalledOnce().Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))
		Assert(t, *unlockCalled == true, "unlock function called")
	})

	t.Run("success hooks not in cfg", func(t *testing.T) {
		preWorkflowHooksSetup(t)
		globalCfg := valid.GlobalCfg{
			Repos: []valid.Repo{
				// one with hooks but mismatched id
				{
					ID: "id1",
					PreWorkflowHooks: []*valid.WorkflowHook{
						&testHook,
					},
				},
				// one with the correct id but no hooks
				{
					ID:               testdata.GithubRepo.ID(),
					PreWorkflowHooks: []*valid.WorkflowHook{},
				},
			},
		}

		preWh.GlobalCfg = globalCfg

		err := preWh.RunPreHooks(ctx, nil)

		Ok(t, err)

		whPreWorkflowHookRunner.VerifyWasCalled(Never()).Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))
		preWhWorkingDirLocker.VerifyWasCalled(Never()).TryLock(testdata.GithubRepo.FullName, newPull.Num, events.DefaultWorkspace, "")
		preWhWorkingDir.VerifyWasCalled(Never()).Clone(log, testdata.GithubRepo, newPull, events.DefaultWorkspace, []string{})
	})

	t.Run("error locking work dir", func(t *testing.T) {
		preWorkflowHooksSetup(t)

		globalCfg := valid.GlobalCfg{
			Repos: []valid.Repo{
				{
					ID: testdata.GithubRepo.ID(),
					PreWorkflowHooks: []*valid.WorkflowHook{
						&testHook,
					},
				},
			},
		}

		preWh.GlobalCfg = globalCfg

		When(preWhWorkingDirLocker.TryLock(testdata.GithubRepo.FullName, newPull.Num, events.DefaultWorkspace, events.DefaultRepoRelDir)).ThenReturn(func() {}, errors.New("some error"))

		err := preWh.RunPreHooks(ctx, nil)

		Assert(t, err != nil, "error not nil")
		preWhWorkingDir.VerifyWasCalled(Never()).Clone(log, testdata.GithubRepo, newPull, events.DefaultWorkspace, []string{})
		whPreWorkflowHookRunner.VerifyWasCalled(Never()).Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))
	})

	t.Run("error cloning", func(t *testing.T) {
		preWorkflowHooksSetup(t)

		var unlockCalled = newBool(false)
		unlockFn := func() {
			unlockCalled = newBool(true)
		}

		globalCfg := valid.GlobalCfg{
			Repos: []valid.Repo{
				{
					ID: testdata.GithubRepo.ID(),
					PreWorkflowHooks: []*valid.WorkflowHook{
						&testHook,
					},
				},
			},
		}

		preWh.GlobalCfg = globalCfg

		When(preWhWorkingDirLocker.TryLock(testdata.GithubRepo.FullName, newPull.Num, events.DefaultWorkspace, events.DefaultRepoRelDir)).ThenReturn(unlockFn, nil)
		When(preWhWorkingDir.Clone(log, testdata.GithubRepo, newPull, events.DefaultWorkspace, []string{})).ThenReturn(repoDir, false, errors.New("some error"))

		err := preWh.RunPreHooks(ctx, nil)

		Assert(t, err != nil, "error not nil")

		whPreWorkflowHookRunner.VerifyWasCalled(Never()).Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))
		Assert(t, *unlockCalled == true, "unlock function called")
	})

	t.Run("error running pre hook", func(t *testing.T) {
		preWorkflowHooksSetup(t)

		var unlockCalled = newBool(false)
		unlockFn := func() {
			unlockCalled = newBool(true)
		}

		globalCfg := valid.GlobalCfg{
			Repos: []valid.Repo{
				{
					ID: testdata.GithubRepo.ID(),
					PreWorkflowHooks: []*valid.WorkflowHook{
						&testHook,
					},
				},
			},
		}

		preWh.GlobalCfg = globalCfg

		When(preWhWorkingDirLocker.TryLock(testdata.GithubRepo.FullName, newPull.Num, events.DefaultWorkspace, events.DefaultRepoRelDir)).ThenReturn(unlockFn, nil)
		When(preWhWorkingDir.Clone(log, testdata.GithubRepo, newPull, events.DefaultWorkspace, []string{})).ThenReturn(repoDir, false, nil)
		When(whPreWorkflowHookRunner.Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))).ThenReturn(result, runtimeDesc, errors.New("some error"))

		err := preWh.RunPreHooks(ctx, nil)

		Assert(t, err != nil, "error not nil")
		Assert(t, *unlockCalled == true, "unlock function called")
	})

	t.Run("comment args passed to webhooks", func(t *testing.T) {
		preWorkflowHooksSetup(t)

		var unlockCalled = newBool(false)
		unlockFn := func() {
			unlockCalled = newBool(true)
		}

		globalCfg := valid.GlobalCfg{
			Repos: []valid.Repo{
				{
					ID: testdata.GithubRepo.ID(),
					PreWorkflowHooks: []*valid.WorkflowHook{
						&testHook,
					},
				},
			},
		}

		cmd := &events.CommentCommand{
			Flags: []string{"comment", "args"},
		}

		expectedCtx := pCtx
		expectedCtx.EscapedCommentArgs = []string{"\\c\\o\\m\\m\\e\\n\\t", "\\a\\r\\g\\s"}

		preWh.GlobalCfg = globalCfg

		When(preWhWorkingDirLocker.TryLock(testdata.GithubRepo.FullName, newPull.Num, events.DefaultWorkspace, events.DefaultRepoRelDir)).ThenReturn(unlockFn, nil)
		When(preWhWorkingDir.Clone(log, testdata.GithubRepo, newPull, events.DefaultWorkspace, []string{})).ThenReturn(repoDir, false, nil)
		When(whPreWorkflowHookRunner.Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))).ThenReturn(result, runtimeDesc, nil)

		err := preWh.RunPreHooks(ctx, cmd)

		Ok(t, err)
		whPreWorkflowHookRunner.VerifyWasCalledOnce().Run(runtimematchers.AnyModelsWorkflowHookCommandContext(), EqString(testHook.RunCommand), EqString(repoDir))
		Assert(t, *unlockCalled == true, "unlock function called")
	})
}

repository: gocardless/atlantis

repo_name: gocardless/atlantis


text:
# SPDX-License-Identifier: MIT

# Currently requires ptest to be set in local.conf as a member of
# DISTRO_FEATURES, as is proper. However, we need to eventually have that setup
# and working here.

require mion-image-onlpv1.bb

#DISTRO_FEATURES_append += " ptest"

IMAGE_FEATURES += " ptest-pkgs"
IMAGE_INSTALL += "ptest-runner"

license: MIT

repository: NetworkGradeLinux/meta-mion

license_type: permissive

repo_name: NetworkGradeLinux/meta-mion

branch_name: refs/heads/dunfell

gha_license_id: MIT

gha_language: C

extension: bb


text:
package main

import (
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	uuid "github.com/satori/go.uuid"
)

// index handles HTTP requests
func index(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodPost {
		log.Println("Handling post..")
		indexAction(w, r)
		return
	}
	//
	w.Header().Set("Content-Type", "text/html")
	err := tpls.ExecuteTemplate(w, "index.gohtml", struct {
		Error string
		Done  string
	}{
		Error: r.FormValue("error"),
		Done:  r.FormValue("done"),
	})
	if err != nil {
		log.Fatalln(err)
	}
}

func indexAction(w http.ResponseWriter, r *http.Request) {
	name := r.FormValue("name")
	ep := r.FormValue("ep")
	ct := r.FormValue("ct")
	pl := r.FormValue("pl")
	// 2021-01-22T12:41
	d := r.FormValue("due") + ":00Z"
	due, err := time.Parse(time.RFC3339, d)
	if err != nil {
		log.Println("Invalid date:", d)
		http.Redirect(w, r, "/?error=invalid-date", http.StatusSeeOther)
		return
	}
	cd, err := strconv.Atoi(r.FormValue("cd"))
	if err != nil {
		cd = 200
	}
	j := job{
		UUID:         fmt.Sprintf("%s", uuid.NewV4()),
		Name:         name,
		Endpoint:     ep,
		ContentType:  ct,
		Payload:      pl,
		Due:          due,
		Status:       statusQueued,
		HTTPOkStatus: cd,
	}
	log.Printf("Creating job: %s (%s)\n", name, j.UUID)
	db.Create(&j)
	http.Redirect(w, r, fmt.Sprintf("/?done=%s", j.UUID), http.StatusSeeOther)
}

repository: brugnara/background-job-system

repo_name: brugnara/background-job-system

branch_name: refs/heads/main

extension: go


text:
DESCRIPTION = "Another Python SQLite Wrapper"
HOMEPAGE = "https://code.google.com/p/apsw/"
DEPENDS = "sqlite3"
LICENSE = "Libpng"
LIC_FILES_CHKSUM = "file://PKG-INFO;md5=9a1ca3283c0390f7cca24fc1cbe71de0"
PR = "0"

SRC_URI = "http://apsw.googlecode.com/files/apsw-${PV}.zip"

SRC_URI[md5sum] = "5393765e7ef55def11dae08149133136"
SRC_URI[sha256sum] = "4e58472b6adff5aec9830ae209d65815d0d6ca74878d6cfed7becbbadec096b7"

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

#inherit setuptools
inherit autotools distutils

BBCLASSEXTEND = "native"

license: Unlicense

repository: areadelta/recipes-local

repo_name: areadelta/recipes-local

branch_name: refs/heads/master


text:
@inproceedings{,
  abstract = {Abstract goes here},
  author = {Firstname Lastname and Firstname Lastname},
  title = {Paper Title}
}

repository: JabRef/jabref

repo_name: JabRef/jabref

gha_language: Java

extension: bib


text:
package interfaces

import (
	"context"

	"github.com/quangdangfit/go-admin/app/models"
	"github.com/quangdangfit/go-admin/app/schema"
)

// IRoleService interface
type IRoleService interface {
	Create(ctx context.Context, item *schema.RoleBodyParams) (*models.Role, error)
}


text:
# Copyright 2017 Raptor Engineering, LLC
# Copyright 2014-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
SUMMARY = "Rest API Daemon"
DESCRIPTION = "Daemon to handle RESTful interface."
SECTION = "base"
PR = "r1"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://rest.py;beginline=6;endline=19;md5=0b1ee7d6f844d472fa306b2fee2167e0"

DEPENDS_append = " update-rc.d-native"

SRC_URI = "file://setup-rest-api.sh \
           file://rest.py \
           file://rest_bmc.py \
           file://rest_fruid.py \
           file://rest_gpios.py \
           file://rest_server.py \
           file://rest_sensors.py \
           file://rest_slotid.py \
           file://bmc_command.py \
          "

S = "${WORKDIR}"

binfiles = "rest.py rest_bmc.py rest_fruid.py rest_gpios.py rest_server.py rest_sensors.py bmc_command.py rest_slotid.py setup-rest-api.sh"

pkgdir = "rest-api"

do_install() {
  dst="${D}/usr/local/fbpackages/${pkgdir}"
  bin="${D}/usr/local/bin"
  install -d $dst
  install -d $bin
  for f in ${binfiles}; do
    install -m 755 $f ${dst}/$f
    ln -snf ../fbpackages/${pkgdir}/$f ${bin}/$f
  done
  for f in ${otherfiles}; do
    install -m 644 $f ${dst}/$f
  done
  install -d ${D}${sysconfdir}/init.d
  install -d ${D}${sysconfdir}/rcS.d
  install -m 755 setup-rest-api.sh ${D}${sysconfdir}/init.d/setup-rest-api.sh
  update-rc.d -r ${D} setup-rest-api.sh start 95 2 3 4 5  .
}

FBPACKAGEDIR = "${prefix}/local/fbpackages"

FILES_${PN} = "${FBPACKAGEDIR}/rest-api ${prefix}/local/bin ${sysconfdir} "

# Inhibit complaints about .debug directories for the fand binary:

INHIBIT_PACKAGE_DEBUG_SPLIT = "1"
INHIBIT_PACKAGE_STRIP = "1"


text:
# base recipe: meta-security/recipes-security/libmhash/libmhash_0.9.9.9.bb
# base branch: warrior

SUMMARY = "Library of hashing algorithms."
DESCRIPTION = "\
  Mhash is a free (under GNU Lesser GPL) library \
  which provides a uniform interface to a large number of hash \
  algorithms. These algorithms can be used to compute checksums, \
  message digests, and other signatures. \
  "
HOMEPAGE = "http://mhash.sourceforge.net/"

LICENSE = "LGPLv2.0"
LIC_FILES_CHKSUM = "file://COPYING;md5=3bf50002aefd002f49e7bb854063f7e7"

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

DEBIAN_UNPACK_DIR = "${WORKDIR}/mhash-${PV}.orig"

SECTION = "libs"

SRC_URI += "file://Makefile.test \
    file://mhash.c \
    file://run-ptest \
    "

inherit autotools-brokensep ptest pkgconfig

do_compile_ptest() {
    if [ ! -d ${S}/demo ]; then mkdir ${S}/demo; fi
    cp ${WORKDIR}/Makefile.test ${S}/demo/Makefile
    cp ${WORKDIR}/mhash.c ${S}/demo/
    make -C ${S}/demo CFLAGS="${CFLAGS} -I${S}/include/" LDFLAGS="${LDFLAGS} -L${S}/lib/.libs"
}

do_install_ptest() {
    install -m 0755 ${S}/demo/mhash ${D}${PTEST_PATH}
}

repository: meta-debian/meta-debian

repo_name: meta-debian/meta-debian

branch_name: refs/heads/warrior

gha_language: BitBake


text:
SUMMARY = "An IPC library for high performance servers"
DESCRIPTION = "libqb is a library with the primary purpose of providing high performance client server reusable features. \
It provides high performance logging, tracing, ipc, and poll."

HOMEPAGE = "https://github.com/clusterlabs/libqb/wiki"

SECTION = "libs"

inherit autotools pkgconfig

SRC_URI = "https://fedorahosted.org/releases/q/u/quarterback/${BP}.tar.xz \
          "

SRC_URI[md5sum] = "de1e5d38fa449b4d127940c10d117260"
SRC_URI[sha256sum] = "9a419c649ed51f275dc780da8a15babb8a5d33633567bd9e0cb6193b6e21f4fe"

LICENSE = "LGPL-2.1"

LIC_FILES_CHKSUM = "file://COPYING;md5=321bf41f280cf805086dd5a720b37785"

do_configure_prepend() {
    ( cd ${S}
    ${S}/autogen.sh )
}


text:
package server

import (
	"bytes"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"
	"github.com/go-chi/cors"
	"github.com/go-chi/render"
	"github.com/hashicorp/go-hclog"
	"github.com/leonardochaia/vendopunkto/internal/conf"
	"github.com/leonardochaia/vendopunkto/internal/store"
)

// VendoPunktoRouter is the public routerplugin
type VendoPunktoRouter interface {
	chi.Router
}

// NewRouter Creates the chi Router and configures global paths
func NewRouter(
	invoices *InvoiceHandler,
	globalLogger hclog.Logger,
	txBuilder store.TransactionBuilder,
	startupConf conf.Startup,
) (*VendoPunktoRouter, error) {

	var router VendoPunktoRouter
	router = chi.NewRouter()

	logger := globalLogger.Named("api-server")

	// add basic middlewares
	setupMiddlewares(router, startupConf, logger)

	// tx per request
	router.Use(store.NewTxPerRequestMiddleware(globalLogger, txBuilder))

	// versions
	router.Route("/api/v1", func(r chi.Router) {
		r.Get("/info", GetVersion())
		r.Mount("/invoices", invoices.Routes())
	})

	serveSPA(router, "/", "spa/dist/vendopunkto")

	// Enable profiler
	if startupConf.Server.ProfilerEnabled && startupConf.Server.ProfilerPath != "" {
		logger.Debug("Profiler enabled on API", "path", startupConf.Server.ProfilerPath)
		router.Mount(startupConf.Server.ProfilerPath, middleware.Profiler())
	}

	return &router, nil
}

func setupMiddlewares(
	router chi.Router,
	startupConf conf.Startup,
	logger hclog.Logger) {
	router.Use(middleware.RequestID)
	router.Use(middleware.RealIP)
	router.Use(middleware.Recoverer)
	router.Use(render.SetContentType(render.ContentTypeJSON))
	router.Use(middleware.GetHead)

	// Log Requests
	if startupConf.Server.LogRequests {
		router.Use(newRequestLogger(logger))
	}

	// CORS Config
	router.Use(cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{
			http.MethodHead, http.MethodOptions,
			http.MethodGet, http.MethodPost, http.MethodPut,
			http.MethodDelete, http.MethodPatch,
		},
		AllowedHeaders:   []string{"*"},
		AllowCredentials: true,
		MaxAge:           300,
	}).Handler)

}
func newRequestLogger(parentLogger hclog.Logger) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			var requestID string
			if reqID := r.Context().Value(middleware.RequestIDKey); reqID != nil {
				requestID = reqID.(string)
			}

			ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)

			responseBuffer := new(bytes.Buffer)
			ww.Tee(responseBuffer)
			next.ServeHTTP(ww, r)

			latency := time.Since(start)
			logger := parentLogger.Named("request").With(
				"status", ww.Status(),
				"duration", latency.String(),
				"remote", r.RemoteAddr,
				"url", r.RequestURI,
				"method", r.Method,
				"requestID", requestID)

			if ww.Status() >= 500 {
				logger.Error("Request errored",
					"response", responseBuffer.String())
			} else if ww.Status() >= 400 {
				logger.Warn("Bad request",
					"response", responseBuffer.String())
			} else if ww.Status() >= 200 {
				logger.Info("Request succees")
			}
		})
	}

}

// serveSPA is serving static files
func serveSPA(r chi.Router, public string, static string) {

	if strings.ContainsAny(public, "{}*") {
		panic("FileServer does not permit URL parameters.")
	}

	root, _ := filepath.Abs(static)
	if _, err := os.Stat(root); os.IsNotExist(err) {
		panic("Static Documents Directory Not Found")
	}

	fs := http.StripPrefix(public, http.FileServer(http.Dir(root)))

	if public != "/" && public[len(public)-1] != '/' {
		r.Get(public, http.RedirectHandler(public+"/", 301).ServeHTTP)
		public += "/"
	}

	r.Get(public+"*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		file := strings.Replace(r.RequestURI, public, "/", 1)
		if _, err := os.Stat(root + file); os.IsNotExist(err) {
			http.ServeFile(w, r, path.Join(root, "index.html"))
			return
		}
		fs.ServeHTTP(w, r)
	}))
}

repository: leonardochaia/vendopunkto

repo_name: leonardochaia/vendopunkto

gha_language: Go


text:
DESCRIPTION = "Icon theme from the Elementary project"
SECTION = "x11/icons"
HOMEPAGE = "http://www.elementary-project.com/"

inherit gtk-icon-cache

# We have to get the icons from a mirror (LaunchPad) as DeviantArt has a download
# wrapper to stop simple HTTP gets :(.

SRC_URI = " \
  http://launchpad.net/elementaryicons/2.0/2.3/+download/elementary-monochrome.tar.gz;name=mono;subdir=${BPN}-${PV} \
  http://launchpad.net/elementaryicons/2.0/2.3/+download/elementary.tar.gz;name=regular;subdir=${BPN}-${PV} \
"

SRC_URI[mono.md5sum] = "986a2475e9953450b37912d154bb325d"
SRC_URI[mono.sha256sum] = "da461bd70b2fda633f26aa7495e1efc5d97815661799566f0a8accaea411272f"

SRC_URI[regular.md5sum] = "674a88984f55170c17298863f72dd34d"
SRC_URI[regular.sha256sum] = "f7cacfd0e4d3c9ea1c84b29a4f2c75fa1066d6c7f9b41ca0b96ae033c23992a6"

do_install() {
	install -d ${D}${datadir}/icons/elementary/
	install -d ${D}${datadir}/icons/elementary-monochrome/

	cp -R ${S}/elementary/* ${D}${datadir}/icons/elementary/
	cp -R ${S}/elementary-monochrome/* ${D}${datadir}/icons/elementary-monochrome/
}

FILES_${PN} = "${datadir}/icons/elementary*"
RDEPENDS_${PN} += "gnome-icon-theme"
PACKAGE_ARCH = "all"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
DESCRIPTION = "The Zapping VBI library, in short ZVBI, provides functions to \
capture and decode VBI data. It is written in plain ANSI C with few dependencies \
on other tools and libraries."
HOMEPAGE = "http://zapping.sourceforge.net/ZVBI/index.html"
LICENSE = "GPL"
SECTION = "libs/multimedia"
DEPENDS = "libpng"
PR = "r1"

SRC_URI = "${SOURCEFORGE_MIRROR}/zapping/zvbi-${PV}.tar.bz2"
S = "${WORKDIR}/zvbi-${PV}"

inherit autotools pkgconfig

SRC_URI[md5sum] = "a01cbe39a48579ba92582ff75a5e37c2"
SRC_URI[sha256sum] = "a832819915838b364dd19f7f5d8d632b7d0493d8a19e2d011f9b5a3f2e8cf266"


text:
package cli

import (
	"context"
	"fmt"
	"io"
	"math"
	"time"

	"github.com/google/go-github/v31/github"
	"golang.org/x/oauth2"
)

type CLI struct {
	username             string
	token                string
	day                  int
	showDetails          int
	client               *github.Client
	context              context.Context
	accountTotalChannel  chan int
	accountUniqueChannel chan int
	repoChannel          chan *github.Repository
	haltChannel          chan int
}

func New(token string) CLI {
	cli := CLI{
		username:    "",
		token:       "",
		day:         0,
		showDetails: 1,
	}

	cli.SetToken(token)

	cli.context = context.Background()
	tokenSource := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: cli.token},
	)

	tokenClient := oauth2.NewClient(cli.context, tokenSource)

	cli.client = github.NewClient(tokenClient)
	cli.accountTotalChannel = make(chan int)
	cli.accountUniqueChannel = make(chan int)
	cli.repoChannel = make(chan *github.Repository)
	cli.haltChannel = make(chan int)

	return cli
}

func (cli *CLI) SetToken(token string) {
	cli.token = token
}

func (cli *CLI) SetDay(day int) {
	cli.day = day
}

func (cli *CLI) ShowDetails(showDetails int) {
	cli.showDetails = showDetails
}

func (cli *CLI) Initialize() bool {
	user, _, err := cli.client.Users.Get(cli.context, "")
	if err != nil {
		fmt.Println("GitHub API authentication failed. Token may be invalid.", cli.token)
		return false
	}

	cli.username = string(user.GetLogin())
	return true
}

func (cli *CLI) GetRepos() []*github.Repository {
	opts := new(github.RepositoryListOptions)
	opts.PerPage = 1000
	opts.Page = 1
	// list all repositories for the authenticated user
	repos, _, err := cli.client.Repositories.List(cli.context, cli.username, opts)

	if err != nil {
		fmt.Println("Cannot fetch repositories from GitHub. Error message:", err)
		return []*github.Repository{}
	}

	if len(repos) == 0 {
		fmt.Println("User has no repositories")
		return []*github.Repository{}
	}

	return repos
}

func (cli *CLI) RepoStat(w io.Writer) {
	for repo := range cli.repoChannel {
		if cli.showDetails == 1 {
			fmt.Print(".")
		}

		stats, _, _ := cli.client.Repositories.ListTrafficViews(cli.context, cli.username, repo.GetName(), nil)

		viewCount := 0
		uniqueCount := 0
		dayDiff := int(math.Abs(float64(cli.day))) + 1

		for _, view := range stats.Views {
			if view.GetTimestamp().After(time.Now().UTC().AddDate(0, 0, -dayDiff)) {
				uniqueCount += view.GetUniques()
				viewCount += view.GetCount()
			}
		}

		if cli.showDetails == 1 {
			fmt.Fprintf(w, "%s\t%d\t%d\t\n", repo.GetFullName(), viewCount, uniqueCount)
		}

		cli.accountTotalChannel <- viewCount
		cli.accountUniqueChannel <- uniqueCount
	}

	cli.haltChannel <- 1
}

func (cli *CLI) Execute(w io.Writer) {
	fmt.Print("Checking repositories ")

	repos := cli.GetRepos()
	repoCount := len(repos)

	cli.accountTotalChannel = make(chan int, repoCount)
	cli.accountUniqueChannel = make(chan int, repoCount)

	if cli.showDetails == 1 {
		fmt.Fprintf(w, "Repository\tTotal View\tUnique View\t\n")
	}

	for i := 0; i < repoCount; i++ {
		go cli.RepoStat(w)
	}

	for _, repo := range repos {
		cli.repoChannel <- repo
	}

	close(cli.repoChannel)

	cli.Finiliaze(w, repoCount)
}

func (cli *CLI) Finiliaze(
	w io.Writer,
	repoCount int) {

	finishedCount := 0
	for finished := range cli.haltChannel {
		finishedCount = finishedCount + finished

		if finishedCount == repoCount {
			close(cli.haltChannel)
			close(cli.accountTotalChannel)
			close(cli.accountUniqueChannel)
			fmt.Println(".")
			fmt.Println("")
		}
	}

	total := 0
	for t := range cli.accountTotalChannel {
		total += t
	}

	unique := 0
	for u := range cli.accountUniqueChannel {
		unique += u
	}

	fmt.Fprintln(w, "")
	fmt.Fprintln(w, "Total View:", total, ", Unique View:", unique)
}

repository: umutphp/github-stats

repo_name: umutphp/github-stats


text:
package tenvis

import (
	"context"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes/empty"
	"github.com/xdarksome/scp"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type messageChannel struct {
	initial  chan []*SCPMessage
	messages chan *SCPMessage
	done     chan struct{}
}

func (s *messageChannel) Done() {
	s.done <- struct{}{}
}

func newMessageChannel() messageChannel {
	return messageChannel{
		make(chan []*SCPMessage, 1),
		make(chan *SCPMessage, 100),
		make(chan struct{}),
	}
}

type Broadcaster struct {
	key     PrivateKey
	storage Storage

	input  chan *scp.Message
	output map[chan struct{}]messageChannel
	buffer []*SCPMessage
	queue  chan messageChannel
}

func NewBroadcaster(key PrivateKey, storage Storage) *Broadcaster {
	return &Broadcaster{
		key:     key,
		storage: storage,
		input:   make(chan *scp.Message, 1000000),
		output:  make(map[chan struct{}]messageChannel),
		queue:   make(chan messageChannel),
	}
}

func (b *Broadcaster) broadcast(m *SCPMessage) {
	message := &SCPMessage{
		Type:      SCPMessage_Type(m.Type),
		SlotIndex: m.SlotIndex,
		Counter:   m.Counter,
		Value:     m.Value,
	}

	for done, ch := range b.output {
		select {
		case <-done:
			delete(b.output, done)
		default:
			ch.messages <- message
		}
	}
}

func (b *Broadcaster) appendBuffer(m *SCPMessage) {
	if b.buffer == nil || b.buffer[len(b.buffer)-1].SlotIndex != m.SlotIndex {
		b.buffer = []*SCPMessage{m}
		return
	}

	b.buffer = append(b.buffer, m)
}

func (b *Broadcaster) run() {
	for {
		select {
		case m := <-b.input:
			message := &SCPMessage{
				Type:      SCPMessage_Type(m.Type),
				SlotIndex: m.SlotIndex,
				Counter:   m.Counter,
				Value:     m.Value,
			}
			b.appendBuffer(message)
			b.broadcast(message)
		case ch := <-b.queue:
			b.output[ch.done] = ch
			ch.initial <- b.buffer
		}
	}
}

func (b *Broadcaster) newStream() messageChannel {
	s := newMessageChannel()
	b.queue <- s
	return s
}

func (b *Broadcaster) sendMessages(stream Tenvis_StreamSCPMessagesServer, messages ...*SCPMessage) error {
	m := &SCPMessages{
		List: messages,
	}

	bytes, err := proto.Marshal(m)
	if err != nil {
		return status.Error(codes.Internal, "failed to proto marshal output")
	}

	m.Signature = b.key.Sign(bytes)
	if err := stream.Send(m); err != nil {
		return status.Error(codes.Internal, "failed to send output")
	}

	return nil
}

func (b *Broadcaster) StreamSCPMessages(req *empty.Empty, stream Tenvis_StreamSCPMessagesServer) error {
	ch := b.newStream()
	defer ch.Done()

	init := <-ch.initial
	if init != nil {
		if err := b.sendMessages(stream, init...); err != nil {
			return err
		}
	}

	for {
		m := <-ch.messages
		if err := b.sendMessages(stream, m); err != nil {
			return err
		}
	}
}

func (b *Broadcaster) GetLedger(ctx context.Context, req *GetLedgerRequest) (*LedgerMessage, error) {
	ledger, err := b.storage.GetLedger(req.Index)
	if err != nil {
		return new(LedgerMessage), status.Error(codes.Internal, "failed to get ledger from redis")
	}

	if ledger == nil {
		return new(LedgerMessage), status.Error(codes.NotFound, "ledger not found")
	}

	message := &LedgerMessage{
		Ledger: ledger,
	}

	bytes, err := proto.Marshal(message)
	if err != nil {
		return new(LedgerMessage), status.Error(codes.Internal, "failed to proto marshal")
	}
	message.Signature = b.key.Sign(bytes)

	return message, nil
}

repository: xDarksome/tenvis

repo_name: xDarksome/tenvis


text:
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/asvvvad/clap/clap"
	"github.com/atotto/clipboard"
)

func main() {
	var file string
	var stdin bool
	var print bool

	flag.StringVar(&file, "file", "", "Use text from file")
	flag.BoolVar(&stdin, "stdin", false, "Use text from stdin")
	flag.BoolVar(&print, "print", false, "Print result.")

	flag.Usage = func() {
		fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
		fmt.Println("\n  Copy the text you want to tilde then run tildeit and paste the result")
		fmt.Println("\n  Options:")
		fmt.Println("  -------")
		flag.PrintDefaults()
		fmt.Println("\n~t~i~l~d~e~i~t~ by tilde.club/~asvvvad - github.com/asvvvad/tildeit")
	}

	flag.Parse()

	// The string that will contain the input text
	var text string
	var err error
	var bytes []byte

	if stdin {
		bytes, err = ioutil.ReadAll(os.Stdin)
		text = string(bytes)
	} else if file != "" {
		bytes, err = ioutil.ReadFile(file)
		text = string(bytes)
	} else {
		text, err = clipboard.ReadAll()
	}

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// The string that will contain the final result
	result := "~" + clap.Emoji(text, "~") + "~"

	if print {
		fmt.Println(result)
	} else {
		err := clipboard.WriteAll(result)
		if err != nil {
			fmt.Println(err)
			// Print out in case of unsupported system
			fmt.Println(result)
			os.Exit(1)
		}
		fmt.Println("~tilde'd~and~copied~")
	}
}


text:
@article{Hasan-2021-Putting,
    title = "Putting Table Cartograms into Practice",
    author = "Hasan, Mohammad Rakib  and
      Mondal, Debajyoti  and
      Tasnim, Jarin  and
      Schneider, Kevin A.",
    journal = "Advances in Visual Computing",
    year = "2021",
    publisher = "Springer International Publishing",
    url = "https://aclanthology.org/G21-15001",
    doi = "10.1007/978-3-030-90439-5_8",
    pages = "91--102",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

gha_language: Python


text:
package validator

import (
	"github.com/meshplus/bitxhub/internal/ledger"
	"github.com/meshplus/bitxhub/internal/validator/validatorlib"
	"github.com/sirupsen/logrus"
)

// Validator is the instance that can use wasm to verify transaction validity
type FabV14Validator struct {
	ledger ledger.Ledger
	logger logrus.FieldLogger
}

// New a validator instance
func NewFabV14Validator(ledger ledger.Ledger, logger logrus.FieldLogger) *FabV14Validator {
	return &FabV14Validator{
		ledger: ledger,
		logger: logger,
	}
}

// Verify will check whether the transaction info is valid
func (vlt *FabV14Validator) Verify(address, from string, proof []byte, validators string) (bool, error) {
	vInfo, err := validatorlib.UnmarshalValidatorInfo([]byte(validators))
	if err != nil {
		return false, err
	}
	err = validatorlib.ValidateV14(proof, []byte(vInfo.Policy), vInfo.ConfByte, vInfo.Cid)
	if err != nil {
		return false, err
	}

	return true, nil
}

repository: terasum/bitxhub

repo_name: terasum/bitxhub


text:
@inproceedings{Moustafa13,
  pdf = {http://jmlr.org/proceedings/papers/v29/Moustafa13.pdf},
  title = {Learning a Metric Space for Neighbourhood Topology Estimation: Application to Manifold Learning},
  author = {Moustafa, Karim Abou- and Schuurmans, Dale and Ferrie, Frank},
  pages = {341-356},
  abstract = {Manifold learning algorithms rely on a neighbourhood graph to provide an estimate of the data's local topology. Unfortunately, current methods for estimating local topology assume local Euclidean geometry and locally uniform data density, which often leads to poor data embeddings. We address these shortcomings by proposing a framework that combines local learning with parametric density estimation for local topology estimation. Given a data set $\mathcal{D} \subset \mathcal{X}$, we first estimate a new metric space $(\mathbb{X},d_{\mathbb{X}})$ that characterizes the varying sample density of $\mathcal{X}$ in $\mathbb{X}$, then use $(\mathbb{X},d_{\mathbb{X}})$ as a new (pilot) input space for the graph construction step of the manifold learning process.
The proposed framework results in significantly improved embeddings, which we demonstrated objectively by assessing clustering accuracy.},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX


text:
#======================================#
#           SUMMARY/LICENCE            #
#--------------------------------------#
SUMMARY = "Library for manipulating C and Unicode strings"

HOMEPAGE = "http://www.gnu.org/software/libunistring/"

LICENSE = "LGPLv3+ | GPLv2"
LIC_FILES_CHKSUM = "file://COPYING.LIB;md5=6a6a8e020838b23406c81b19c1d46df6 \
                    file://README;beginline=45;endline=65;md5=08287d16ba8d839faed8d2dc14d7d6a5 \
                    file://doc/libunistring.texi;md5=b86c9fd7acaac623017239640631912c \
                    "

#======================================#
#           REQUIRE/INHERIT            #
#--------------------------------------#
inherit autotools texinfo

#======================================#
#                SOURCE                #
#--------------------------------------#
SRC_URI = "${GNU_MIRROR}/libunistring/libunistring-${PV}.tar.xz;name=source \
           file://iconv-m4-remove-the-test-to-convert-euc-jp.patch          \
           "

SRC_URI[source.md5sum] = "82e0545363d111bfdfec2ddbfe62ffd3"
SRC_URI[source.sha256sum] = "2e3764512aaf2ce598af5a38818c0ea23dedf1ff5460070d1b6cee5c3336e797"

#======================================#
#           DEPENDS/PROVIDES           #
#--------------------------------------#

#======================================#
#         BUILD CONFIGURATIONS         #
#--------------------------------------#

#======================================#
#                TASKS                 #
#--------------------------------------#

#======================================#
#            PACKAGES/FILES            #
#--------------------------------------#

#======================================#
#            INSTALL SCRIPT            #
#--------------------------------------#

#======================================#
#             ALTERNATIVES             #
#--------------------------------------#

#======================================#
#           USERADD/SYSTEMD            #
#--------------------------------------#

#======================================#
#                 TEST                 #
#--------------------------------------#


text:
/*
Copyright 2018 Turbine Labs, Inc.

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 flags

//go:generate mockgen -source $GOFILE -destination mock_$GOFILE -package $GOPACKAGE --write_package_comment=false

import (
	"github.com/turbinelabs/api/client"
	"github.com/turbinelabs/api/service"
	tbnflag "github.com/turbinelabs/nonstdlib/flag"
)

// ClientFromFlags represents command-line flags specifying
// configuration of a service.All backed by the Turbine Labs API.
type ClientFromFlags interface {
	Validate() error

	// Make produces a service.All from the provided flags, or an
	// error.
	Make() (service.All, error)

	// MakeAdmin produces a service.Admin from the provided flags,
	// or an error.
	MakeAdmin() (service.Admin, error)
}

// NewClientFromFlags creates a ServiceFromFlags, which configures the
// necessary flags to construct a service.All instance.
func NewClientFromFlags(clientApp client.App, flagset tbnflag.FlagSet) ClientFromFlags {
	return NewClientFromFlagsWithSharedAPIConfig(clientApp, flagset, nil)
}

// NewClientFromFlagsWithSharedAPIConfig creates a ClientFromFlags,
// which configures the necessary flags to construct a service.All
// instance. The given APIConfigFromFlags is used to obtain the API
// auth key.
func NewClientFromFlagsWithSharedAPIConfig(
	clientApp client.App,
	flagset tbnflag.FlagSet,
	apiConfigFromFlags APIConfigFromFlags,
) ClientFromFlags {
	ff := &clientFromFlags{clientApp: clientApp}

	if apiConfigFromFlags == nil {
		ff.apiConfigFromFlags = NewAPIConfigFromFlags(flagset)
	} else {
		ff.apiConfigFromFlags = apiConfigFromFlags
	}

	return ff
}

type clientFromFlags struct {
	clientApp          client.App
	apiConfigFromFlags APIConfigFromFlags
}

func (ff *clientFromFlags) Validate() error {
	return ff.apiConfigFromFlags.Validate()
}

func (ff *clientFromFlags) Make() (service.All, error) {
	endpoint, err := ff.apiConfigFromFlags.MakeEndpoint()
	if err != nil {
		return nil, err
	}

	apiKey := ff.apiConfigFromFlags.APIKey()

	return client.NewAll(endpoint, apiKey, ff.clientApp)
}

func (ff *clientFromFlags) MakeAdmin() (service.Admin, error) {
	endpoint, err := ff.apiConfigFromFlags.MakeEndpoint()
	if err != nil {
		return nil, err
	}

	apiKey := ff.apiConfigFromFlags.APIKey()

	return client.NewAdmin(endpoint, apiKey, ff.clientApp)
}

repository: turbinelabs/api

repo_name: turbinelabs/api


text:
package goutils

import (
	"bufio"
	"os"
	"strings"
)

// ReadLine read file line by line and calls handler with each line and index.
func ReadLine(filepath string, handler func(line string, index uint64)) error {
	f, err := os.Open(filepath)
	if err != nil {
		return err
	}
	defer f.Close()

	var idx uint64
	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		handler(scanner.Text(), idx)
		idx++
	}

	if err := scanner.Err(); err != nil {
		return err
	}
	return nil
}

// IsFileExists tests existence of specified file.
func IsFileExists(filepath string) bool {
	_, err := os.Stat(filepath)
	if err == nil {
		return true
	}
	return os.IsExist(err)
}

// RemoveTrailingSlash remove the last slash of a path except the root path.
func RemoveTrailingSlash(path string) string {
	if len(path) > 1 && strings.HasSuffix(path, "/") {
		return path[:len(path)-1]
	}
	return path
}

// IsDir tests whether a path is dir or not, true if path is dir, false otherwise.
func IsDir(path string) bool {
	stat, err := os.Stat(path)
	if err != nil {
		return false
	}

	mode := stat.Mode()
	return mode.IsDir()
}

// IsRegular tests whether a path is a regular file.
func IsRegular(path string) bool {
	stat, err := os.Stat(path)
	if err != nil {
		return false
	}

	mode := stat.Mode()
	return mode.IsRegular()
}

repository: gaols/goutils

repo_name: gaols/goutils


text:
require cmake.inc

SRC_URI[md5sum] = "f5dd061c31765a49dc17ae8bdc986779"
SRC_URI[sha256sum] = "f20607d4f33376ea648307681630574662d0c3f59d88a7a02ad547b6320631f1"


text:
package pearl

import (
	"encoding/binary"
	"errors"
)

// Reference: https://github.com/torproject/torspec/blob/master/tor-spec.txt#L501-L541
//
//	4.1. Negotiating versions with VERSIONS cells
//
//	   There are multiple instances of the Tor link connection protocol.  Any
//	   connection negotiated using the "certificates up front" handshake (see
//	   section 2 above) is "version 1".  In any connection where both parties
//	   have behaved as in the "renegotiation" handshake, the link protocol
//	   version must be 2.  In any connection where both parties have behaved
//	   as in the "in-protocol" handshake, the link protocol must be 3 or higher.
//
//	   To determine the version, in any connection where the "renegotiation"
//	   or "in-protocol" handshake was used (that is, where the responder
//	   sent only one certificate at first and where the initiator did not
//	   send any certificates in the first negotiation), both parties MUST
//	   send a VERSIONS cell.  In "renegotiation", they send a VERSIONS cell
//	   right after the renegotiation is finished, before any other cells are
//	   sent.  In "in-protocol", the initiator sends a VERSIONS cell
//	   immediately after the initial TLS handshake, and the responder
//	   replies immediately with a VERSIONS cell.  Parties MUST NOT send any
//	   other cells on a connection until they have received a VERSIONS cell.
//
//	   The payload in a VERSIONS cell is a series of big-endian two-byte
//	   integers.  Both parties MUST select as the link protocol version the
//	   highest number contained both in the VERSIONS cell they sent and in the
//	   versions cell they received.  If they have no such version in common,
//	   they cannot communicate and MUST close the connection.  Either party MUST
//	   close the connection if the versions cell is not well-formed (for example,
//	   if it contains an odd number of bytes).
//
//	   Since the version 1 link protocol does not use the "renegotiation"
//	   handshake, implementations MUST NOT list version 1 in their VERSIONS
//	   cell.  When the "renegotiation" handshake is used, implementations
//	   MUST list only the version 2.  When the "in-protocol" handshake is
//	   used, implementations MUST NOT list any version before 3, and SHOULD
//	   list at least version 3.
//
//	   Link protocols differences are:
//	     1 -- The "certs up front" handshake.
//	     2 -- Uses the renegotiation-based handshake. Introduces
//	          variable-length cells.
//	     3 -- Uses the in-protocol handshake.
//	     4 -- Increases circuit ID width to 4 bytes.
//

// ErrVersionsCellOddLength is returned when we receive a versions cell of odd
// length. This should never happen, because the body should be a list of 16-bit
// integers.
var ErrVersionsCellOddLength = errors.New("versions cell with odd length")

// VersionsCell is a list of supported link protocol versions.
type VersionsCell struct {
	SupportedVersions []LinkProtocolVersion
}

var _ CellBuilder = new(VersionsCell)

// ParseVersionsCell parses a Cell into the list of supported versions.
func ParseVersionsCell(c Cell) (*VersionsCell, error) {
	if c.Command() != CommandVersions {
		return nil, ErrUnexpectedCommand
	}

	payload := c.Payload()
	n := len(payload)

	if (n % 2) != 0 {
		return nil, ErrVersionsCellOddLength
	}

	v := make([]LinkProtocolVersion, n/2)
	for i := 0; i < n; i += 2 {
		v[i/2] = LinkProtocolVersion(binary.BigEndian.Uint16(payload[i : i+2]))
	}

	return &VersionsCell{
		SupportedVersions: v,
	}, nil
}

// Cell builds the cell bytes for the versions cell.
func (v VersionsCell) Cell() (Cell, error) {
	n := uint16(2 * len(v.SupportedVersions))
	c := NewCellEmptyPayload(0, CommandVersions, n)
	payload := c.Payload()
	for i, version := range v.SupportedVersions {
		binary.BigEndian.PutUint16(payload[2*i:2*i+2], uint16(version))
	}
	return NewLegacyCell(c), nil
}

repository: wizadr/pearl

repo_name: wizadr/pearl


text:
@misc{sbr,
  author = {{Acton}, S.},
  title = {{Image Pre-Processor SBR}},
  howpublished = {Private communications},
  year = 2015
}

@inproceedings{Jeschke15A,
        author = {{Jeschke}, E. and {Inagaki}, T. and {Kackley}, R.},
        title  = "Enhancements to {Ginga}: a {Python} Package for Building Astronomical Data Viewers",
        booktitle = "Astronomical Data Analysis Software and Systems XXIV",
        year   = 2015,
        editor = {{Taylor}, A.~R. and {Rosolowsky}, E.},
        publisher = "ASP",
        note   = "Vol. 495" }


text:
@inproceedings{younis_2012,
author = {Mussa, Awad A Younis},
year = {2012},
month = {07},
pages = {},
title = {Relationship between Attack Surface and Vulnerability Density: A Case Study on Apache HTTP Server}
}

@article{jiao_wu_2007,
author = {Jiao, J. and Xu, Z. and Wei, W.},
journal = {IJCSNS International Journal of Computer Science and Network Security},
year = {2007},
month = {02},
pages = {353-359},
title = {Method of Identify OS based on TCP/IP fingerprint},
volume = {3}
}

@INPROCEEDINGS{han_du_2010,
author={X. {Han} and X. {Du}},
booktitle={2010 2nd IEEE International Conference on Information and Financial Engineering},
title={A new method about operating system identification},
year={2010},
volume={},
number={},
pages={882-885},
keywords={authorisation;computer network security;operating systems (computers);transport protocols;operating system identification;firewall;remote host operating system;ARP protocol;TCP/IP protocol stack;host detection;TCP port scanning process;fingerprint storehouse design;operating system detecting process;network security assessment system;Operating systems;Fingerprint recognition;Fires;Protocols;IP networks;Security;Computers;ARP Protocol;Network Security;Operating System Identification;TCP / IP Fingerprint},
doi={10.1109/ICIFE.2010.5609496},
ISSN={null},
month={Sep.},}

@INPROCEEDINGS{li_avellino_janies_collins_2016,
author={X. {Li} and P. {Avellino} and J. {Janies} and M. P. {Collins}},
booktitle={MILCOM 2016 - 2016 IEEE Military Communications Conference},
title={Software asset analyzer: A system for detecting configuration anomalies},
year={2016},
volume={},
number={},
pages={998-1003},
keywords={safety-critical software;security of data;software asset analyzer;configuration anomaly detection;SAA;software patch management;software inventories;software patching efficiency improvement;security patching;vulnerable software installation detection;remediation process verification;Software as a service;Metadata;Monitoring;Computer bugs;Computer security;Attack;Detection and Prevention;Asset Inventory;Anomaly detection;Configuration Management;Incident Response;Intrusion Detection;Threat Monitoring and Analysis},
doi={10.1109/MILCOM.2016.7795460},
ISSN={2155-7586},
month={Nov},}

@misc{dillon_2019,
title={@zerosum0x0: reverse engineering, penetration testing, exploit development},
url={zerosum0x0.blogspot.com},
journal={@zerosum0x0: reverse engineering, penetration testing, exploit development}, author={Dillon, Sean}, year={2019}, month={May}}

@misc{yan_chen_2019, title={Exploitation of Windows CVE-2019-0708 (BlueKeep): Three Ways to Write Data into the Kernel with RDP PDU}, url={https://unit42.paloaltonetworks.com/exploitation-of-windows-cve-2019-0708-bluekeep-three-ways-to-write-data-into-the-kernel-with-rdp-pdu/}, journal={Unit42}, author={Yan, Tao and Chen, Jin}, year={2019}, month={Sep}}

@misc{go_zingbox_com_2019,
title={BlueKeep and Forthcoming RDP Attacks},
author={Zingbox Security Research},
url={http://go.zingbox.com/rs/562-ZPO-907/images/BlueKeep-and-Forthcoming-RDP-Attacks.pdf}, journal={go.zingbox.com},
publisher={Zingbox Security Research}, year={2019}}

@misc{mcafee_rdp_blog,
title={RDP Stands for “Really DO Patch!” – Understanding the Wormable RDP Vulnerability CVE-2019-0708},
author={E. {Caroll} and A. {Mundo} and P. {Laulheret} and C. {Beek} and S. {Povolny}},
url={https://www.mcafee.com/blogs/other-blogs/mcafee-labs/rdp-stands-for-really-do-patch-understanding-the-wormable-rdp-vulnerability-cve-2019-0708/}, journal={mcafee.com/blogs},
publisher={McAfee Labs}, year={2019}}

@article{zain_ankur_derek_log_2014,
author = {Shamsi, Zain and Nandwani, Ankur and Leonard, Derek and Loguinov, Dmitri},
year = {2014},
month = {06},
pages = {},
title = {Hershel: Single-Packet OS Fingerprinting},
volume = {42},
isbn = {978-1-4503-2789-3},
journal = {ACM SIGMETRICS Performance Evaluation Review},
doi = {10.1145/2591971.2591972}
}

@article{penetration_2016,
  title={Penetration Testing and Mitigation of Vulnerabilities Windows Server},
  author={Deris Stiawan and Mohammad Yazid Bin Idris and Abdul Hanan Abdullah and Mohammed AlQurashi and Rahmat Budiarto},
  journal={I. J. Network Security},
  year={2016},
  volume={18},
  pages={501-513}
}


text:
DESCRIPTION = "Tool to sign omap3 x-loader images"

LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://${COREBASE}/LICENSE;md5=3f40d7994397109285ec7b81fdeb3b58"

PR = "r1"

SRC_URI = "file://signGP.c"

do_compile() {
	${CC} ${CFLAGS} ${LDFLAGS} ${WORKDIR}/signGP.c -o signGP
}

do_install() {
	install -d ${D}${bindir}
	install -m 0755 signGP ${D}${bindir}
}

NATIVE_INSTALL_WORKS = "1"

BBCLASSEXTEND = "native"

repository: DougBarry/meta-openpandora

repo_name: DougBarry/meta-openpandora


text:
package main

import (
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/nlopes/slack"
	"github.com/yuin/gopher-lua"
	"layeh.com/gopher-luar"
)

const slackChatClientTypeName = "slackChatClient"
const slackDefaultConfigLua = `  myname = "golbot"
  myid   = "U1XXXXXX"
  local bot = golbot.newbot("Slack", {
    token = "",
    log = {"seelog", type="adaptive", mininterval="200000000", maxinterval="1000000000", critmsgcount="5",
      {"formats",
        {"format", id="main", format="%Date(2006-01-02 15:04:05) [%Level] %Msg"},
      },
      {"outputs", formatid="main",
        {"filter", levels="trace,debug,info,warn,error,critical",
          {"console"}
        },
      }
    }
  })

  bot:on("message", function(e)
    local ch = e.channel
    local user = e.user
    local msg = e.text

    if e.sub_type == "" and user ~= myid then
      msglog:printf("%s\t%s\t%s", ch, user, msg)
      bot:say(ch, msg)
      goworker({channel=ch, message=msg, nick=nick})
	end
  end)
`

type slackChatClient struct {
	slackobj       *slack.Client
	rtm            *slack.RTM
	commonOption   *CommonClientOption
	logger         *log.Logger
	userId         string
	startedAt      float64
	callbacks      map[string][]*lua.LFunction
	userId2Name    map[string]string
	userName2Id    map[string]string
	channelId2Name map[string]string
	channelName2Id map[string]string
}

func (client *slackChatClient) toSlackChannelId(v string) string {
	if ok, _ := regexp.MatchString(`[CU][0-9].*`, v); ok {
		return v
	}
	if strings.HasPrefix(v, "#") {
		if v, ok := client.channelName2Id[v[1:]]; ok {
			return v
		}
	}
	if v, ok := client.userName2Id[v]; ok {
		return v
	}
	return v
}

func (client *slackChatClient) applyCallback(L *lua.LState, msg *slack.RTMEvent) {
	mutex.Lock()
	defer mutex.Unlock()
	v, ok := client.callbacks[msg.Type]
	if !ok {
		return
	}
	for _, callback := range v {
		if e, ok := msg.Data.(*slack.MessageEvent); ok {
			f, _ := strconv.ParseFloat(e.Timestamp, 64)
			if (f - client.startedAt) < 3 {
				return
			}
		}
		pushN(L, callback, luar.New(L, msg.Data))
		if err := L.PCall(1, 0, nil); err != nil {
			client.logger.Printf("[Error] %s", err.Error())
		}
	}
}

func (client *slackChatClient) Logger() *log.Logger {
	return client.logger
}

func (client *slackChatClient) CommonOption() *CommonClientOption {
	return client.commonOption
}

func (client *slackChatClient) Say(target, message string) {
	client.rtm.SendMessage(client.rtm.NewOutgoingMessage(message, client.toSlackChannelId(target)))
}

func (client *slackChatClient) On(L *lua.LState, typ string, callback *lua.LFunction) {
	mutex.Lock()
	defer mutex.Unlock()
	v, ok := client.callbacks[typ]
	if !ok {
		v = []*lua.LFunction{}
		client.callbacks[typ] = v
	}
	client.callbacks[typ] = append(v, callback)
}

func (client *slackChatClient) Respond(L *lua.LState, pattern *regexp.Regexp, fn *lua.LFunction) {
	client.On(L, "message", L.NewFunction(func(L *lua.LState) int {
		e := L.CheckUserData(1).Value.(*slack.MessageEvent)
		matches := pattern.FindAllStringSubmatch(e.Text, -1)
		mentionMe, _ := regexp.MatchString("<@"+client.userId+"[^>]*>", e.Text)
		if (e.SubType == "me_message" || len(e.SubType) == 0) && len(matches) != 0 && mentionMe {
			user := client.userId2Name[e.User]
			channel := "#" + client.channelId2Name[e.Channel]
			pushN(L, fn, luar.New(L, matches[0]), luar.New(L, NewMessageEvent(user, channel, e.Text, e)))
			if err := L.PCall(2, 0, nil); err != nil {
				client.logger.Printf("[ERROR] %s", err.Error())
			}
		}
		return 0
	}))
}

func (client *slackChatClient) Serve(L *lua.LState, fn *lua.LFunction) {
	rtm := client.rtm
	client.startedAt = float64(time.Now().Unix())
	go rtm.ManageConnection()

	for {
		select {
		case msg := <-rtm.IncomingEvents:
			client.applyCallback(L, &msg)
			switch ev := msg.Data.(type) {
			case *slack.ChannelCreatedEvent:
				client.logger.Printf("[Info] Channel created : %s(ID:%s)", ev.Channel.Name, ev.Channel.ID)
				client.channelName2Id[ev.Channel.Name] = ev.Channel.ID
				client.channelId2Name[ev.Channel.ID] = ev.Channel.Name
			case *slack.ChannelRenameEvent:
				client.logger.Printf("[Info] Channel renamed: ID:%s %s -> %s", ev.Channel.ID, client.channelId2Name[ev.Channel.ID], ev.Channel.Name)
				delete(client.channelName2Id, client.channelId2Name[ev.Channel.ID])
				client.channelName2Id[ev.Channel.Name] = ev.Channel.ID
			case *slack.ChannelDeletedEvent:
				client.logger.Printf("[Info] Channel deleted: %s(ID:%s)", client.channelId2Name[ev.Channel], ev.Channel)
				delete(client.channelName2Id, client.channelId2Name[ev.Channel])
				delete(client.channelId2Name, ev.Channel)

			case *slack.ConnectedEvent:
				channels := []string{}
				client.userId = ev.Info.User.ID
				for _, c := range ev.Info.Channels {
					client.channelName2Id[c.Name] = c.ID
					client.channelId2Name[c.ID] = c.Name
					channels = append(channels, c.Name)
				}
				for _, u := range ev.Info.Users {
					client.userName2Id[u.Name] = u.ID
					client.userId2Name[u.ID] = u.Name
				}
				client.logger.Printf("[Info] Connected to %s(channels:%s)", ev.Info.Team.Domain, strings.Join(channels, ","))
				client.logger.Printf("[Info] My name is %s(ID:%s)", ev.Info.User.Name, client.userId)
			default:
				// Ignore other events..
			}
		case msg := <-luaMainChan:
			func() {
				mutex.Lock()
				defer mutex.Unlock()
				pushN(L, fn, msg)
				L.PCall(1, 0, nil)
			}()
		}
	}
}

func registerSlackChatClientType(L *lua.LState) {
	registerChatClientType(L, slackChatClientTypeName)
}

func newSlackChatClient(L *lua.LState, co *CommonClientOption, opt *lua.LTable) {
	token, ok := getStringField(L, opt, "token")
	if !ok {
		L.RaiseError("'token' is required")
	}

	slackobj := slack.New(token)
	chatClient := &slackChatClient{slackobj, nil, co, co.Logger, "", 0, make(map[string][]*lua.LFunction), make(map[string]string), make(map[string]string), make(map[string]string), make(map[string]string)}

	if co.Logger == nil {
		slack.SetLogger(log.New(os.Stdout, "", log.Lshortfile|log.LstdFlags))
	} else {
		slack.SetLogger(co.Logger)
	}

	chatClient.rtm = chatClient.slackobj.NewRTM()
	L.Push(newChatClient(L, slackChatClientTypeName, chatClient, luar.New(L, chatClient.rtm).(*lua.LUserData)))
}

var eventMapping = map[string]interface{}{ // {{{
	"message":         slack.MessageEvent{},
	"presence_change": slack.PresenceChangeEvent{},
	"user_typing":     slack.UserTypingEvent{},

	"channel_marked":          slack.ChannelMarkedEvent{},
	"channel_created":         slack.ChannelCreatedEvent{},
	"channel_joined":          slack.ChannelJoinedEvent{},
	"channel_left":            slack.ChannelLeftEvent{},
	"channel_deleted":         slack.ChannelDeletedEvent{},
	"channel_rename":          slack.ChannelRenameEvent{},
	"channel_archive":         slack.ChannelArchiveEvent{},
	"channel_unarchive":       slack.ChannelUnarchiveEvent{},
	"channel_history_changed": slack.ChannelHistoryChangedEvent{},

	"dnd_updated":      slack.DNDUpdatedEvent{},
	"dnd_updated_user": slack.DNDUpdatedEvent{},

	"im_created":         slack.IMCreatedEvent{},
	"im_open":            slack.IMOpenEvent{},
	"im_close":           slack.IMCloseEvent{},
	"im_marked":          slack.IMMarkedEvent{},
	"im_history_changed": slack.IMHistoryChangedEvent{},

	"group_marked":          slack.GroupMarkedEvent{},
	"group_open":            slack.GroupOpenEvent{},
	"group_joined":          slack.GroupJoinedEvent{},
	"group_left":            slack.GroupLeftEvent{},
	"group_close":           slack.GroupCloseEvent{},
	"group_rename":          slack.GroupRenameEvent{},
	"group_archive":         slack.GroupArchiveEvent{},
	"group_unarchive":       slack.GroupUnarchiveEvent{},
	"group_history_changed": slack.GroupHistoryChangedEvent{},

	"file_created":         slack.FileCreatedEvent{},
	"file_shared":          slack.FileSharedEvent{},
	"file_unshared":        slack.FileUnsharedEvent{},
	"file_public":          slack.FilePublicEvent{},
	"file_private":         slack.FilePrivateEvent{},
	"file_change":          slack.FileChangeEvent{},
	"file_deleted":         slack.FileDeletedEvent{},
	"file_comment_added":   slack.FileCommentAddedEvent{},
	"file_comment_edited":  slack.FileCommentEditedEvent{},
	"file_comment_deleted": slack.FileCommentDeletedEvent{},

	"pin_added":   slack.PinAddedEvent{},
	"pin_removed": slack.PinRemovedEvent{},

	"star_added":   slack.StarAddedEvent{},
	"star_removed": slack.StarRemovedEvent{},

	"reaction_added":   slack.ReactionAddedEvent{},
	"reaction_removed": slack.ReactionRemovedEvent{},

	"pref_change": slack.PrefChangeEvent{},

	"team_join":              slack.TeamJoinEvent{},
	"team_rename":            slack.TeamRenameEvent{},
	"team_pref_change":       slack.TeamPrefChangeEvent{},
	"team_domain_change":     slack.TeamDomainChangeEvent{},
	"team_migration_started": slack.TeamMigrationStartedEvent{},

	"manual_presence_change": slack.ManualPresenceChangeEvent{},

	"user_change": slack.UserChangeEvent{},

	"emoji_changed": slack.EmojiChangedEvent{},

	"commands_changed": slack.CommandsChangedEvent{},

	"email_domain_changed": slack.EmailDomainChangedEvent{},

	"bot_added":   slack.BotAddedEvent{},
	"bot_changed": slack.BotChangedEvent{},

	"accounts_changed": slack.AccountsChangedEvent{},

	"reconnect_url": slack.ReconnectUrlEvent{},
} // }}}

repository: yuin/golbot

repo_name: yuin/golbot


text:
package webservice

import (
	"errors"
	"fmt"
	"time"

	"github.com/Luoxin/Eutamias/utils"
	"github.com/Luoxin/Eutamias/utils/json"

	"github.com/elliotchance/pie/pie"
	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/session"
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"

	"github.com/Luoxin/Eutamias/conf"
	"github.com/Luoxin/Eutamias/db"
	"github.com/Luoxin/Eutamias/domain"
	"github.com/Luoxin/Eutamias/proxynode"
	"github.com/Luoxin/Eutamias/tohru"
	"github.com/Luoxin/Eutamias/version"
)

var validate = validator.New()
var store *session.Store

const (
	SessionKeyUid     = "Uid"
	SessionKeyUserKey = "UserKey"
	SessionKeyUserIp  = "UserIp"
)

const slt = ".\";v&vm6vOyrS)Ew@ByjN1Er|=<9B~=PniQM4C4Ca=2V@%ZadNP\\Vd:I^}\\["

func genPassword(key, pwd string) string {
	return utils.Md5(fmt.Sprintf("%s_%s_%s", key, slt, pwd))
}

func getReq(c *fiber.Ctx, req interface{}) error {
	err := c.BodyParser(&req)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	err = validate.Struct(req)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	return nil
}

func Registration(c *fiber.Ctx) error {
	var req tohru.RegistrationReq
	var rsp tohru.RegistrationRsp

	err := getReq(c, &req)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	var tohruFeed domain.TohruFeed
	err = db.Db.Where("user_id = ?", req.TohruKey).First(&tohruFeed).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {

		} else {
			log.Errorf("err:%v", err)
			return err
		}
	} else {
		return errors.New("tohru is already exist")
	}

	tohruFeed = domain.TohruFeed{
		UserId:       req.TohruKey,
		UserPassword: genPassword(req.TohruKey, req.TohruPassword),
		LastIp:       utils.GetRealIpFromCtx(c),
	}

	log.Info(genPassword(req.TohruKey, req.TohruPassword))

	err = db.Db.Create(&tohruFeed).Error
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	return c.JSON(rsp)
}

func ChangePassword(c *fiber.Ctx) error {
	var req tohru.ChangePasswordReq
	var rsp tohru.ChangePasswordRsp

	err := getReq(c, &req)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	var tohruFeed domain.TohruFeed
	err = db.Db.Where("user_id = ?", req.TohruKey).First(&tohruFeed).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			log.Error("user not found")
			return c.SendStatus(403)
		}
		log.Errorf("err:%v", err)
		return err
	}

	log.Info(genPassword(req.TohruKey, req.OldTohruPassword))

	if tohruFeed.UserPassword != genPassword(req.TohruKey, req.OldTohruPassword) {
		log.Error("password is fail")
		return c.SendStatus(403)
	}

	if req.NewTohruPassword != req.OldTohruPassword {
		err = db.Db.Model(&tohruFeed).Where("id = ?", tohruFeed.Id).
			Updates(map[string]interface{}{
				"user_password": genPassword(req.TohruKey, req.NewTohruPassword),
			}).Error
		if err != nil {
			log.Errorf("err:%v", err)
			return err
		}
	}

	return c.JSON(rsp)
}

func CheckUsable(c *fiber.Ctx) error {
	var req tohru.CheckUsableReq
	var rsp tohru.CheckUsableRsp

	err := getReq(c, &req)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	hello, err := conf.Ecc.ECCDecrypt(req.Hello)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	var userInfo tohru.UserInfo
	err = json.Unmarshal([]byte(hello), &userInfo)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	if userInfo.Hello != tohru.Hello {
		log.Error("hello not match")
		return c.SendStatus(403)
	}

	var tohruFeed domain.TohruFeed
	err = db.Db.Where("user_id = ?", userInfo.TohruKey).First(&tohruFeed).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			log.Error("user not found")
			return c.SendStatus(403)
		}
		log.Errorf("err:%v", err)
		return err
	}

	log.Info(genPassword(userInfo.TohruKey, userInfo.TohruPassword))

	if tohruFeed.UserPassword != genPassword(userInfo.TohruKey, userInfo.TohruPassword) {
		log.Error("password is fail")
		return c.SendStatus(403)
	}

	log.Infof("%v last ip is %v", userInfo.TohruKey, utils.GetRealIpFromCtx(c))

	if tohruFeed.LastIp != utils.GetRealIpFromCtx(c) {
		err = db.Db.Model(&domain.TohruFeed{}).
			Where("id = ?", tohruFeed.Id).
			Updates(map[string]interface{}{
				"last_ip": utils.GetRealIpFromCtx(c),
			}).Error
		if err != nil {
			log.Errorf("err:%v", err)
			return err
		}
	}

	sess, err := store.Get(c)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	err = sess.Regenerate()
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	rsp.Token = sess.ID()

	err = sess.Destroy()
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	sess.Set(SessionKeyUid, tohruFeed.Id)
	sess.Set(SessionKeyUserKey, userInfo.TohruKey)
	sess.Set(SessionKeyUserIp, utils.GetRealIpFromCtx(c))
	sess.Set(tohru.TokenKey, rsp.Token)
	sess.SetExpiry(time.Hour)

	// save session
	err = sess.Save()
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	rsp.Version = version.Version
	return c.JSON(rsp)
}

func SyncNode(c *fiber.Ctx) error {
	var req tohru.SyncNodeReq
	var rsp tohru.SyncNodeRsp

	err := getReq(c, &req)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	b, err := conf.Ecc.ECCDecrypt(req.NodeList)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	var nodeUrlList pie.Strings
	err = json.Unmarshal([]byte(b), &nodeUrlList)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	var contribution int
	nodeUrlList.Each(func(s string) {
		isNew, err := proxynode.AddNodeWithUrl(s)
		if err != nil {
			log.Errorf("err:%v", err)
			return
		}

		if isNew {
			contribution++
		}
	})

	if contribution > 0 {
		log.Info(contribution)
		sess, err := store.Get(c)
		if err != nil {
			log.Errorf("err:%v", err)
			return err
		}

		err = db.Db.Model(&domain.TohruFeed{}).
			Where("id = ?", sess.Get(SessionKeyUid)).
			Updates(map[string]interface{}{
				"up_count": gorm.Expr("up_count + ?", contribution),
			}).Error
		if err != nil {
			log.Errorf("err:%v", err)
			return err
		}
	}

	rsp.NodeList, err = proxynode.GetNode4Tohru(10 + contribution)
	if err != nil {
		log.Errorf("err:%v", err)
		return err
	}

	return c.JSON(rsp)
}

func registerTohru(app fiber.Router) error {
	app.Use("/", func(c *fiber.Ctx) error {
		var whiteList = pie.Strings{
			"/tohru/CheckUsable",
			"/tohru/Registration",
			"/tohru/ChangePassword",
		}

		path := c.Path()

		if whiteList.Any(func(value string) bool {
			return value == path
		}) {
			return c.Next()
		}

		sess, err := store.Get(c)
		if err != nil {
			log.Errorf("err:%v", err)
			return err
		}

		if sess.Get(SessionKeyUserIp) != utils.GetRealIpFromCtx(c) {
			return c.SendStatus(403)
		}

		return c.Next()
	})

	app.Use("/Registration", basicauth.New(basicauth.Config{
		Users: map[string]string{
			"admin": "admin",
		},
		Authorizer: func(user, pass string) bool {
			if user == "admin" && pass == "admin" {
				return true
			}
			return false
		},
	}))

	app.Post("/ChangePassword", ChangePassword)
	app.Post("/Registration", Registration)

	app.Post("/CheckUsable", CheckUsable)
	app.Post("/SyncNode", SyncNode)

	return nil
}


text:
SUMMARY = "org.openbmc.control.Host implementation for OpenPOWER"
DESCRIPTION = "A host control implementation suitable for OpenPOWER systems."
PROVIDES += "virtual/obmc-host-ctl"
PV = "1.0+git${SRCPV}"
PR = "r1"

SKELETON_DIR = "op-hostctl"
SYSTEMD_SERVICE:${PN} = " \
        op-start-host@.service \
        "
START_TMPL = "op-start-host@.service"
START_TGTFMT = "obmc-host-startmin@{1}.target"
START_INSTFMT = "op-start-host@{0}.service"
START_FMT = "../${START_TMPL}:${START_TGTFMT}.requires/${START_INSTFMT}"
SYSTEMD_LINK:${PN} += "${@compose_list_zip(d, 'START_FMT', 'OBMC_HOST_INSTANCES', 'OBMC_CHASSIS_INSTANCES')}"

inherit skeleton-gdbus
inherit obmc-phosphor-dbus-service
inherit pkgconfig

RPROVIDES:${PN} += "virtual-obmc-host-ctl"

DBUS_SERVICE:${PN} += "org.openbmc.control.Host@.service"
OBMC_CONTROL_INST = "org.openbmc.control.Host@{0}.service"
OBMC_CONTROL_SVC = "org.openbmc.control.Host@.service"
OBMC_CONTROL_FMT = "../${OBMC_CONTROL_SVC}:multi-user.target.wants/${OBMC_CONTROL_INST}"
SYSTEMD_LINK:${PN} += "${@compose_list(d, 'OBMC_CONTROL_FMT', 'OBMC_HOST_INSTANCES')}"

repository: openbmc/openbmc

repo_name: openbmc/openbmc

gha_license_id: NOASSERTION


text:
//html/template package which is used to render the html from a template.
//net/http package to handle https requests.
//read/write to the database and use it to power content management system.
//templates dir will hold the html templates and cmd will contain the executable code ie. main.go file
package main

import (
	//"codes/contentx"
	"github.com/shikharvashistha/contentx"
	"os"
)

func main() {
	p := &contentx.Page{ //created a reference to an instance of contentx.Page
		Title:   "Hello World",
		Content: "Body of our web page",
	}
	contentx.Tmpl.ExecuteTemplate(os.Stdout, "index", p)
	//os.Stdout is where to write the template to
	//next argument is the template name
	//next argument is the data to be passed to the template
}

repository: shikharvashistha/contentX

repo_name: shikharvashistha/contentX


text:
package lesson3

import (
	"testing"
)

func TestIsMatch(t *testing.T) {
	rText := "abcdefg"
	lText := "gfedcba"
	if ok := IsMatch(rText, lText); !ok {
		t.Fatal(rText, lText)
	}

	rText = "abcdefg"
	lText = "gfedbba"
	if ok := IsMatch(rText, lText); ok {
		t.Fatal(rText, lText)
	}

	rText = "abcdefg"
	lText = "hgfedcba"
	if ok := IsMatch(rText, lText); ok {
		t.Fatal(rText, lText)
	}
}

func TestIsMatchBySort(t *testing.T) {
	rText := "abcdefg"
	lText := "gfedcba"
	if ok := IsMatchBySort(rText, lText); !ok {
		t.Fatal(rText, lText)
	}

	rText = "abcdefg"
	lText = "gfedbba"
	if ok := IsMatchBySort(rText, lText); ok {
		t.Fatal(rText, lText)
	}

	rText = "abcdefg"
	lText = "hgfedcba"
	if ok := IsMatchBySort(rText, lText); ok {
		t.Fatal(rText, lText)
	}
}

repository: gotokatsuya/CTCI

repo_name: gotokatsuya/CTCI


text:
package models

// Log represents a log message object
type Log struct {
	Message        string
	Data           interface{}
	AdditionalInfo interface{}
}


text:
package main

import (
    "fmt"
    "net/http"
    "./config"
    "./controller"
    "strconv"
)

func main() {
    conf := config.GetConfig()

    http.HandleFunc("/", controller.About)
    http.HandleFunc("/flows/", controller.Flows)
    http.HandleFunc("/flow/", controller.Flow)
    http.HandleFunc("/user/", controller.UserSteps)

    fmt.Println("Running server on port: " + strconv.Itoa(conf.Service.Port))
    http.ListenAndServe(":" + strconv.Itoa(conf.Service.Port), nil)
}


text:
package GoJira_test

import (
	. "github.com/ryanplasma/GoJira"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"net/http"
	"net/http/httptest"
)

var _ = Describe("Issue", func() {
	var (
		mux     *http.ServeMux
		server  *httptest.Server
		session *Session
	)

	BeforeEach(func() {
		mux = http.NewServeMux()
		server = httptest.NewServer(mux)
		session = NewSession(server.URL, "TEST", "TEST", "TEST")
	})

	Describe("Issue()", func() {
		It("should return and Issue", func() {
			mux.HandleFunc("/issue/TEST-123", func(w http.ResponseWriter, r *http.Request) {
				respondWithJSON(w, loadFixture("issue.json"))
			})
			issue, err := session.Issue("TEST-123")
			if err != nil {
				Fail("ERROR: " + err.Error())
			}
			Expect(issue).Should(BeAssignableToTypeOf(&Issue{}))
			Expect(issue.Key).ToNot(BeNil())
		})
	})
})

repository: ryanplasma/GoJira

repo_name: ryanplasma/GoJira


text:
DESCRIPTION = "GLib-based DBus bindings for shr-project.org"
AUTHOR = "Klaus 'mrmoku' Kurzmann"
LICENSE = "LGPL"
SECTION = "devel"
DEPENDS = "gdbus-binding-tool glib-2.0 shr-specs"
SRCREV = "761dea6463326714c00342cb53ba28a1c2dfea63"
PV = "2011.01.04.1+gitr${SRCPV}"
PR = "r0"

inherit autotools

SRC_URI = "git://git.shr-project.org/repo/libshr-glib.git;protocol=http;branch=master"
S = "${WORKDIR}/git"

do_configure_prepend() {
       sed -i -e s#SHR_SPECS_DIR="#SHR_SPECS_DIR="${STAGING_DIR_HOST}/#g ${S}/configure.ac
}


text:
HOMEPAGE = "http://linux.bytesex.org/fbida/"
DESCRIPTION = "frame buffer image and doc viewer tools"
AUTHOR = "Gerd Hoffmann"
SECTION = "utils"

LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=8ca43cbc842c2336e835926c2166c28b"

DEPENDS = "virtual/libiconv libpng jpeg fontconfig freetype libexif curl libungif tiff"

SRC_URI = "git://git.kraxel.org/fbida"
SRCREV = "cb0ce5fa5f42bfaea4f8f326bcd8914dd14e782d"
S = "${WORKDIR}/git"

EXTRA_OEMAKE = "STRIP="

do_compile() {
    sed -i -e 's: cpp: ${TARGET_PREFIX}cpp -I{STAGING_INCDIR}:g' GNUmakefile
    oe_runmake
}

do_install() {
    oe_runmake 'DESTDIR=${D}' install
}

RDEPENDS_${PN} = "ttf-dejavu-sans-mono"

repository: ExorEmbedded/exor-workspace

repo_name: ExorEmbedded/exor-workspace


text:
@InProceedings{carvalho09a,
  title = {Handling Sparsity via the Horseshoe},
  author = {Carlos M. Carvalho and Nicholas G. Polson and James G. Scott},
  pages = {73--80},
  abstract = {This paper presents a general, fully Bayesian framework for sparse supervised-learning problems based on the horseshoe prior. The horseshoe prior is a member of the family of multivariate scale mixtures of normals, and is therefore closely related to widely used approaches for sparse Bayesian learning, including, among others, Laplacian priors (e.g. the LASSO) and Student-t priors (e.g. the relevance vector machine). The advantages of the horseshoe are its robustness at handling unknown sparsity and large outlying signals. These properties are justifed theoretically via a representation theorem and accompanied by comprehensive empirical experiments that compare its performance to benchmark alternatives.},
  pdf = {http://jmlr.org/proceedings/papers/v5/carvalho09a/carvalho09a.pdf},
}


text:
@Proceedings{pgm2016,
  booktitle = {Proceedings of the Eighth International Conference on Probabilistic Graphical Models},
  name = {Conference on Probabilistic Graphical Models},
  conference_number = 8,
  shortname = {PGM 2016},
  year = {2016},
  editor = {Alessandro Antonucci and Giorgio Corani and Cassio Polpo \{de Campos\}},
  published = {2016-08-15},
  conference_url = {http://www2.idsia.ch/cms/pgm/},
  address = {Lugano, Switzerland},
  start = {2016-09-06},
  end = {2016-09-09},
  volume = {52},
  sections = {preface=Preface|default=Accepted Papers}
}

repository: mlresearch/papersite

repo_name: mlresearch/papersite


text:
require xfce4-base-image.bb

export IMAGE_BASENAME = "xfce4-tiny-image"

IMAGE_INSTALL += " \
    packagegroup-xfce-extended \
    packagegroup-xfce-multimedia \
    rodent-icon-theme \
    \
    packagegroup-gui-tiny \
    ${@bb.utils.contains('BBFILE_COLLECTIONS', 'meta-musicians', 'xfce4-mixer', '', d)} \
"

repository: ZeraGmbH/meta-mortsgna

repo_name: ZeraGmbH/meta-mortsgna


text:
SUMMARY = "Internationalized Domain Names in Applications (IDNA)"
HOMEPAGE = "https://github.com/kjd/idna"
AUTHOR = "Kim Davies <kim@cynosure.com.au>"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://LICENSE.rst;md5=cf36c8682cc154d2d4aa57bd6246b9a1"

SRC_URI = "https://files.pythonhosted.org/packages/cb/19/57503b5de719ee45e83472f339f617b0c01ad75cba44aba1e4c97c2b0abd/idna-2.9.tar.gz"
SRC_URI[md5sum] = "870b8b80267f00f0faf1b7ba4bdbf14e"
SRC_URI[sha256sum] = "7588d1c14ae4c77d74036e8c22ff447b26d0fde8f007354fd48a7814db15b7cb"

S = "${WORKDIR}/idna-2.9"

RDEPENDS_${PN} = ""

inherit setuptools3

repository: danieltarnu/meta-marlin

repo_name: danieltarnu/meta-marlin

gha_language: PHP


text:
package log

import (
	"io"
	"sync"
)

// AsyncWriter is an Writer that writes asynchronously.
type AsyncWriter struct {
	// ChannelSize is the size of the data channel, the default size is 1.
	ChannelSize uint

	// Writer specifies the writer of output.
	Writer Writer

	once    sync.Once
	ch      chan *Entry
	chClose chan error
}

// Close implements io.Closer, and closes the underlying Writer.
func (w *AsyncWriter) Close() (err error) {
	w.ch <- nil
	err = <-w.chClose
	if closer, ok := w.Writer.(io.Closer); ok {
		if err1 := closer.Close(); err1 != nil {
			err = err1
		}
	}
	return
}

// WriteEntry implements Writer.
func (w *AsyncWriter) WriteEntry(e *Entry) (int, error) {
	w.once.Do(func() {
		// channels
		w.ch = make(chan *Entry, w.ChannelSize)
		w.chClose = make(chan error)
		go func() {
			var err error
			for entry := range w.ch {
				if entry == nil {
					break
				}
				_, err = w.Writer.WriteEntry(entry)
				epool.Put(entry)
			}
			w.chClose <- err
		}()
	})

	// cheating to logger pool
	entry := epool.Get().(*Entry)
	entry.Level = e.Level
	entry.buf, e.buf = e.buf, entry.buf

	w.ch <- entry
	return len(entry.buf), nil
}

var _ Writer = (*AsyncWriter)(nil)

repository: phuslu/log

repo_name: phuslu/log


text:
SUMMARY = "A library to access weather information from online services"

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

GNOMEBASEBUILDCLASS = "meson"

inherit gnomebase gsettings gobject-introspection gettext gtk-doc vala features_check upstream-version-is-even

SRC_URI[archive.md5sum] = "ff399cf89e97a3e574ae05db5617b96b"
SRC_URI[archive.sha256sum] = "ee1201a8fc25c14e940d3b26db49a34947c8aebf67dee01ee67fbcb06ecb37a0"

# gobject-introspection is mandatory and cannot be configured
REQUIRED_DISTRO_FEATURES = "gobject-introspection-data"
UNKNOWN_CONFIGURE_WHITELIST:append = " introspection"

GTKDOC_MESON_OPTION = "gtk_doc"

DEPENDS = " \
    gtk+3 \
    json-glib \
    libsoup-2.4 \
    geocode-glib \
"

repository: Intel-BMC/openbmc

repo_name: Intel-BMC/openbmc


text:
@article{persson19,
   author = {Persson, Inger and Arnroth, Lukas and Thulin, Mans},
   title = {Multivariate two sample permutation tests for trials with multiple time to event outcomes},
   journal = {Pharmaceutical Statistics},
   volume = {18},
   year = 2019,
   pages = {476-485},
   doi = {10.1002/pst.1938}
}
@article{wei84,
   author = {Wei, LJ and Lachin, JM},
   title = {Two sample asymptotically distribution free tests for incomplete multivariate observations},
   journal = {Journal of the American Statistical Association},
   volume = {79(387)},
   year = 1984,
   pages = {653-661},
   doi = {10.1080/01621459.1984.10478093}
}
@article{thulin14,
   author = {Mans Thulin},
   title = {The cost of using exact confidence intervals for a binomial proportion},
   journal = {Electronic Journal of Statistics},
   volume = {8(1)},
   year = 2014,
   pages = {817-840},
   doi = {10.1214/14-EJS909}
}
@article{huster89,
   author = {Huster, WJ and Brookmeyer, R and Self, SG},
   title = {Modelling paired survival data with covariates},
   journal = {Biometrics},
   volume = {45},
   year = 1989,
   pages = {145-156},
   doi = {10.2307/2532041}}

repository: mthulin/MultSurvTests

repo_name: mthulin/MultSurvTests


text:
SUMMARY = "OpenJPEG library"
DESCRIPTION = "OpenJPEG library is an open-source JPEG 2000 codec written in C language.\
    It has been developed in order to promote the use of JPEG 2000, a still-image compression\
    standard from the Joint Photographic Experts Group (JPEG)."
HOMEPAGE = "http://www.openjpeg.org"
LICENSE = "BSD-2-Clause"
LIC_FILES_CHKSUM = "file://LICENSE;md5=c648878b4840d7babaade1303e7f108c"

DEPENDS_append = " libpng tiff lcms zlib"

SRC_URI = "\
    git://github.com/uclouvain/openjpeg.git;protocol=https \
    file://0002-Do-not-ask-cmake-to-export-binaries-they-don-t-make-.patch \
    file://CVE-2020-6851.patch \
    file://CVE-2020-8112.patch \
"
SRCREV = "57096325457f96d8cd07bd3af04fe81d7a2ba788"
S = "${WORKDIR}/git"

inherit cmake

# for multilib
EXTRA_OECMAKE += "-DOPENJPEG_INSTALL_LIB_DIR=${@d.getVar('baselib', True).replace('/', '')}"

FILES_${PN} += "${libdir}/openjpeg*"

repository: WebPlatformForEmbedded/meta-wpe

repo_name: WebPlatformForEmbedded/meta-wpe


text:
package model_api

import (
	"goskeleton/app/model"
	"goskeleton/app/model/tool"
)

func FlowAdTypeRelDB() *FlowAdTypeRelModel {
	return &FlowAdTypeRelModel{BaseModel: model.BaseModel{DB: model.CreateMysqlDB("Api")}}
}

type FlowAdTypeRelModel struct {
	model.BaseModel `json:"-"`
	Id              int64   `gorm:"column:id" json:"id"`
	FlowId          int64   `gorm:"column:flow_id" json:"flow_id"`                 // 流量配置id
	AppKey          string  `gorm:"column:app_key" json:"app_key"`                 //
	AdType          int     `gorm:"column:ad_type" json:"ad_type"`                 // 广告类型 1视频2插页
	Price           float64 `gorm:"column:price" json:"price"`                     // 底价
	Status          int     `gorm:"column:status" json:"status"`                   // 是否开启1是0否
	IsPriority      int     `gorm:"column:is_priority" json:"is_priority"`         // 是否使用优先1是0否
	IsUseDsp        int     `gorm:"column:is_use_dsp" json:"is_use_dsp"`           // 是否使用DSP 1是0否
	IsDelay         int     `gorm:"column:is_delay" json:"is_delay"`               // 尝鲜延迟加载1是0否
	Time            int64   `gorm:"column:time" json:"time"`                       // 尝鲜延迟加载时间,单位为秒
	Del             int     `gorm:"column:del" json:"del"`                         // 删除标志
	IsAppRel        int     `gorm:"column:is_app_rel" json:"is_app_rel"`           // 是否定向app配置0否1是
	IsBlockPolicy   int     `gorm:"column:is_block_policy" json:"is_block_policy"` // 是否定向广告位策略0否1是
	IsDefault       int     `gorm:"column:is_default" json:"is_default"`           // 是否使用默认配置
	model.TimeColumns
}

// TableName 表名
func (f *FlowAdTypeRelModel) TableName() string {
	return "flow_ad_type_rel"
}

func (f *FlowAdTypeRelModel) GetsBy(query *tool.WhereQuery, order string) (list []*FlowAdTypeRelModel) {
	if order == "" {
		order = "update_time desc"
	}
	f.Table(f.TableName()).Where(query.QuerySql, query.QueryParams...).Order(order).Find(&list)
	return
}

repository: cxlcxl/go-test

repo_name: cxlcxl/go-test


text:
package detective

import (
	"context"
	"fmt"
	"strconv"
	"time"

	core "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	meta "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/klog/v2"
)

func (d *Detective) createNamespace() error {
	klog.V(2).Infof("Creating Namespace")
	spec := &core.Namespace{
		ObjectMeta: meta.ObjectMeta{
			GenerateName: "detective-",
		},
		Status: core.NamespaceStatus{},
	}

	ns, err := d.client.CoreV1().Namespaces().Create(d.tomb.Context(nil), spec, meta.CreateOptions{})
	if err != nil {
		return err
	}

	d.namespace = ns
	klog.V(3).Infof("  created %v", ns.Name)

	return nil
}

func (d *Detective) deleteNamespace() error {
	klog.V(2).Infof("Deleting Namespace")
	err := d.client.CoreV1().Namespaces().Delete(context.Background(), d.namespace.Name, meta.DeleteOptions{})
	if err != nil {
		return err
	}
	klog.V(3).Infof("  deleted %v", d.namespace.Name)
	return nil
}

func (d *Detective) waitForServiceAccountInNamespace() error {
	klog.V(2).Info("Waiting for Service Account")

	return wait.PollImmediateUntil(1*time.Second, func() (done bool, err error) {
		_, err = d.client.CoreV1().ServiceAccounts(d.namespace.Name).Get(d.tomb.Context(nil), "default", meta.GetOptions{})
		return err == nil, nil
	}, d.tomb.Dying())
}

func (d *Detective) createPods() error {
	nodes, err := d.ListNodesWithPredicate(d.NodeIsSchedulabeleAndRunning)
	if err != nil {
		return err
	}

	klog.V(2).Info("Creating pods")
	for _, node := range nodes {
		if !d.tomb.Alive() {
			return fmt.Errorf("Interrupted")
		}
		if _, err := d.createPod(d.createPodSpec(node, false)); err != nil {
			return err
		}
		if _, err := d.createPod(d.createPodSpec(node, true)); err != nil {
			return err
		}
	}

	return nil
}

func (d *Detective) createPod(pod *core.Pod) (*core.Pod, error) {
	pod, err := d.client.CoreV1().Pods(d.namespace.Name).Create(d.tomb.Context(nil), pod, meta.CreateOptions{})
	if err == nil {
		klog.V(3).Infof("  created %v on %v", pod.Name, pod.Spec.NodeName)
	}
	return pod, err
}

func (d *Detective) createPodSpec(node *core.Node, hostNetwork bool) *core.Pod {
	var gracePeriod int64 = 2
	return &core.Pod{
		ObjectMeta: meta.ObjectMeta{
			GenerateName: "server-",
			Labels: map[string]string{
				"nodeName":    node.Name,
				"hostNetwork": strconv.FormatBool(hostNetwork),
			},
		},
		Spec: core.PodSpec{
			Containers: []core.Container{
				{
					Name:  "server",
					Image: d.testImage,
					Ports: []core.ContainerPort{{ContainerPort: 9376}},
				},
			},
			NodeName:                      node.Name,
			HostNetwork:                   hostNetwork,
			TerminationGracePeriodSeconds: &gracePeriod,
		},
	}
}

func (d *Detective) waitForPodsRunning() error {
	klog.V(2).Info("Waiting for running Pods")

	nodes, err := d.ListNodesWithPredicate(d.NodeIsSchedulabeleAndRunning)
	if err != nil {
		return err
	}

	return wait.PollImmediateUntil(1*time.Second, func() (done bool, err error) {
		pods, err := d.informers.Core().V1().Pods().Lister().Pods(d.namespace.Name).List(labels.Everything())
		if err != nil {
			return false, err
		}

		running := 0
		for _, pod := range pods {
			switch pod.Status.Phase {
			case core.PodRunning:
				running++
			case core.PodFailed:
				return false, fmt.Errorf("Failed to create a Pod: %v", pod.Status.Reason)
			}
		}

		klog.V(3).Infof("  %v/%v pods running", running, len(nodes)*2)
		return running == len(nodes)*2, nil
	}, d.tomb.Dying())
}

func (d *Detective) createSevices(withExternalIP bool) error {
	klog.V(2).Info("Creating services")

	pods, err := d.informers.Core().V1().Pods().Lister().Pods(d.namespace.Name).List(labels.Everything())
	if err != nil {
		return err
	}

	for _, pod := range pods {
		if !d.tomb.Alive() {
			return fmt.Errorf("Interrupted")
		}

		spec, err := d.createServiceSpec(pod, withExternalIP)
		if err != nil {
			return err
		}

		service, err := d.client.CoreV1().Services(d.namespace.Name).Create(d.tomb.Context(nil), spec, meta.CreateOptions{})
		if err != nil {
			return err
		}
		klog.V(3).Infof("  created %v at %v for %v", service.Name, service.Spec.ExternalIPs, pod.Name)
	}

	return nil
}

func (d *Detective) createServiceSpec(pod *core.Pod, withExternalIP bool) (*core.Service, error) {
	service := &core.Service{
		ObjectMeta: meta.ObjectMeta{
			GenerateName: "clusterip-",
			Labels: map[string]string{
				"podName":     pod.Name,
				"podIP":       pod.Status.PodIP,
				"nodeName":    pod.Spec.NodeName,
				"hostNetwork": strconv.FormatBool(pod.Spec.HostNetwork),
			},
		},
		Spec: core.ServiceSpec{
			Type: core.ServiceTypeClusterIP,
			Ports: []core.ServicePort{
				{
					Port:       ServiceHttpPort,
					TargetPort: intstr.IntOrString{IntVal: PodHttpPort},
				},
			},
			Selector: map[string]string{
				"nodeName":    pod.Spec.NodeName,
				"hostNetwork": strconv.FormatBool(pod.Spec.HostNetwork),
			},
		},
	}

	if withExternalIP {
		if len(d.externalIPs) == 0 {
			return nil, fmt.Errorf("No more externalIPs available. Boom!")
		}

		d.externalIPs = d.externalIPs[1:]
		service.Spec.ExternalIPs = []string{d.externalIPs[0]}
	}

	return service, nil
}

func (d *Detective) waitForServiceEndpoints() error {
	klog.V(2).Info("Waiting for service endpoints")

	nodes, err := d.ListNodesWithPredicate(d.NodeIsSchedulabeleAndRunning)
	if err != nil {
		return err
	}

	return wait.PollImmediateUntil(1*time.Second, func() (done bool, err error) {
		services, err := d.informers.Core().V1().Services().Lister().List(labels.Everything())
		if err != nil {
			return false, err
		}

		klog.V(3).Infof("  found %v nodes", len(nodes))
		klog.V(3).Infof("  found %v srvices", len(services))

		ready := 0
		for _, service := range services {
			endpoints, err := d.informers.Core().V1().Endpoints().Lister().Endpoints(d.namespace.Name).Get(service.Name)
			if err != nil {
				if errors.IsNotFound(err) {
					klog.V(3).Infof("  endpoint %v not found: %v", service.Name, err)
					continue
				}
				klog.V(3).Infof("  endpoint %v error: %v", service.Name, err)
				return false, err
			}
			for _, subset := range endpoints.Subsets {
				ready = ready + len(subset.Addresses)
			}
		}

		klog.V(3).Infof("  %v/%v services ready", ready, len(nodes)*2)
		return ready == len(nodes)*2, nil
	}, d.tomb.Dying())
}

repository: alex-egorov/kube-detective

repo_name: alex-egorov/kube-detective


text:
package boopy

import "time"

// Periodically fix finger tables.
// periodically runs down finger table, recreating finger entries for each finger table ID
func (node *Node) fixFingerRoutine(val int) {
	next := 0
	timer := time.NewTicker(time.Duration(val) * time.Millisecond)
	for {
		select {
		case <-timer.C:
			// found in finger.go,
			next = node.fixFinger(next)
		case <-node.shutdownCh:
			timer.Stop()
			return
		}
	}
}

// Stabilize Routine
func (node *Node) stabilizeRoutine(val int) {
	timer := time.NewTicker(time.Duration(val) * time.Millisecond)
	for {
		select {
		case <-timer.C:
			node.stabilize()
		case <-node.shutdownCh:
			timer.Stop()
			return
		}
	}

}

// Check predecessor failed routine
func (node *Node) checkPredecessorRoutine(val int) {
	ticker := time.NewTicker(time.Duration(val) * time.Millisecond)
	for {
		select {
		case <-ticker.C:
			node.checkPredecessor()
		case <-node.shutdownCh:
			ticker.Stop()
			return
		}
	}

}

repository: bonedaddy/Boopy

repo_name: bonedaddy/Boopy


text:
package inputport

import (
	"pumpkin/codes/domain/model"
)

type ShowUserInputPort interface {
	DoUsecase(user *model.User) error
}

type ShowUsersInputPort interface {
	DoUsecase(users model.Users) error
}


text:
package lux

import (
	"github.com/go-gl/gl/v3.3-core/gl"
	glm "github.com/go-gl/mathgl/mgl32"
	gl2 "github.com/luxengine/gl"
	"github.com/luxengine/lux/utils"
)

//Mesh is an interface to represent any renderable mesh
type Mesh interface {
	Bind()
	Delete()
	Size() int32
	DrawCall()
}

//VUNMesh is a Vertex-Uv-Normal mesh
type VUNMesh struct { //Vertex, Uv, Normal Model
	VAO                              gl2.VertexArray
	Indices, Positions, Uvs, Normals gl2.Buffer
	Msize                            int32
}

//NewWavefrontModelFromFile loads a wavefront from the given file. Can only load files that are triangulated and with UV. Does not do anythign with material property.
func NewWavefrontModelFromFile(file string) Mesh {
	//load object
	meshObj := utils.LoadObject(file, false)

	//prepare indices //to optimise later
	indices, indexedVertices, indexedUvs, indexedNormals := utils.IndexVBOSlow(meshObj.Vertices, meshObj.UVs, meshObj.Normals)
	return NewVUNModel(indices, indexedVertices, indexedUvs, indexedNormals)
}

//NewVUNModel process and uploads the data to the GPU.
func NewVUNModel(indices []uint16, indexedVertices []glm.Vec3, indexedUvs []glm.Vec2, indexedNormals []glm.Vec3) Mesh {

	m := VUNMesh{}
	m.VAO = gl2.GenVertexArray()
	m.VAO.Bind()
	defer m.VAO.Unbind()

	m.Msize = int32(len(indices))
	//create a bunch of buffers and fill them
	//Positions
	m.Positions = gl2.GenBuffer()
	m.Positions.Bind(gl.ARRAY_BUFFER)
	m.Positions.Data(gl.ARRAY_BUFFER, len(indexedVertices)*3*4, ptr(indexedVertices), gl.STATIC_DRAW)

	//Uvs
	m.Uvs = gl2.GenBuffer()
	m.Uvs.Bind(gl.ARRAY_BUFFER)
	m.Uvs.Data(gl.ARRAY_BUFFER, len(indexedUvs)*2*4, ptr(indexedUvs), gl.STATIC_DRAW)

	//Normals
	m.Normals = gl2.GenBuffer()
	m.Normals.Bind(gl.ARRAY_BUFFER)
	m.Normals.Data(gl.ARRAY_BUFFER, len(indexedNormals)*3*4, ptr(indexedNormals), gl.STATIC_DRAW)

	//indices
	m.Indices = gl2.GenBuffer()
	m.Indices.Bind(gl.ELEMENT_ARRAY_BUFFER)
	m.Indices.Data(gl.ELEMENT_ARRAY_BUFFER, len(indices)*2, ptr(indices), gl.STATIC_DRAW)

	return &m
}

//Bind the vertex array and all vertex attrib required to render this mesh.
func (m *VUNMesh) Bind() {
	vao := m.VAO
	vao.Bind()

	vao.EnableVertexAttribArray(0)
	m.Positions.Bind(gl.ARRAY_BUFFER)
	vao.VertexAttribPointer(0, 3, gl.FLOAT, false, 0, nil)

	vao.EnableVertexAttribArray(1)
	m.Uvs.Bind(gl.ARRAY_BUFFER)
	vao.VertexAttribPointer(1, 2, gl.FLOAT, false, 0, nil)

	vao.EnableVertexAttribArray(2)
	m.Normals.Bind(gl.ARRAY_BUFFER)
	vao.VertexAttribPointer(2, 3, gl.FLOAT, false, 0, nil)

	m.Indices.Bind(gl.ELEMENT_ARRAY_BUFFER)
}

//Unbind all the resources.
func (m *VUNMesh) Unbind() {
	m.VAO.Unbind()
}

//Delete all allocated resources (buffers, vertexarray,etc).
func (m VUNMesh) Delete() {
	defer m.Positions.Delete()
	defer m.Uvs.Delete()
	defer m.Normals.Delete()
	defer m.Indices.Delete()
	defer m.VAO.Delete()
}

//Size returns the amount of verteices to be drawn.
func (m *VUNMesh) Size() int32 {
	return m.Msize
}

//DrawCall send a single draw call
func (m *VUNMesh) DrawCall() {
	gl.DrawElements(gl.TRIANGLES, m.Size(), gl.UNSIGNED_SHORT, nil)
}


text:
@article{Lai2011,
author = {Lai, Chris C. K. and Lee, Joseph H. W.},
booktitle = {Asian And Pacific Coasts 2011},
doi = {10.1142/9789814366489_0248},
month = {nov},
pages = {2065--2075},
publisher = {World Scientific},
title = {{The Near-field Jet Behavior of 60° Dense Jets Discharged Into A Perpendicular Crossflow}},
url = {http://www.worldscientific.com/doi/abs/10.1142/9789814366489{\_}0248},
year = {2011}
}


text:
# Copyright (c) 2012-2022 LG Electronics, Inc.

DESCRIPTION = "webOS component for managing network connections using connman"
AUTHOR = "Muralidhar N <muralidhar.n@lge.com>"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = " \
    file://LICENSE;md5=2763f3ed850f8412903ea776e0526bea \
    file://oss-pkg-info.yaml;md5=b0cf0d697c8340cbfa56b94bdc2539fb \
"

SECTION = "webos/services"

DEPENDS = "luna-service2 libpbnjson glib-2.0 luna-prefs openssl glib-2.0-native wca-support-api wca-support"
RDEPENDS:${PN} = "connman connman-client"

WEBOS_VERSION = "1.1.0-39_dc622623142035004f2354cc90cfee0e8fc3c5b3"
PR = "r10"

PV = "1.1.0-39+git${SRCPV}"

SRCREV = "dc622623142035004f2354cc90cfee0e8fc3c5b3"

inherit webos_public_repo
inherit webos_cmake
inherit webos_system_bus
inherit webos_systemd
inherit pkgconfig

# Set EXTRA_OECMAKE in webos-connman-adapter.bbappend to override default value for wifi and wired interfaces, for eg.
# EXTRA_OECMAKE += "-DWIFI_IFACE_NAME=wlan0 -DWIRED_IFACE_NAME=eth1"

EXTRA_OECMAKE += "-DENABLE_SCAN_ON_SOFTAP=true"

PACKAGECONFIG[enable-multiple-routing-table] = "-DMULTIPLE_ROUTING_TABLE:BOOL=true,-DMULTIPLE_ROUTING_TABLE:BOOL=false,"
PACKAGECONFIG = "enable-multiple-routing-table"

SRC_URI = "${WEBOSOSE_GIT_REPO_COMPLETE} \
            file://0001-Workaround-to-prevent-luna-call-pending.patch \
            file://0002-Add-systemd-service-file.patch \
            file://0003-Add-back-com.palm.wan-for-cellular-support.patch \
"

S = "${WORKDIR}/git"

repository: webOS-ports/meta-webos-ports

repo_name: webOS-ports/meta-webos-ports

branch_name: refs/heads/kirkstone


text:
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package retry_test

import (
	"context"
	"errors"
	"fmt"
	"log"

	"github.com/m3db/m3/src/x/retry"
)

func ExampleRetrier() {
	var (
		opts    = retry.NewOptions()
		retrier = retry.NewRetrier(opts)
		context = context.Background()
	)

	continueFn := func(attempt int) bool {
		// Check if the context has been canceled.
		select {
		case <-context.Done():
			return false
		default:
			return true
		}
	}

	var attempts int
	fn := func() error {
		// Perform some work which may fail.

		if attempts++; attempts == 3 {
			fmt.Printf("Attempt %v succeeded", attempts)
			// Output: Attempt 3 succeeded

			return nil
		}
		return errors.New("test")
	}

	if err := retrier.AttemptWhile(continueFn, fn); err != nil {
		log.Fatal(err)
	}

}


text:
SECTION = "kernel"
DESCRIPTION = "Mainline Linux kernel"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=d7810fab7487fb0aad327b76f1be7cd7"
COMPATIBLE_MACHINE = "(sun4i|sun5i|sun7i|sun8i)"

inherit kernel

require linux.inc

KBRANCH ?= "master"

# Pull in the devicetree files into the rootfs
RDEPENDS_${KERNEL_PACKAGE_NAME}-base += "kernel-devicetree"

# Default is to use stable kernel version
# If you want to use latest git version set to "1"
DEFAULT_PREFERENCE = "-1"

KERNEL_EXTRA_ARGS += "LOADADDR=${UBOOT_ENTRYPOINT}"

# 4.15-rc1
PV = "4.15+git${SRCPV}"
SRCREV_pn-${PN} = "4fbd8d194f06c8a3fd2af1ce560ddb31f7ec8323"

SRC_URI = "git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git;protocol=git;branch=master \
        file://defconfig \
        "
S = "${WORKDIR}/git"

repository: rofehr/mld-source

repo_name: rofehr/mld-source


text:
@inproceedings{Janousch:2015mtf,
      author         = "Janousch, Markus and others",
      title          = "{Overview and Status of the SwissFEL Project at PSI}",
      booktitle      = "{Proceedings, 15th International Conference on
                        Accelerator and Large Experimental Physics Control Systems
                        (ICALEPCS 2015): Melbourne, Australia, October 17-23,
                        2015}",
      year           = "2015",
      url            = "https://inspirehep.net/record/1481755/files/fra3o03.pdf",
      pages          = "FRA3O03",
      doi            = "10.18429/JACoW-ICALEPCS2015-FRA3O03",
      SLACcitation   = "%%CITATION = INSPIRE-1481755;%%"
}

repository: musoke/inspirer

repo_name: musoke/inspirer

gha_language: Rust


text:
SUMMARY = "Linux Kernel timestamping"
LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=d7810fab7487fb0aad327b76f1be7cd7"

SRC_URI = "https://www.kernel.org/pub/linux/kernel/v4.x/linux-${PV}.tar.xz"

SRC_URI[md5sum] = "fe9dc0f6729f36400ea81aa41d614c37"
SRC_URI[sha256sum] = "caf51f085aac1e1cea4d00dbbf3093ead07b551fc07b31b2a989c05f8ea72d9f"

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

PACKAGE_ARCH = "${MACHINE_ARCH}"

do_compile () {
	cd ${S}/Documentation/networking/timestamping
	${CC} -o timestamping timestamping.c
}

do_install () {
	install -d ${D}${bindir}
	install -m 0755 ${S}/Documentation/networking/timestamping/timestamping ${D}${bindir}
}

INSANE_SKIP:${PN} = "ldflags"

repository: rcn-ee/meta-arago

repo_name: rcn-ee/meta-arago