text:
package tests

import (
    "reflect"
    "testing"
)

/**
 * [1528] Kids With the Greatest Number of Candies
 *
 * Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.
 *
 * For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.
 *
 *
 * Example 1:
 *
 *
 * Input: candies = [2,3,5,1,3], extraCandies = 3
 * Output: [true,true,true,false,true]
 * Explanation:
 * Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids.
 * Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
 * Kid 3 has 5 candies and this is already the greatest number of candies among the kids.
 * Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies.
 * Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
 *
 *
 * Example 2:
 *
 *
 * Input: candies = [4,2,1,1,2], extraCandies = 1
 * Output: [true,false,false,false,false]
 * Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy.
 *
 *
 * Example 3:
 *
 *
 * Input: candies = [12,1,12], extraCandies = 10
 * Output: [true,false,true]
 *
 *
 *
 * Constraints:
 *
 *
 * 	2 <= candies.length <= 100
 * 	1 <= candies[i] <= 100
 * 	1 <= extraCandies <= 50
 *
 */

func TestKidsWiththeGreatestNumberofCandies(t *testing.T) {
    var cases = []struct {
    	input []int
    	extra int
        output []bool
    }{
    	{
    	    input: []int{2,3,5,1,3},
    	    extra: 3,
    	    output: []bool{true, true, true, false, true},
        },
    }
    for _, c := range cases {
        x := kidsWithCandies(c.input, c.extra)
        if !reflect.DeepEqual(x, c.output) {
            t.Fail()
        }
    }
}

// submission codes start here

func kidsWithCandies(candies []int, extraCandies int) []bool {
	maxInit := 0
    for _, v := range candies {
        maxInit = max(maxInit, v)
    }

    res := make([]bool, len(candies))
    for i, v := range candies {
        if v + extraCandies >= maxInit {
            res[i] = true
        } else {
            res[i] = false
        }
    }
    return res
}

// submission codes end


text:
package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var (
	port        int
	storageAddr string
	remoteAddr  string
	hmacSecret  string
	sessionUuid string
)

// Initialize function will be called when every command gets called.
func init() {
	// Get our environment variables which will used to configure our application and save across all the sub-commands.
	rootCmd.PersistentFlags().StringVar(&hmacSecret, "hmacSecret", os.Getenv("TBRIDGE_SERVER_HMAC_SECRET"), "The bridge signing key.")
	rootCmd.PersistentFlags().StringVar(&sessionUuid, "sessionUuid", os.Getenv("TBRIDGE_SERVER_SESSION_UUID"), "The bridge session uuid.")
}

var rootCmd = &cobra.Command{
	Use:   "tbridge-server",
	Short: "Bridge time-series data across a network",
	Long:  `Bridge time-series data across a network using HTTP in client and serve mode.`,
	Run: func(cmd *cobra.Command, args []string) {
		// Do nothing...
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

license: ISC

repository: isgasho/tbridge-server

license_type: permissive

repo_name: isgasho/tbridge-server

branch_name: refs/heads/master

extension: go


text:
require upslug2_8.bb
inherit native

SRC_URI[md5sum] = "c7e9c64afa7a375a523a250f9fd778a9"
SRC_URI[sha256sum] = "b0b5302ce0d17efb0d2a8ba92273524cbe8f96ebd5ae21475c905922806d445a"

license: MIT

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
@article{mccauley2016ending,
  title={Ending hide and seek at sea},
  author={McCauley, Douglas J and Woods, Paul and Sullivan, Brian and Bergman, Bjorn and Jablonicky, Caroline and Roan, Aaron and Hirshfield, Michael and Boerder, Kristina and Worm, Boris},
  journal={Science},
  volume={351},
  number={6278},
  pages={1148--1150},
  year={2016},
  publisher={American Association for the Advancement of Science}
}

@article{hintzen2012vmstools,
  title={VMStools: open-source software for the processing, analysis and visualisation of fisheries logbook and {VMS} data},
  author={Hintzen, Niels T and Bastardie, Francois and Beare, Doug and Piet, Gerjan J and Ulrich, Clara and Deporte, Nicolas and Egekvist, Josefine and Degel, Henrik},
  journal={Fisheries Research},
  volume={115},
  pages={31--43},
  year={2012},
  publisher={Elsevier}
}

@article{bertrand2005levy,
  title={L{\'e}vy trajectories of {P}eruvian purse-seiners as an indicator of the spatial distribution of anchovy (\textit{{E}ngraulis ringens})},
  author={Bertrand, Sophie and Burgos, Julian M and Gerlotto, Fran{\c{c}}ois and Atiquipa, Jaime},
  journal={ICES Journal of Marine Science},
  volume={62},
  number={3},
  pages={477--482},
  year={2005},
  publisher={Oxford University Press}
}

@article{bastardie2010detailed,
  title={Detailed mapping of fishing effort and landings by coupling fishing logbooks with satellite-recorded vessel geo-location},
  author={Bastardie, Francois and Nielsen, J Rasmus and Ulrich, Clara and Egekvist, Josefine and Degel, Henrik},
  journal={Fisheries Research},
  volume={106},
  number={1},
  pages={41--53},
  year={2010},
  publisher={Elsevier}
}

@article{murawski2005effort,
  title={Effort distribution and catch patterns adjacent to temperate {MPA}s},
  author={Murawski, Steven A and Wigley, Susan E and Fogarty, Michael J and Rago, Paul J and Mountain, David G},
  journal={ICES Journal of Marine Science},
  volume={62},
  number={6},
  pages={1150--1167},
  year={2005},
  publisher={Oxford University Press}
}

@article{sbrocco2013marspec,
  title={MARSPEC: ocean climate layers for marine spatial ecology},
  author={Sbrocco, Elizabeth J and Barber, Paul H},
  journal={Ecology},
  volume={94},
  number={4},
  pages={979--979},
  year={2013},
  publisher={Eco Soc America}
}

@article{colloca2015seascape,
  title={The seascape of demersal fish nursery areas in the north {M}editerranean Sea, a first step towards the implementation of spatial planning for trawl fisheries},
  author={Colloca, Francesco and Garofalo, Germana and Bitetto, Isabella and Facchini, Maria Teresa and Grati, Fabio and Martiradonna, Angela and Mastrantonio, Gianluca and Nikolioudakis, Nikolaos and Ordinas, Francesc and Scarcella, Giuseppe and others},
  journal={PloS One},
  volume={10},
  number={3},
  pages={e0119590},
  year={2015},
  publisher={Public Library of Science}
}

@Book{wood2006gam,
  title = {Generalized Additive Models: An Introduction with {R}},
  year = {2006},
  author = {S.N Wood},
  publisher = {Chapman and Hall/CRC},
}

@Manual{rlesc,
  title = {R: A Language and Environment for Statistical Computing},
  author = {{R Core Team}},
  organization = {R Foundation for Statistical Computing},
  address = {Vienna, Austria},
  year = {2017},
  url = {https://www.R-project.org/},
}

@article{pauly1998fishing,
  title={Fishing down marine food webs},
  author={Pauly, Daniel and Christensen, Villy and Dalsgaard, Johanne and Froese, Rainer and Torres, Francisco},
  journal={Science},
  volume={279},
  number={5352},
  pages={860--863},
  year={1998},
  publisher={American Association for the Advancement of Science}
}

@article{hoekstra2005confronting,
  title={Confronting a biome crisis: global disparities of habitat loss and protection},
  author={Hoekstra, Jonathan M and Boucher, Timothy M and Ricketts, Taylor H and Roberts, Carter},
  journal={Ecology letters},
  volume={8},
  number={1},
  pages={23--29},
  year={2005},
  publisher={Wiley Online Library}
}

@misc{euro_stat2016,
  title = {Fishing Fleet by Type of Gear and Engine Power},
  author = {Eurostat},
  year = {2016},
  howpublished = {\url{http://appsso.eurostat.ec.europa.eu/nui/show.do?dataset=fish_fleet_gp&lang=en}},
  note = {Accessed: 2016-08-01}
}

@article{russo2013spatial,
  title={Spatial indicators of fishing pressure: Preliminary analyses and possible developments},
  author={Russo, T and Parisi, A and Cataudella, S},
  journal={Ecological Indicators},
  volume={26},
  pages={141--153},
  year={2013},
  publisher={Elsevier}
}

@article{lee2010developing,
  title={Developing reliable, repeatable, and accessible methods to provide high-resolution estimates of fishing-effort distributions from vessel monitoring system ({VMS}) data},
  author={Lee, Janette and South, Andy B and Jennings, Simon},
  journal={ICES Journal of Marine Science},
  volume={67},
  number={6},
  pages={1260--1271},
  year={2010},
  publisher={Oxford University Press}
}

@article{zuur2010protocol,
  title={A protocol for data exploration to avoid common statistical problems},
  author={Zuur, Alain F and Ieno, Elena N and Elphick, Chris S},
  journal={Methods in Ecology and Evolution},
  volume={1},
  number={1},
  pages={3--14},
  year={2010},
  publisher={Wiley Online Library}
}

@article{vespe2016mapping,
  title={Mapping {EU} fishing activities using ship tracking data},
  author={Vespe, Michele and Gibin, Maurizio and Alessandrini, Alfredo and Natale, Fabrizio and Mazzarella, Fabio and Osio, Giacomo C},
  journal={Journal of Maps},
  volume={12},
  number={sup1},
  pages={520--525},
  year={2016},
  publisher={Taylor \& Francis}
}

@article{gelman2008weakly,
  title={A weakly informative default prior distribution for logistic and other regression models},
  author={Gelman, Andrew and Jakulin, Aleks and Pittau, Maria Grazia and Su, Yu-Sung and others},
  journal={The Annals of Applied Statistics},
  volume={2},
  number={4},
  pages={1360--1383},
  year={2008},
  publisher={Institute of Mathematical Statistics}
}

@article{carpenter2017stan,
  title={Stan: A probabilistic programming language},
  author={Bob Carpenter and Andrew Gelman and Matthew Hoffman and Daniel Lee and Ben Goodrich and Michael Betancourt and Marcus Brubaker and Jiqiang Guo and Peter Li and Allen Riddell},
  journal={Journal of Statistical Software},
  volume={76},
  number={1},
  pages={1--32},
  year={2017}
}

@Misc{rstanarm2016,
  title = {rstanarm: {Bayesian} applied regression modeling via {Stan}.},
  author = {{Stan Development Team}},
  note = {R package version 2.13.1},
  year = {2016},
  url = {http://mc-stan.org/},
}

@book{gelman2013bda3,
  title={Bayesian data analysis},
  author={Gelman, Andrew and Carlin, John B and Stern, Hal S and Dunson, David B},
  volume={3},
  year={2013}
}

@book{mcelreath2020statistical,
  title={Statistical Rethinking: A Bayesian course with examples in R and Stan},
  author={McElreath, Richard},
  year={2020},
  publisher={CRC Press}
}

@book{hobbs2015bayesian,
  title={Bayesian Models: a Statistical Primer for Ecologists},
  author={Hobbs, N Thompson and Hooten, Mevin B},
  year={2015},
  publisher={Princeton University Press}
}

@book{holmes2018modern,
  title={Modern Statistics for Modern Biology},
  author={Holmes, Susan and Huber, Wolfgang},
  year={2018},
  publisher={Cambridge University Press}
}

@book{edge2019statistical,
  title={Statistical Thinking from Scratch: A Primer for Scientists},
  author={Edge, Michael D},
  year={2019},
  publisher={Oxford University Press, USA}
}

@book{lambert2018student,
  title={A Student’s Guide to Bayesian statistics},
  author={Lambert, Ben},
  year={2018},
  publisher={Sage}
}

@book{kruschke2014doing,
  title={Doing Bayesian data analysis: A tutorial with R, JAGS, and Stan},
  author={Kruschke, John},
  year={2014},
  publisher={Academic Press}
}

@article{coates1999growth,
  title={Growth of planted tree seedlings in response to ambient light levels in northwestern interior cedar-hemlock forests of British Columbia},
  author={Coates, K Dave and Burton, Philip J},
  journal={Canadian Journal of Forest Research},
  volume={29},
  number={9},
  pages={1374--1382},
  year={1999},
  publisher={NRC Research Press}
}

@article{elahi2012consumers,
  title={Consumers mediate natural variation between prey richness and resource use in a benthic marine community},
  author={Elahi, Robin and Sebens, Kenneth P},
  journal={Marine Ecology Progress Series},
  volume={452},
  pages={131--143},
  year={2012}
}

@book{bolker2008ecological,
  title={Ecological models and data in R},
  author={Bolker, Benjamin M},
  year={2008},
  publisher={Princeton University Press}
}

@book{johnson2022bayes,
  title={Bayes Rules!: An Introduction to Applied Bayesian Modeling},
  author={Johnson, Alicia A. and Ott, Miles Q. and Dogucu, Mine},
  year={2022},
  publisher={CRC Press}
}

@inproceedings{berger1988likelihood,
  title = {The Likelihood Principle},
  author = {Berger, James O. and Wolpert, Robert L.},
  year = {1988},
  series = {Lecture Notes - Monograph Series},
  organization = {Institute of Mathematical Statistics}
}

@article{el1995people,
  title={Are people Bayesian? Uncovering behavioral strategies},
  author={El-Gamal, Mahmoud A. and Grether, David M.},
  journal={Journal of the American Statistical Association},
  volume={90},
  number={432},
  pages={1137--1145},
  year={1995},
  publisher={Taylor \& Francis}
}

@inproceedings{goodman2008dirty,
  title={A dirty dozen: twelve p-value misconceptions},
  author={Goodman, Steven},
  booktitle={Seminars in Hematology},
  volume={45},
  number={3},
  pages={135--140},
  year={2008},
  organization={Elsevier}
}

@article{wasserstein2016asa,
  title={The ASA statement on p-values: context, process, and purpose},
  author={Wasserstein, Ronald L and Lazar, Nicole A},
  journal={The American Statistician},
  volume={70},
  number={2},
  pages={129--133},
  year={2016},
  publisher={Taylor \& Francis}
}

@article{roberts2020think,
  title={How to think like an epidemiologist},
  author={Roberts, Siobhan},
  journal={Don’t worry, a little Bayesian analysis won’t hurt you. New York, NY, USA: New York Times},
  year={2020}
}

@book{mcgrayne2011theory,
  title={The Theory That Would Not Die: How Bayes' Rule Cracked the Enigma Code, Hunted Down Russian Submarines, \& Emerged Triumphant from Two Centuries of Controversy},
  author={McGrayne, Sharon Bertsch},
  year={2011},
  publisher={Yale University Press}
}

@book{fisher1992statistical,
  title={Statistical Methods for Research Workers},
  author={Fisher, Ronald Aylmer},
  year={1925},
  publisher={Oliver and Boyd, Edinburgh}
}

@article{mbuvha2020bayesian,
  title={Bayesian inference of COVID-19 spreading rates in South Africa},
  author={Mbuvha, Rendani and Marwala, Tshilidzi},
  journal={PloS one},
  volume={15},
  number={8},
  pages={e0237126},
  year={2020},
  publisher={Public Library of Science San Francisco, CA USA}
}

@article{lum2010measuring,
  title={Measuring elusive populations with bayesian model averaging for multiple systems estimation: A case study on lethal violations in casanare, 1998-2007},
  author={Lum, Kristian and Price, Megan and Guberek, Tamy and Ball, Patrick},
  journal={Statistics, Politics, and Policy},
  volume={1},
  number={1},
  year={2010},
  publisher={De Gruyter}
}

@book{blackwell1969basicstats,
  title={Basic Statistics},
  author={Blackwell, David},
  year={1969},
  publisher={Mcgraw-Hill Book Company}
}

@article{coates1999growth,
  title={Growth of planted tree seedlings in response to ambient light levels in northwestern interior cedar-hemlock forests of British Columbia},
  author={Coates, K Dave and Burton, Philip J},
  journal={Canadian Journal of Forest Research},
  volume={29},
  number={9},
  pages={1374--1382},
  year={1999},
  publisher={NRC Research Press Ottawa, Canada}
}

extension: bib


text:
@book{Puterman:1994:MDP:528623,
 author = {Puterman, Martin L.},
 title = {Markov Decision Processes: Discrete Stochastic Dynamic Programming},
 year = {1994},
 isbn = {0471619779},
 edition = {1st},
 publisher = {John Wiley \& Sons, Inc.},
 address = {New York, NY, USA},
}

repository: MaxRobinson/CALispCritique

repo_name: MaxRobinson/CALispCritique


text:
package googledevice

import (
	"github.com/rjw57/oauth2device"
)

// Endpoint specifies the endpoints used for the Google OAuth
// 2.0 for devices.
var DeviceEndpoint = oauth2device.DeviceEndpoint{
	CodeURL: "https://accounts.google.com/o/oauth2/device/code",
}


text:
require classpath.inc

SRC_URI += "\
  file://SimpleName.diff;striplevel=0 \
  file://ecj_java_dir.patch \
  file://autotools.patch \
  file://fix-gmp.patch \
  file://toolwrapper-exithook.patch \
  "

PR = "r4"

SRC_URI[md5sum] = "90c6571b8b0309e372faa0f9f6255ea9"
SRC_URI[sha256sum] = "501b5acd4dff79b6100da22cef15080f31071821ce3cea6f1b739bc1b56fac3f"


text:
DESCRIPTION = "Task to install additional scripts and applications into the SDK"
LICENSE = "MIT"
PR = "r29"

PN = "packagegroup-arago-tisdk-amsdk-sdk-host${ARAGO_KERNEL_SUFFIX}"

PACKAGE_ARCH = "${MACHINE_ARCH}"

inherit packagegroup

# Choose the kernel and u-boot recipe sources to use
UBOOT_SRC = "${PREFERRED_PROVIDER_virtual/bootloader}-source"
KERNEL_SRC = "${PREFERRED_PROVIDER_virtual/kernel}-source"

KERNEL_SHADOW_CLONE := "${PREFERRED_PROVIDER_virtual/kernel}"
KERNEL_SHADOW_CLONE_ENABLED := "${SRCIPK_SHALLOW_CLONE_pn-${KERNEL_SHADOW_CLONE}}"

BOOT_MONITOR = ""
BOOT_MONITOR_keystone = "boot-monitor-source"

EXTRA_FILES = ""
EXTRA_FILES_ti43x = "tisdk-uenv"
EXTRA_FILES_omap-a15 = "tisdk-readme tisdk-uenv"
EXTRA_FILES_k3 = "tisdk-readme tisdk-uenv"

RDEPENDS_${PN} = "\
    ti-tisdk-setup \
    ${EXTRA_FILES} \
    ti-tisdk-makefile \
    ${UBOOT_SRC} \
    ${KERNEL_SRC} \
    ${BOOT_MONITOR} \
    ${@oe.utils.conditional('KERNEL_SHADOW_CLONE_ENABLED','true','unshallow-repositories','',d)} \
    tisdk-install \
"


text:
@misc{gva-2020,
    author = {Gun Violence Archive},
    title = "{Mass shootings in 2020}",
    url = {https://www.gunviolencearchive.org/reports/mass-shooting},
    urldate = {2020-03-04},
    mendeley-tags = {Interesting datasets},
    annote = "A mass shooting is defined as four or more shot and/or killed in a single event. There are seven variables in this dataset. The number of rows increases as events are added over time."
}

repository: pmean/build-website

repo_name: pmean/build-website


text:
// Copyright (c) 2020-2022 Doc.ai and/or its affiliates.
//
// Copyright (c) 2023 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 nsmgr_test

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/require"
	"go.uber.org/atomic"
	"go.uber.org/goleak"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"github.com/networkservicemesh/api/pkg/api/networkservice"
	"github.com/networkservicemesh/api/pkg/api/registry"

	nsclient "github.com/networkservicemesh/sdk/pkg/networkservice/chains/client"
	"github.com/networkservicemesh/sdk/pkg/networkservice/common/heal"
	"github.com/networkservicemesh/sdk/pkg/networkservice/common/null"
	"github.com/networkservicemesh/sdk/pkg/networkservice/utils/checks/checkresponse"
	"github.com/networkservicemesh/sdk/pkg/networkservice/utils/count"
	"github.com/networkservicemesh/sdk/pkg/networkservice/utils/inject/injecterror"
	registryclient "github.com/networkservicemesh/sdk/pkg/registry/chains/client"
	"github.com/networkservicemesh/sdk/pkg/tools/clock"
	"github.com/networkservicemesh/sdk/pkg/tools/clockmock"
	"github.com/networkservicemesh/sdk/pkg/tools/sandbox"
)

const (
	tick    = 10 * time.Millisecond
	timeout = 10 * time.Second
)

func TestNSMGR_HealEndpoint(t *testing.T) {
	var samples = []struct {
		name    string
		nodeNum int
	}{
		{
			name:    "Local New",
			nodeNum: 0,
		},
		{
			name:    "Remote New",
			nodeNum: 1,
		},
	}

	for _, sample := range samples {
		t.Run(sample.name, func(t *testing.T) {
			// nolint:scopelint
			testNSMGRHealEndpoint(t, sample.nodeNum)
		})
	}
}

func testNSMGRHealEndpoint(t *testing.T, nodeNum int) {
	t.Cleanup(func() { goleak.VerifyNone(t) })
	ctx, cancel := context.WithTimeout(context.Background(), timeout)

	defer cancel()
	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(nodeNum + 1).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	nseReg := defaultRegistryEndpoint(nsReg.Name)

	counter := new(count.Server)
	nse := domain.Nodes[nodeNum].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken, counter)

	request := defaultRequest(nsReg.Name)

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken)

	conn, err := nsc.Request(ctx, request.Clone())
	require.NoError(t, err)
	require.Equal(t, 1, counter.UniqueRequests())

	nse.Cancel()

	nseReg2 := defaultRegistryEndpoint(nsReg.Name)
	nseReg2.Name += "-2"
	domain.Nodes[nodeNum].NewEndpoint(ctx, nseReg2, sandbox.GenerateTestToken, counter)

	// Wait reconnecting to the new NSE
	require.Eventually(t, checkSecondRequestsReceived(counter.UniqueRequests), timeout, tick)
	require.Equal(t, 2, counter.UniqueRequests())
	closes := counter.UniqueCloses()

	// Check refresh
	request.Connection = conn
	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	// Close with old connection
	_, err = nsc.Close(ctx, conn)
	require.NoError(t, err)

	require.Equal(t, 2, counter.UniqueRequests())
	require.Equal(t, closes+1, counter.UniqueCloses())
}

func TestNSMGRHealEndpoint_DataPlaneBroken_CtrlPlaneBroken(t *testing.T) {
	// This the same test as above but here we explicitly provided livenessCheck function
	// The above test is for nil livenessCheck

	t.Cleanup(func() { goleak.VerifyNone(t) })
	ctx, cancel := context.WithTimeout(context.Background(), timeout)

	defer cancel()
	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(1).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	nseReg := defaultRegistryEndpoint(nsReg.Name)

	counter := new(count.Server)
	nse := domain.Nodes[0].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken, counter)

	request := defaultRequest(nsReg.Name)

	livenessCheck := func(ctx context.Context, conn *networkservice.Connection) bool {
		return false
	}

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken,
		nsclient.WithHealClient(heal.NewClient(ctx,
			heal.WithLivenessCheck(livenessCheck))))

	conn, err := nsc.Request(ctx, request.Clone())
	require.NoError(t, err)
	require.Equal(t, 1, counter.UniqueRequests())

	nse.Cancel()

	nseReg2 := defaultRegistryEndpoint(nsReg.Name)
	nseReg2.Name += "-2"
	domain.Nodes[0].NewEndpoint(ctx, nseReg2, sandbox.GenerateTestToken, counter)

	// Wait reconnecting to the new NSE
	require.Eventually(t, checkSecondRequestsReceived(counter.UniqueRequests), timeout, tick)
	require.Equal(t, 2, counter.UniqueRequests())
	closes := counter.UniqueCloses()

	// Check refresh
	request.Connection = conn
	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	// Close with old connection
	_, err = nsc.Close(ctx, conn)
	require.NoError(t, err)

	require.Equal(t, 2, counter.UniqueRequests())
	require.Equal(t, closes+1, counter.UniqueCloses())
}

func TestNSMGRHealEndpoint_DataPlaneBroken_CtrlPlaneHealthy(t *testing.T) {
	// This the same test as above but here we explicitly provided livenessCheck function
	// The above test is for nil livenessCheck

	t.Cleanup(func() { goleak.VerifyNone(t) })
	ctx, cancel := context.WithTimeout(context.Background(), timeout)

	defer cancel()
	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(1).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	nseReg := defaultRegistryEndpoint(nsReg.Name)

	counter := new(count.Server)
	domain.Nodes[0].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken, counter)

	request := defaultRequest(nsReg.Name)

	livenessCheck := func(ctx context.Context, conn *networkservice.Connection) bool { return false }

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken,
		nsclient.WithHealClient(heal.NewClient(ctx, heal.WithLivenessCheck(livenessCheck))))

	// Connect to the first NSE.
	conn, err := nsc.Request(ctx, request.Clone())
	require.NoError(t, err)
	require.Equal(t, 1, counter.Requests())

	// Create the second NSE.
	nseReg2 := defaultRegistryEndpoint(nsReg.Name)
	nseReg2.Name += "-2"
	domain.Nodes[0].NewEndpoint(ctx, nseReg2, sandbox.GenerateTestToken, counter)

	require.Eventually(t, checkSecondRequestsReceived(counter.UniqueRequests), timeout, tick)
	require.Equal(t, 2, counter.UniqueRequests())
	closes := counter.UniqueCloses()

	// Check refresh
	request.Connection = conn
	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	// Close with old connection
	_, err = nsc.Close(ctx, conn)
	require.NoError(t, err)

	require.Equal(t, 2, counter.UniqueRequests())
	require.Equal(t, closes+1, counter.UniqueCloses())
}

func TestNSMGRHealEndpoint_DatapathHealthy_CtrlPlaneBroken(t *testing.T) {
	t.Cleanup(func() { goleak.VerifyNone(t) })
	ctx, cancel := context.WithTimeout(context.Background(), timeout)

	defer cancel()
	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(1).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	nseReg := defaultRegistryEndpoint(nsReg.Name)

	counter := new(count.Server)
	nse := domain.Nodes[0].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken, counter)

	request := defaultRequest(nsReg.Name)

	livenessCheck := func(ctx context.Context, conn *networkservice.Connection) bool { return true }

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken,
		nsclient.WithHealClient(heal.NewClient(ctx,
			heal.WithLivenessCheck(livenessCheck))))

	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)
	require.Equal(t, 1, counter.UniqueRequests())

	nse.Cancel()

	nseReg2 := defaultRegistryEndpoint(nsReg.Name)
	nseReg2.Name += "-2"
	domain.Nodes[0].NewEndpoint(ctx, nseReg2, sandbox.GenerateTestToken, counter)

	// Should not connect to new NSE
	require.Never(t, func() bool { return counter.UniqueRequests() > 1 }, time.Second*2, tick)
	require.Equal(t, 1, counter.UniqueRequests())
}

func TestNSMGR_HealForwarder(t *testing.T) {
	var samples = []struct {
		name    string
		nodeNum int
	}{
		{
			name:    "Local New",
			nodeNum: 0,
		},
		{
			name:    "Remote New",
			nodeNum: 1,
		},
	}

	for _, sample := range samples {
		t.Run(sample.name, func(t *testing.T) {
			// nolint:scopelint
			testNSMGRHealForwarder(t, sample.nodeNum)
		})
	}
}

func testNSMGRHealForwarder(t *testing.T, nodeNum int) {
	t.Cleanup(func() { goleak.VerifyNone(t) })

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(2).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	counter := new(count.Server)
	domain.Nodes[1].NewEndpoint(ctx, defaultRegistryEndpoint(nsReg.Name), sandbox.GenerateTestToken, counter)

	request := defaultRequest(nsReg.Name)

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken)

	conn, err := nsc.Request(ctx, request.Clone())
	require.NoError(t, err)
	require.Equal(t, 1, counter.UniqueRequests())

	for _, forwarder := range domain.Nodes[nodeNum].Forwarders {
		forwarder.Cancel()
		break
	}

	forwarderReg := &registry.NetworkServiceEndpoint{
		Name:                sandbox.UniqueName("forwarder-2"),
		NetworkServiceNames: []string{"forwarder"},
	}
	domain.Nodes[nodeNum].NewForwarder(ctx, forwarderReg, sandbox.GenerateTestToken)

	// Wait reconnecting through the new Forwarder
	require.Eventually(t, checkSecondRequestsReceived(counter.Requests), timeout, tick)
	require.Equal(t, 2, counter.Requests())
	closes := counter.UniqueCloses()

	// Check refresh
	request.Connection = conn
	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	// Close with old connection
	_, err = nsc.Close(ctx, conn)
	require.NoError(t, err)

	require.Equal(t, 3, counter.Requests())
	require.Equal(t, closes+1, counter.Closes())
}

func TestNSMGR_HealNSMgr(t *testing.T) {
	var samples = []struct {
		name     string
		nodeNum  int
		restored bool
	}{
		{
			name:     "Local Restored",
			nodeNum:  0,
			restored: true,
		},
		{
			name:    "Remote New",
			nodeNum: 1,
		},
	}

	for _, sample := range samples {
		t.Run(sample.name, func(t *testing.T) {
			// nolint:scopelint
			testNSMGRHealNSMgr(t, sample.nodeNum, sample.restored)
		})
	}
}

func testNSMGRHealNSMgr(t *testing.T, nodeNum int, restored bool) {
	t.Cleanup(func() { goleak.VerifyNone(t) })

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(3).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	nseReg := defaultRegistryEndpoint(nsReg.Name)

	counter := new(count.Server)
	domain.Nodes[1].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken, counter)

	request := defaultRequest(nsReg.Name)

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken)

	conn, err := nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	if !restored {
		nseReg2 := defaultRegistryEndpoint(nsReg.Name)
		nseReg2.Name += "-2"

		domain.Nodes[2].NewEndpoint(ctx, nseReg2, sandbox.GenerateTestToken, counter)

		domain.Nodes[nodeNum].NSMgr.Cancel()
	} else {
		domain.Nodes[nodeNum].NSMgr.Restart()
	}

	var closes int
	if restored {
		// Wait reconnecting through the restored NSMgr
		require.Eventually(t, checkSecondRequestsReceived(counter.Requests), timeout, tick)
		require.Equal(t, 2, counter.Requests())
	} else {
		// Wait reconnecting through the new NSMgr
		require.Eventually(t, checkSecondRequestsReceived(counter.UniqueRequests), timeout, tick)
		require.Equal(t, 2, counter.UniqueRequests())
		closes = counter.UniqueCloses()
	}

	// Check refresh
	request.Connection = conn
	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	// Close with old connection
	_, err = nsc.Close(ctx, conn)
	require.NoError(t, err)

	if restored {
		require.Equal(t, 3, counter.Requests())
		require.Equal(t, 2, counter.Closes())
	} else {
		require.Equal(t, 2, counter.UniqueRequests())
		require.Equal(t, closes+1, counter.UniqueCloses())
	}
}

func TestNSMGR_HealRegistry(t *testing.T) {
	t.Cleanup(func() { goleak.VerifyNone(t) })

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(1).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	nseReg := defaultRegistryEndpoint(nsReg.Name)

	counter := new(count.Server)
	domain.Nodes[0].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken, counter)

	request := defaultRequest(nsReg.Name)

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken)

	conn, err := nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	// 1. Restart Registry
	domain.Registry.Restart()

	// 2. Check refresh
	request.Connection = conn
	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	// 3. Check new client request
	nsc = domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken)

	_, err = nsc.Request(ctx, request.Clone())
	require.NoError(t, err)

	require.Equal(t, 3, counter.Requests())
}

func TestNSMGR_CloseHeal(t *testing.T) {
	var samples = []struct {
		name              string
		withNSEExpiration bool
	}{
		{
			name: "Without NSE expiration",
		},
		{
			name:              "With NSE expiration",
			withNSEExpiration: true,
		},
	}

	for _, sample := range samples {
		t.Run(sample.name, func(t *testing.T) {
			// nolint:scopelint
			testNSMGRCloseHeal(t, sample.withNSEExpiration)
		})
	}
}

func testNSMGRCloseHeal(t *testing.T, withNSEExpiration bool) {
	t.Cleanup(func() { goleak.VerifyNone(t) })

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	builder := sandbox.NewBuilder(ctx, t).
		SetNodesCount(1).
		SetNSMgrProxySupplier(nil).
		SetRegistryProxySupplier(nil)

	domain := builder.Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg, err := nsRegistryClient.Register(ctx, defaultRegistryService(t.Name()))
	require.NoError(t, err)

	nseCtx, nseCtxCancel := context.WithTimeout(ctx, time.Second/2)
	if withNSEExpiration {
		// NSE will be unregistered after (tokenTimeout - registerTimeout)
		domain.Nodes[0].NewEndpoint(nseCtx, defaultRegistryEndpoint(nsReg.Name), sandbox.GenerateExpiringToken(time.Second))
	} else {
		domain.Nodes[0].NewEndpoint(nseCtx, defaultRegistryEndpoint(nsReg.Name), sandbox.GenerateTestToken)
	}

	request := defaultRequest(nsReg.Name)

	nscCtx, nscCtxCancel := context.WithCancel(ctx)

	nsc := domain.Nodes[0].NewClient(nscCtx, sandbox.GenerateTestToken)

	reqCtx, reqCancel := context.WithTimeout(ctx, time.Second)
	defer reqCancel()

	// 1. Request
	conn, err := nsc.Request(reqCtx, request.Clone())
	require.NoError(t, err)

	ignoreCurrent := goleak.IgnoreCurrent()

	// 2. Refresh
	request.Connection = conn

	conn, err = nsc.Request(reqCtx, request.Clone())
	require.NoError(t, err)

	// 3. Stop endpoint and wait for the heal to start
	nseCtxCancel()
	time.Sleep(100 * time.Millisecond)

	if withNSEExpiration {
		// 3.1 Wait for the endpoint expiration
		time.Sleep(time.Second)
		c := registryclient.NewNetworkServiceEndpointRegistryClient(ctx,
			registryclient.WithClientURL(domain.Nodes[0].NSMgr.URL),
			registryclient.WithDialOptions(sandbox.DialOptions(sandbox.WithTokenGenerator(sandbox.GenerateTestToken))...))

		stream, err := c.Find(ctx, &registry.NetworkServiceEndpointQuery{
			NetworkServiceEndpoint: &registry.NetworkServiceEndpoint{
				Name: "final-endpoint",
			},
		})

		require.NoError(t, err)

		require.Len(t, registry.ReadNetworkServiceEndpointList(stream), 0)
	}

	// 4. Close connection
	_, _ = nsc.Close(nscCtx, conn.Clone())

	nscCtxCancel()

	require.Eventually(t, func() bool {
		logrus.Error(goleak.Find())
		return goleak.Find(ignoreCurrent) == nil
	}, timeout, tick)

	require.NoError(t, ctx.Err())
}

func checkSecondRequestsReceived(requestsDone func() int) func() bool {
	return func() bool {
		return requestsDone() >= 2
	}
}

func Test_ForwarderShouldBeSelectedCorrectlyOnNSMgrRestart(t *testing.T) {
	var samples = []struct {
		name             string
		nodeNum          int
		pathSegmentCount int
	}{
		{
			name:             "Local",
			nodeNum:          0,
			pathSegmentCount: 4,
		},
		{
			name:             "Remote",
			nodeNum:          1,
			pathSegmentCount: 6,
		},
	}

	for _, sample := range samples {
		t.Run(sample.name, func(t *testing.T) {
			// nolint:scopelint
			testForwarderShouldBeSelectedCorrectlyOnNSMgrRestart(t, sample.nodeNum, sample.pathSegmentCount)
		})
	}
}

func testForwarderShouldBeSelectedCorrectlyOnNSMgrRestart(t *testing.T, nodeNum, pathSegmentCount int) {
	t.Cleanup(func() { goleak.VerifyNone(t) })

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
	defer cancel()

	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(nodeNum + 1).
		SetRegistryProxySupplier(nil).
		SetNSMgrProxySupplier(nil).
		Build()

	var expectedForwarderName string

	require.Len(t, domain.Nodes[nodeNum].Forwarders, 1)
	for k := range domain.Nodes[nodeNum].Forwarders {
		expectedForwarderName = k
	}

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	_, err := nsRegistryClient.Register(ctx, &registry.NetworkService{
		Name: "my-ns",
	})
	require.NoError(t, err)

	nseReg := &registry.NetworkServiceEndpoint{
		Name:                "my-nse-1",
		NetworkServiceNames: []string{"my-ns"},
	}

	nseEntry := domain.Nodes[nodeNum].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken)

	nsc := domain.Nodes[0].NewClient(ctx, sandbox.GenerateTestToken, nsclient.WithHealClient(null.NewClient()))

	request := defaultRequest("my-ns")

	conn, err := nsc.Request(ctx, request.Clone())
	require.NoError(t, err)
	require.NotNil(t, conn)
	require.Equal(t, pathSegmentCount, len(conn.Path.PathSegments))
	require.Equal(t, expectedForwarderName, conn.GetPath().GetPathSegments()[pathSegmentCount-2].Name)

	nseRegistryClient := registryclient.NewNetworkServiceEndpointRegistryClient(ctx,
		registryclient.WithClientURL(sandbox.CloneURL(domain.Nodes[nodeNum].NSMgr.URL)),
		registryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())))

	for i := 0; i < 10; i++ {
		request.Connection = conn.Clone()
		conn, err = nsc.Request(ctx, request.Clone())

		require.NoError(t, err)
		require.Equal(t, expectedForwarderName, conn.GetPath().GetPathSegments()[pathSegmentCount-2].Name)

		domain.Nodes[nodeNum].NSMgr.Restart()

		_, err = nseRegistryClient.Register(ctx, &registry.NetworkServiceEndpoint{
			Name:                nseReg.Name,
			Url:                 nseEntry.URL.String(),
			NetworkServiceNames: nseReg.NetworkServiceNames,
		})
		require.NoError(t, err)

		_, err = nseRegistryClient.Register(ctx, &registry.NetworkServiceEndpoint{
			Name:                expectedForwarderName,
			Url:                 domain.Nodes[nodeNum].Forwarders[expectedForwarderName].URL.String(),
			NetworkServiceNames: []string{"forwarder"},
			NetworkServiceLabels: map[string]*registry.NetworkServiceLabels{
				"forwarder": {
					Labels: map[string]string{
						"p2p": "true",
					},
				},
			},
		})
		require.NoError(t, err)

		domain.Nodes[nodeNum].NewForwarder(ctx, &registry.NetworkServiceEndpoint{
			Name:                sandbox.UniqueName(fmt.Sprintf("%v-forwarder", i)),
			NetworkServiceNames: []string{"forwarder"},
			NetworkServiceLabels: map[string]*registry.NetworkServiceLabels{
				"forwarder": {
					Labels: map[string]string{
						"p2p": "true",
					},
				},
			},
		}, sandbox.GenerateTestToken)
	}
}

func TestNSMGR_RefreshFailed_DataPlaneBroken(t *testing.T) {
	t.Cleanup(func() { goleak.VerifyNone(t) })

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	domain := sandbox.NewBuilder(ctx, t).
		SetNodesCount(1).
		Build()

	nsRegistryClient := domain.NewNSRegistryClient(ctx, sandbox.GenerateTestToken)

	nsReg := defaultRegistryService(t.Name())
	nsReg, err := nsRegistryClient.Register(ctx, nsReg)
	require.NoError(t, err)

	nseReg := defaultRegistryEndpoint(nsReg.Name)

	counter1 := new(count.Server)
	// allow only one successful request
	inject := injecterror.NewServer(injecterror.WithCloseErrorTimes(), injecterror.WithRequestErrorTimes(1, -1))
	isDataplaneHealthy := atomic.Bool{}
	isDataplaneHealthy.Store(true)
	domain.Nodes[0].NewEndpoint(ctx, nseReg, sandbox.GenerateTestToken, counter1, inject)

	request := defaultRequest(nsReg.Name)

	tokenDuration := time.Minute * 15
	clk := clockmock.New(ctx)
	clk.Set(time.Now())

	nsc := domain.Nodes[0].NewClient(ctx,
		sandbox.GenerateExpiringToken(tokenDuration),
		nsclient.WithHealClient(heal.NewClient(ctx,
			heal.WithLivenessCheck(func(ctx context.Context, conn *networkservice.Connection) bool {
				return isDataplaneHealthy.Load()
			}),
			heal.WithLivenessCheckInterval(time.Millisecond*10),
		)),
	)

	requestCtx, requestCalcel := context.WithTimeout(ctx, time.Second)
	requestCtx = clock.WithClock(requestCtx, clk)
	defer requestCalcel()
	conn, err := nsc.Request(requestCtx, request.Clone())
	require.NoError(t, err)
	require.Equal(t, 1, counter1.Requests())

	nseReg2 := defaultRegistryEndpoint(nsReg.Name)
	nseReg2.Name += "-2"

	counter2 := new(count.Server)
	// automatically restore data plane flag to prevent repeated heal
	dataPlaneNotifier := checkresponse.NewServer(t, func(t *testing.T, c *networkservice.Connection) {
		if c != nil {
			isDataplaneHealthy.Store(true)
		}
	})
	domain.Nodes[0].NewEndpoint(ctx, nseReg2, sandbox.GenerateTestToken, dataPlaneNotifier, counter2)

	// refresh interval in this test is expected to be 3 minutes and a few milliseconds
	clk.Add(time.Second * 190)

	// wait till refresh reached NSE, to make sure that initial heal monitor is canceled
	require.Eventually(t, checkSecondRequestsReceived(counter1.Requests), timeout, tick)

	isDataplaneHealthy.Store(false)

	require.Eventually(t, func() bool { return counter2.Requests() >= 1 }, timeout, tick)
	require.Equal(t, 1, counter2.UniqueRequests())
	require.Equal(t, 1, counter2.Requests())

	_, err = nsc.Close(ctx, conn.Clone())
	require.NoError(t, err)
}

repository: networkservicemesh/sdk

repo_name: networkservicemesh/sdk

branch_name: refs/heads/main

gha_language: Go


text:
SUMMARY = "Kodi Media Center"

LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://LICENSE.md;md5=7b423f1c9388eae123332e372451a4f7"

FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}-18:"

PACKAGE_ARCH = "${MACHINE}"

inherit cmake gettext python3-dir python3native

DEPENDS += " \
            fmt \
            flatbuffers flatbuffers-native \
            fstrcmp \
            rapidjson \
            crossguid \
            libdvdnav libdvdcss libdvdread \
            ${@bb.utils.contains('PREFERRED_VERSION_ffmpeg', '3.4.2', 'ffmpeg-kodi-18', 'ffmpeg', d)} \
            git-native \
            curl-native \
            gperf-native \
            jsonschemabuilder-native \
            nasm-native \
            swig-native \
            unzip-native \
            yasm-native \
            zip-native \
            \
            avahi \
            boost \
            bzip2 \
            curl \
            dcadec \
            enca \
            expat \
            faad2 \
            fontconfig \
            fribidi \
            glib-2.0 \
            giflib \
            libass \
            libcdio \
            libcec \
            libinput \
            libbluray \
            libmad \
            libmicrohttpd \
            libmms \
            libmodplug \
            libnfs \
            libpcre \
            libplist \
            libsamplerate0 \
            libsquish \
            libssh \
            libtinyxml \
            libusb1 \
            libxkbcommon \
            libxslt \
            lzo \
            mpeg2dec \
            python \
            samba \
            sqlite3 \
            taglib \
            virtual/egl \
            wavpack \
            yajl \
            zlib \
            texturepacker-native \
            \
            gstreamer1.0 \
            gstreamer1.0-plugins-base \
          "

#SRCREV = "ded117bbd636fc88802599a590e26b1d0fd7c609" #18.3
#SRCREV = "61d162be4091bf7154214c8422abd0fdf6cedc45" #18.4
#SRCREV = "103415d16038a57f59842cac72d4929389f224a9" #18.5
#SRCREV = "8e967df9218279618bcbfa8a898d8f80f7b4e449" #18.6
#SRCREV = "0442d7060875ff5da7d028dea918054b28d6c80a" #18.7
SRCREV = "45686bddb1f308ec580f97eb4b228b8a6606b320"

# 'patch' doesn't support binary diffs
PATCHTOOL = "git"

PR = "r15"

PV = "18.8-gitr${SRCPV}"
SRC_URI = "git://github.com/xbmc/xbmc.git;protocol=https;branch=Leia \
           \
           file://0001-Add-support-for-musl-triplets.patch \
           file://0004-Replace-u_int64_t-with-uint64_t-from-stdint.h.patch \
           \
           file://0005-estuary-move-recently-added-entries-to-the-top-in-ho.patch \
           file://0006-kodi.sh-set-mesa-debug.patch \
           file://0007-peripheral-settings-export-CEC-device_name-in-GUI.patch \
           file://0010-flatbuffers.patch \
           file://0011-WIP-windowing-gbm-add-option-to-limit-gui-size.patch \
           \
           file://PR15286-shader-nopow.patch \
           file://15941.patch \
           \
           file://stb-support.patch \
           file://stb-settings.patch \
           file://e2player.patch \
           file://0001-introduce-basic-GstPlayer.patch \
           file://0001-add-find-GLIB.patch \
           file://0001-fix-build-with-crossguid-0.2.x.patch \
          "

SRC_URI_append_libc-musl = " \
           file://0002-Fix-file_Emu-on-musl.patch \
           file://0003-Remove-FILEWRAP.patch \
"

S = "${WORKDIR}/git"

ACCEL ?= ""
ACCEL_x86 = "vaapi vdpau"
ACCEL_x86-64 = "vaapi vdpau"
ACCEL_arm = "openglesv2"

# Default to GBM everywhere, sucks to be nvidia
WINDOWSYSTEM ?= "stb"

PACKAGECONFIG ??= "${ACCEL} ${WINDOWSYSTEM} pulseaudio lcms lto \
                   ${@bb.utils.contains('DISTRO_FEATURES', 'x11', 'x11', '', d)}"

# Core windowing system choices

PACKAGECONFIG[x11] = "-DCORE_PLATFORM_NAME=x11,,libxinerama libxmu libxrandr libxtst glew"
PACKAGECONFIG[gbm] = "-DCORE_PLATFORM_NAME=gbm -DGBM_RENDER_SYSTEM=gles,,"
PACKAGECONFIG[stb] = "-DCORE_PLATFORM_NAME=stb,,"
PACKAGECONFIG[raspberrypi] = "-DCORE_PLATFORM_NAME=rbpi,,userland"
PACKAGECONFIG[amlogic] = "-DCORE_PLATFORM_NAME=aml,,"
PACKAGECONFIG[wayland] = "-DCORE_PLATFORM_NAME=wayland -DWAYLAND_RENDER_SYSTEM=gles,,wayland waylandpp"

PACKAGECONFIG[opengl] = "-DENABLE_OPENGL=ON,,"
PACKAGECONFIG[openglesv2] = "-DENABLE_GLES=ON,,virtual/egl"

PACKAGECONFIG[vaapi] = "-DENABLE_VAAPI=ON,-DENABLE_VAAPI=OFF,libva"
PACKAGECONFIG[vdpau] = "-DENABLE_VDPAU=ON,-DENABLE_VDPAU=OFF,libvdpau"
PACKAGECONFIG[mysql] = "-DENABLE_MYSQLCLIENT=ON,-DENABLE_MYSQLCLIENT=OFF,mysql5"
PACKAGECONFIG[pulseaudio] = "-DENABLE_PULSEAUDIO=ON,-DENABLE_PULSEAUDIO=OFF,pulseaudio"
PACKAGECONFIG[lcms] = ",,lcms"

# Compilation tunes

PACKAGECONFIG[gold] = "-DENABLE_LDGOLD=ON,-DENABLE_LDGOLD=OFF"
PACKAGECONFIG[lto] = "-DUSE_LTO=${@oe.utils.cpu_count()},-DUSE_LTO=OFF"

LDFLAGS += "${TOOLCHAIN_OPTIONS}"
LDFLAGS_append_mips = " -latomic"
LDFLAGS_append_mipsel = " -latomic"
LDFLAGS_append_mips64 = " -latomic"
LDFLAGS_append_mips64el = " -latomic"

KODI_ARCH = ""
KODI_ARCH_mips = "-DWITH_ARCH=${TARGET_ARCH}"
KODI_ARCH_mipsel = "-DWITH_ARCH=${TARGET_ARCH}"
KODI_ARCH_mips64 = "-DWITH_ARCH=${TARGET_ARCH}"
KODI_ARCH_mips64el = "-DWITH_ARCH=${TARGET_ARCH}"

KODI_DISABLE_INTERNAL_LIBRARIES = " \
  -DENABLE_INTERNAL_CROSSGUID=OFF \
  -DENABLE_INTERNAL_FLATBUFFERS=OFF \
  -DENABLE_INTERNAL_FMT=OFF \
  -DENABLE_INTERNAL_FSTRCMP=0 \
  -DENABLE_INTERNAL_RapidJSON=OFF \
  -DENABLE_INTERNAL_FFMPEG=OFF \
"

EXTRA_OECMAKE = " \
    ${KODI_ARCH} \
    ${KODI_DISABLE_INTERNAL_LIBRARIES} \
    \
    -DNATIVEPREFIX=${STAGING_DIR_NATIVE}${prefix} \
    -DJava_JAVA_EXECUTABLE=/usr/bin/java \
    -DWITH_TEXTUREPACKER=${STAGING_BINDIR_NATIVE}/TexturePacker \
    -DWITH_JSONSCHEMABUILDER=${STAGING_BINDIR_NATIVE}/JsonSchemaBuilder \
    \
    -DCMAKE_NM='${NM}' \
    \
    -DFFMPEG_PATH=${STAGING_DIR_TARGET} \
    -DLIBDVD_INCLUDE_DIRS=${STAGING_INCDIR} \
    -DNFS_INCLUDE_DIR=${STAGING_INCDIR} \
    -DSHAIRPLAY_INCLUDE_DIR=${STAGING_INCDIR} \
    \
    -DENABLE_AIRTUNES=ON \
    -DENABLE_OPTICAL=OFF \
    -DENABLE_DVDCSS=OFF \
    -DENABLE_DEBUGFISSION=OFF \
    -DCMAKE_BUILD_TYPE=RelWithDebInfo \
"

# OECMAKE_GENERATOR="Unix Makefiles"
# PARALLEL_MAKE = " "

FULL_OPTIMIZATION_armv7a = "-fexpensive-optimizations -fomit-frame-pointer -O3 -ffast-math"
FULL_OPTIMIZATION_armv7ve = "-fexpensive-optimizations -fomit-frame-pointer -O3 -ffast-math"
BUILD_OPTIMIZATION = "${FULL_OPTIMIZATION}"

# for python modules
export HOST_SYS
export BUILD_SYS
export STAGING_LIBDIR
export STAGING_INCDIR
export PYTHON_DIR

export TARGET_PREFIX

do_configure_prepend() {
    # Ensure 'nm' can find the lto plugins
    liblto=$(find ${STAGING_DIR_NATIVE} -name "liblto_plugin.so.0.0.0")
    mkdir -p ${STAGING_LIBDIR_NATIVE}/bfd-plugins
    ln -sf $liblto ${STAGING_LIBDIR_NATIVE}/bfd-plugins/liblto_plugin.so

    sed -i -e 's:CMAKE_NM}:}${TARGET_PREFIX}gcc-nm:' ${S}/xbmc/cores/DllLoader/exports/CMakeLists.txt
}

INSANE_SKIP_${PN} = "rpaths already-stripped"

FILES_${PN} = "${libdir}/kodi ${libdir}/xbmc"
FILES_${PN} += "${bindir}/kodi ${bindir}/xbmc"
FILES_${PN} += "${datadir}/icons ${datadir}/kodi ${datadir}/xbmc ${datadir}/applications"
FILES_${PN} += "${bindir}/kodi-standalone ${bindir}/xbmc-standalone ${datadir}/xsessions"
FILES_${PN} += "${libdir}/firewalld"
FILES_${PN}-dev = "${includedir}"
FILES_${PN}-dbg += "${libdir}/kodi/.debug ${libdir}/kodi/*/.debug ${libdir}/kodi/*/*/.debug ${libdir}/kodi/*/*/*/.debug"

# kodi uses some kind of dlopen() method for libcec so we need to add it manually
# OpenGL builds need glxinfo, that's in mesa-demos
RRECOMMENDS_${PN}_append = " libcec \
                             libcurl \
                             libnfs \
                             nss \
                             os-release \
                             ${@bb.utils.contains('PACKAGECONFIG', 'x11', 'xdyinfo xrandr xinit mesa-demos', '', d)} \
                             python \
                             python-ctypes \
                             python-lang \
                             python-re \
                             python-netclient \
                             python-html \
                             python-difflib \
                             python-json \
                             python-zlib \
                             python-shell \
                             python-sqlite3 \
                             python-compression \
                             python-xmlrpc \
                             python-pycryptodomex \
                             python-profile \
                             tzdata-africa \
                             tzdata-americas \
                             tzdata-antarctica \
                             tzdata-arctic \
                             tzdata-asia \
                             tzdata-atlantic \
                             tzdata-australia \
                             tzdata-europe \
                             tzdata-pacific \
                             xkeyboard-config \
                             kodi-addon-inputstream-adaptive \
                             kodi-addon-inputstream-rtmp \
                             alsa-plugins \
                           "

RRECOMMENDS_${PN}_append_libc-glibc = " glibc-charmap-ibm850 \
                                        glibc-gconv-ibm850 \
                                        glibc-charmap-ibm437 \
                                        glibc-gconv-ibm437 \
                                        glibc-gconv-unicode \
                                        glibc-gconv-utf-32 \
                                        glibc-charmap-utf-8 \
                                        glibc-localedata-en-us \
                                      "

repository: neutrino-hd/meta-neutrino

repo_name: neutrino-hd/meta-neutrino

branch_name: refs/heads/dunfell

gha_language: BitBake


text:
package api

import (
	"errors"
	"gf-vue-admin/library/response"
	model "gf-vue-admin/app/model/system"
	"gf-vue-admin/app/model/system/request"
	service "gf-vue-admin/app/service/system"
	"gf-vue-admin/library/global"
	"github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"time"
)

var GfJWTMiddleware *jwt.GfJWTMiddleware

func init() {
	GfJWTMiddleware, _ = jwt.New(&jwt.GfJWTMiddleware{
		Realm:           global.Config.Jwt.SigningKey,
		Key:             []byte(global.Config.Jwt.SigningKey),
		Timeout:         time.Duration(global.Config.Jwt.ExpiresAt) * time.Hour * 24,
		MaxRefresh:      time.Duration(global.Config.Jwt.RefreshAt) * time.Hour * 24,
		IdentityKey:     "admin_id",
		TokenLookup:     "header:Authorization, query:token, cookie:jwt",
		TokenHeadName:   "Bearer",
		TimeFunc:        time.Now,
		Authenticator:   Authenticator,
		LoginResponse:   LoginResponse,
		RefreshResponse: RefreshResponse,
		Unauthorized:    Unauthorized,
		IdentityHandler: IdentityHandler,
		PayloadFunc:     PayloadFunc,
	})
}

func PayloadFunc(data interface{}) jwt.MapClaims {
	claims := jwt.MapClaims{}
	params := data.(map[string]interface{})
	if len(params) > 0 {
		for k, v := range params {
			claims[k] = v
		}
	}
	return claims
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@description: 设置JWT的身份。
func IdentityHandler(r *ghttp.Request) interface{} {
	claims := jwt.ExtractClaims(r)
	return claims[GfJWTMiddleware.IdentityKey]
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@description: 用于定义自定义的未经授权的回调函数。
func Unauthorized(r *ghttp.Request, code int, message string) {
	_ = r.Response.WriteJson(&response.Response{Code: 7, Data: g.Map{"reload": true}, Message: "未登录或非法访问或" + message})
	r.ExitAll()
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@description: 用于定义自定义的登录成功回调函数
func LoginResponse(r *ghttp.Request, code int, token string, expire time.Time) {
	claims := r.GetParam("admin")
	data, ok := claims.(*model.Admin)
	r.SetParam("claims", data) // 设置参数保存到请求中
	if !ok {
		_ = r.Response.WriteJson(&response.Response{Code: 7, Message: "登录失败!"})
		r.Exit()
	}
	if !global.Config.System.UseMultipoint {
		_ = r.Response.WriteJson(&response.Response{Code: 0, Data: g.Map{"user": data, "token": token, "expiresAt": expire.Unix() * 1000}, Message: "登录成功!"})
		r.Exit()
	}
	redisJwt, err := service.JwtBlacklist.GetRedisJWT(data.Uuid)
	if redisJwt == "" {
		if err = service.JwtBlacklist.SetRedisJWT(data.Uuid, token); err != nil {
			_ = r.Response.WriteJson(&response.Response{Code: 7, Error: err, Message: "设置登录状态失败!"})
			r.Exit()
		}
		_ = r.Response.WriteJson(&response.Response{Code: 0, Data: g.Map{"user": data, "token": token, "expiresAt": expire.Unix() * 1000}, Message: "登录成功!"})
		r.Exit()
	}
	if err = service.JwtBlacklist.JwtToBlacklist(redisJwt); err != nil {
		_ = r.Response.WriteJson(&response.Response{Code: 7, Error: err, Message: "jwt作废失败!"})
		r.Exit()
	}
	if err = service.JwtBlacklist.SetRedisJWT(data.Uuid, token); err != nil {
		_ = r.Response.WriteJson(&response.Response{Code: 7, Error: err, Message: "设置登录状态失败!"})
		r.Exit()
	}
	_ = r.Response.WriteJson(&response.Response{Code: 0, Data: g.Map{"user": data, "token": token, "expiresAt": expire.Unix() * 1000}, Message: "登录成功!"})
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@description: 用于获取新令牌，无论当前令牌是否过期。
func RefreshResponse(r *ghttp.Request, code int, token string, expire time.Time) {
	//if service.IsBlacklist(token) {
	//	global.Result(r, global.ERROR, g.Map{"reload": true}, "您的帐户异地登陆或令牌失效")
	//	r.ExitAll()
	//}
	//Token, err := GfJWTMiddleware.ParseToken(r) // 解析token
	//if err != nil {
	//	global.FailWithMessage(r, "Token不正确,更新失败")
	//	r.Exit()
	//}
	//var (
	//	claims   = gconv.Map(Token.Claims)
	//	redisJwt string
	//	admin    *admins.AdminHasOneAuthority
	//)
	//admin, err = service.FindAdmin(gconv.String(claims["admin_uuid"]))
	//if err != nil {
	//	global.FailWithMessage(r, "刷新Token失败")
	//	r.Exit()
	//}
	//if !g.Cfg("system").GetBool("system.UseMultipoint") {
	//	global.OkDetailed(r, response.AdminLogin{User: admin, Token: token, ExpiresAt: expire.Unix() * 1000}, "登录成功!")
	//	r.Exit()
	//}
	//if redisJwt, err = service.GetRedisJWT(admin.Uuid); err != nil {
	//	global.FailWithMessage(r, "刷新Token失败")
	//	r.Exit()
	//}
	//if err == nil && redisJwt != "" {
	//	if err = service.JsonInBlacklist(&jwts.Entity{Jwt: redisJwt}); err != nil {
	//		global.Result(r, code, g.Map{}, "jwt作废失败")
	//		r.Exit()
	//	}
	//	if err := service.SetRedisJWT(admin.Uuid, token); err != nil {
	//		global.Result(r, code, g.Map{}, "设置登录状态失败")
	//		r.Exit()
	//	}
	//}
	//global.OkDetailed(r, response.AdminLogin{User: admin, Token: token, ExpiresAt: expire.Unix() * 1000}, "登录成功!")
	r.ExitAll()
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@description: 用于验证登录参数。 它必须返回用户数据作为用户标识符，并将其存储在Claim Array中。 检查错误（e），以确定适当的错误消息。
func Authenticator(r *ghttp.Request) (interface{}, error) {
	var info request.AdminLogin
	if err := r.Parse(&info); err != nil {
		_ = r.Response.WriteJson(&response.Response{Code: 7, Error: err, Message: err.Error()})
		r.Exit()
	}
	if !service.Store.Verify(info.CaptchaId, info.Captcha, true) { // 验证码校对
		return nil, errors.New("验证码错误! ")
	}
	if data, err := service.Admin.Login(&info); err != nil {
		_ = r.Response.WriteJson(&response.Response{Code: 7, Error: err, Err: err.Error()})
		r.ExitAll()
		return nil, nil
	} else {
		r.SetParam("admin", data) // 设置参数保存到请求中
		return g.Map{"admin_uuid": data.Uuid, "admin_id": data.ID, "admin_nickname": data.Nickname, "admin_authority_id": data.AuthorityId}, nil
	}
}

repository: SanFenZuiCom/gf-vue-admin

repo_name: SanFenZuiCom/gf-vue-admin


text:
package discordgoext

import (
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"github.com/bwmarrin/discordgo"
)

// A Context struct holds variables for Messages
type Context struct {
	Invoked string
	Argstr  string
	Args    []string
	Channel *discordgo.Channel
	Guild   *discordgo.Guild
	Mess    *discordgo.MessageCreate
	Sess    *ExtSession
}

// SendEmbed is a helper function to easily send embeds.
// em: embed to send
func (ctx *Context) SendEmbed(em *discordgo.MessageEmbed) (*discordgo.Message, error) {
	m, err := ctx.Sess.ChannelMessageSendEmbed(ctx.Mess.ChannelID, em)
	return m, err
}

// QuickSendEmbed is a helper function to easily send strings as an embed.
// s: string to send
func (ctx *Context) QuickSendEmbed(s string) (*discordgo.Message, error) {
	em := ctx.Sess.CreateEmbed(ctx)
	em.Description = s
	return ctx.SendEmbed(em)
}

// SendMessage sends a message to the channel the command came from.
// em: embed to send
func (ctx *Context) SendMessage(s string) (*discordgo.Message, error) {
	return ctx.Sess.ChannelMessageSend(ctx.Mess.ChannelID, s)
}

// ErrUserFinding is the error it gives when more than 1 or no users are found, used to return commands.
var ErrUserFinding = errors.New("Found more than 1 or no users")

func removeDuplicateUsers(list *[]*discordgo.User) {
	found := make(map[string]bool)
	j := 0
	for i, x := range *list {
		if !found[x.ID] {
			found[x.ID] = true
			(*list)[j] = (*list)[i]
			j++
		}
	}
	*list = (*list)[:j]
}

// GetAllUsers is a helper function to return all members
func (ctx *Context) GetAllUsers() (ms []*discordgo.User, err error) {
	servers, err := ctx.Sess.UserGuilds(100, "", "")
	if err != nil {
		return
	}
	for _, server := range servers {
		var g *discordgo.Guild
		g, err = ctx.Sess.State.Guild(server.ID)
		if err != nil {
			continue
		}
		for _, m := range g.Members {
			ms = append(ms, m.User)
		}
	}
	removeDuplicateUsers(&ms)
	return
}

// GetUserByName is a helper function to find a User by string
// query: String to use when finding User
func (ctx *Context) GetUserByName(query string) (members []*discordgo.User, err error) {
	MentionRegex := regexp.MustCompile(`<@!?(\d+)>`)
	var id, discrim string
	if MentionRegex.MatchString(query) {
		id = MentionRegex.FindStringSubmatch(query)[1]
	} else if regexp.MustCompile(`^.*#\d{4}$`).MatchString(query) {
		discrim = query[len(query)-4:]
		query = strings.TrimSpace(query[:len(query)-5])
	}
	var exact, wrongcase, startswith, contains, all []*discordgo.User
	lowerQuery := strings.ToLower(query)
	all, err = ctx.GetAllUsers()
	if err != nil {
		return
	}
	for _, u := range all {
		if id != "" && u.ID == id {
			exact = append(exact, u)
			break
		}
		if discrim != "" && u.Discriminator != discrim {
			continue
		}
		if u.Username == query {
			exact = append(exact, u)
		} else if len(exact) == 0 && strings.ToLower(u.Username) == lowerQuery {
			wrongcase = append(wrongcase, u)
		} else if len(wrongcase) == 0 && strings.HasPrefix(strings.ToLower(u.Username), lowerQuery) {
			startswith = append(startswith, u)
		} else if len(startswith) == 0 && strings.Contains(strings.ToLower(u.Username), lowerQuery) {
			contains = append(contains, u)
		}
	}
	if len(exact) != 0 {
		members = exact
	} else if len(wrongcase) != 0 {
		members = wrongcase
	} else if len(startswith) != 0 {
		members = startswith
	} else {
		members = contains
	}
	return
}

// GuildGetUserByName is a helper function to find a User by string in a guild
// query: String to use when finding User
// GuildID: ID for guild
func (ctx *Context) GuildGetUserByName(query, GuildID string) (members []*discordgo.User, err error) {
	MentionRegex := regexp.MustCompile(`<@!?(\d+)>`)
	var id, discrim string
	if MentionRegex.MatchString(query) {
		id = MentionRegex.FindStringSubmatch(query)[1]
	} else if regexp.MustCompile(`^.*#\d{4}$`).MatchString(query) {
		discrim = query[len(query)-4:]
		query = strings.TrimSpace(query[:len(query)-5])
	}
	var exact, wrongcase, startswith, contains []*discordgo.User
	var all []*discordgo.Member
	lowerQuery := strings.ToLower(query)
	g, err := ctx.Sess.State.Guild(GuildID)
	if err != nil {
		return
	}
	all = g.Members
	if err != nil {
		return
	}
	for _, m := range all {
		nick := m.Nick
		u := m.User
		if id != "" && u.ID == id {
			exact = append(exact, u)
			break
		}
		if discrim != "" && u.Discriminator != discrim {
			continue
		}
		if u.Username == query || (nick != "" && nick == query) {
			exact = append(exact, u)
		} else if len(exact) == 0 && strings.ToLower(u.Username) == lowerQuery || (nick != "" && strings.ToLower(nick) == lowerQuery) {
			wrongcase = append(wrongcase, u)
		} else if len(wrongcase) == 0 && strings.HasPrefix(strings.ToLower(u.Username), lowerQuery) || (nick != "" && strings.HasPrefix(strings.ToLower(nick), lowerQuery)) {
			startswith = append(startswith, u)
		} else if len(startswith) == 0 && strings.Contains(strings.ToLower(u.Username), lowerQuery) || (nick != "" && strings.Contains(strings.ToLower(nick), lowerQuery)) {
			contains = append(contains, u)
		}
	}
	if len(exact) != 0 {
		members = exact
	} else if len(wrongcase) != 0 {
		members = wrongcase
	} else if len(startswith) != 0 {
		members = startswith
	} else {
		members = contains
	}
	return
}

// ParseTooManyUsers is a helper function to create a message for finding too many users
// query: String used when finding User
// users: List of users found
func (ctx *Context) ParseTooManyUsers(query string, users []*discordgo.User) (*discordgo.Message, error) {
	out := fmt.Sprintf("Multiple users found for query **%s**:", query)
	for i := 0; i < 6; i++ {
		if i < len(users) {
			out += "\n - " + users[i].Username + " #" + users[i].Discriminator
		}
	}
	if len(users) > 6 {
		out += "\n**And " + strconv.Itoa(len(users)-6) + " more...**"
	}
	return ctx.SendMessage(out)
}

// GetUser is a helper function to get a user by name
func (ctx *Context) GetUser(args ...string) (user *discordgo.User, err error) {
	var query, gid string
	var users []*discordgo.User

	query = args[0]

	if len(args) > 1 {
		gid = args[1]
	}

	if gid != "" {
		users, err = ctx.GuildGetUserByName(query, gid)
		if err != nil {
			ctx.SendMessage("Error collecting users: " + err.Error())
			return
		}
		if len(users) < 1 {
			users, err = ctx.GetUserByName(query)
			if len(users) < 1 {
				ctx.SendMessage("No user found with name **" + query + "**")
				err = ErrUserFinding
				return
			}
			if err != nil {
				ctx.SendMessage("Error collecting users: " + err.Error())
				return
			}
		}
		if len(users) > 1 {
			ctx.ParseTooManyUsers(query, users)
			err = ErrUserFinding
			return
		}
		user = users[0]
	} else {
		users, err = ctx.GetUserByName(query)
		if err != nil {
			ctx.SendMessage("Error collecting users: " + err.Error())
			return
		}
		if len(users) < 1 {
			ctx.SendMessage("No user found with name **" + query + "**")
			err = ErrUserFinding
			return
		}
		if len(users) > 1 {
			ctx.ParseTooManyUsers(query, users)
			err = ErrUserFinding
			return
		}
		user = users[0]
	}
	if len(users) > 1 {
		ctx.ParseTooManyUsers(query, users)
		err = ErrUserFinding
		return
	}
	return
}

repository: CyberFlameGO/discordgoext

repo_name: CyberFlameGO/discordgoext


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

package user_meta_service

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

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"
	"github.com/go-openapi/strfmt"

	"github.com/pydio/cells-sdk-go/v3/models"
)

// UpdateUserMetaNamespaceReader is a Reader for the UpdateUserMetaNamespace structure.
type UpdateUserMetaNamespaceReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *UpdateUserMetaNamespaceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {
	case 200:
		result := NewUpdateUserMetaNamespaceOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil
	case 401:
		result := NewUpdateUserMetaNamespaceUnauthorized()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 403:
		result := NewUpdateUserMetaNamespaceForbidden()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 404:
		result := NewUpdateUserMetaNamespaceNotFound()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 500:
		result := NewUpdateUserMetaNamespaceInternalServerError()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	default:
		return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
	}
}

// NewUpdateUserMetaNamespaceOK creates a UpdateUserMetaNamespaceOK with default headers values
func NewUpdateUserMetaNamespaceOK() *UpdateUserMetaNamespaceOK {
	return &UpdateUserMetaNamespaceOK{}
}

/* UpdateUserMetaNamespaceOK describes a response with status code 200, with default header values.

UpdateUserMetaNamespaceOK update user meta namespace o k
*/
type UpdateUserMetaNamespaceOK struct {
	Payload *models.IdmUpdateUserMetaNamespaceResponse
}

func (o *UpdateUserMetaNamespaceOK) Error() string {
	return fmt.Sprintf("[PUT /user-meta/namespace][%d] updateUserMetaNamespaceOK  %+v", 200, o.Payload)
}
func (o *UpdateUserMetaNamespaceOK) GetPayload() *models.IdmUpdateUserMetaNamespaceResponse {
	return o.Payload
}

func (o *UpdateUserMetaNamespaceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.IdmUpdateUserMetaNamespaceResponse)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewUpdateUserMetaNamespaceUnauthorized creates a UpdateUserMetaNamespaceUnauthorized with default headers values
func NewUpdateUserMetaNamespaceUnauthorized() *UpdateUserMetaNamespaceUnauthorized {
	return &UpdateUserMetaNamespaceUnauthorized{}
}

/* UpdateUserMetaNamespaceUnauthorized describes a response with status code 401, with default header values.

User is not authenticated
*/
type UpdateUserMetaNamespaceUnauthorized struct {
}

func (o *UpdateUserMetaNamespaceUnauthorized) Error() string {
	return fmt.Sprintf("[PUT /user-meta/namespace][%d] updateUserMetaNamespaceUnauthorized ", 401)
}

func (o *UpdateUserMetaNamespaceUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	return nil
}

// NewUpdateUserMetaNamespaceForbidden creates a UpdateUserMetaNamespaceForbidden with default headers values
func NewUpdateUserMetaNamespaceForbidden() *UpdateUserMetaNamespaceForbidden {
	return &UpdateUserMetaNamespaceForbidden{}
}

/* UpdateUserMetaNamespaceForbidden describes a response with status code 403, with default header values.

User has no permission to access this resource
*/
type UpdateUserMetaNamespaceForbidden struct {
	Payload *models.RestError
}

func (o *UpdateUserMetaNamespaceForbidden) Error() string {
	return fmt.Sprintf("[PUT /user-meta/namespace][%d] updateUserMetaNamespaceForbidden  %+v", 403, o.Payload)
}
func (o *UpdateUserMetaNamespaceForbidden) GetPayload() *models.RestError {
	return o.Payload
}

func (o *UpdateUserMetaNamespaceForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.RestError)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewUpdateUserMetaNamespaceNotFound creates a UpdateUserMetaNamespaceNotFound with default headers values
func NewUpdateUserMetaNamespaceNotFound() *UpdateUserMetaNamespaceNotFound {
	return &UpdateUserMetaNamespaceNotFound{}
}

/* UpdateUserMetaNamespaceNotFound describes a response with status code 404, with default header values.

Resource does not exist in the system
*/
type UpdateUserMetaNamespaceNotFound struct {
	Payload *models.RestError
}

func (o *UpdateUserMetaNamespaceNotFound) Error() string {
	return fmt.Sprintf("[PUT /user-meta/namespace][%d] updateUserMetaNamespaceNotFound  %+v", 404, o.Payload)
}
func (o *UpdateUserMetaNamespaceNotFound) GetPayload() *models.RestError {
	return o.Payload
}

func (o *UpdateUserMetaNamespaceNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.RestError)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewUpdateUserMetaNamespaceInternalServerError creates a UpdateUserMetaNamespaceInternalServerError with default headers values
func NewUpdateUserMetaNamespaceInternalServerError() *UpdateUserMetaNamespaceInternalServerError {
	return &UpdateUserMetaNamespaceInternalServerError{}
}

/* UpdateUserMetaNamespaceInternalServerError describes a response with status code 500, with default header values.

An internal error occurred in the backend
*/
type UpdateUserMetaNamespaceInternalServerError struct {
	Payload *models.RestError
}

func (o *UpdateUserMetaNamespaceInternalServerError) Error() string {
	return fmt.Sprintf("[PUT /user-meta/namespace][%d] updateUserMetaNamespaceInternalServerError  %+v", 500, o.Payload)
}
func (o *UpdateUserMetaNamespaceInternalServerError) GetPayload() *models.RestError {
	return o.Payload
}

func (o *UpdateUserMetaNamespaceInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.RestError)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

repository: pydio/cells-sdk-go

repo_name: pydio/cells-sdk-go


text:
HOMEPAGE = "https://github.com/docker/compose"
SUMMARY = "Define and run multi-container applications with Docker"
DESCRIPTION = "Docker Compose is a tool for running multi-container \
 applications on Docker defined using the Compose file format."
SECTION = "devel"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://src/${GO_IMPORT}/LICENSE;md5=175792518e4ac015ab6696d16c4f607e"

SRC_URI = "\
	git://github.com/docker/compose.git;branch=main;protocol=https;name=compose \
	git://github.com/docker/cli.git;branch=24.0;protocol=https;name=cli;destsuffix=${S}/src/github.com/docker/cli \
	"

SRCREV_compose = "8318f66330358988a058bf611a953f464ab7973f"
SRCREV_cli = "3713ee1eea0447bcfe27378ad247c7e245406f04"
SRCREV_FORMAT = "compose_cli"

UPSTREAM_CHECK_COMMITS = "1"

GO_IMPORT = "github.com/docker/compose/v2"

inherit go-mod

GO_EXTRA_LDFLAGS = "-w -X ${GO_IMPORT}/internal.Version=${PV}"

go_do_compile() {
	export TMPDIR="${GOTMPDIR}"
	mkdir -p ${B}/cli-plugins/bin
	${GO} mod download -modcacherw
	cp -f ${S}/src/github.com/docker/cli/cli/config/config.go ${B}/pkg/mod/github.com/docker/cli@v24.0.4+incompatible/cli/config/config.go
	# remove prebuilt binaries to avoid qa issues
	rm -f ${B}/pkg/mod/github.com/laurazard/godog*/bin/staticcheck*
	rm -f ${B}/pkg/mod/github.com/in-toto/in-toto-golang*/test/data/helloworld
	${GO} build ${GOBUILDFLAGS} -o ${B}/cli-plugins/bin/docker-compose ./cmd
}

go_do_install:append() {
	install -d ${D}${libdir}/docker/cli-plugins
	install -m 755 ${B}/cli-plugins/bin/docker-compose ${D}${libdir}/docker/cli-plugins
}

FILES:${PN} += "${libdir}/docker/cli-plugins"

RDEPENDS:${PN} += "docker"

repository: foundriesio/meta-lmp

repo_name: foundriesio/meta-lmp

gha_license_id: MIT


text:
@article{tsuchiya2019ord,
  title={Semi-Supervised Ordinal Regression Based on Empirical Risk Minimization},
  author={Tsuchiya, T. and Charoenphakdee, N. and Sato, I. and Sugiyama, M.},
  journal={arXiv preprint arXiv:1901.11351},
  year={2019},
  order={3},
  arxiv={1901.11351}
}
@article{ni2019rejection,
  title={On Possibility and Impossibility of Multiclass Classification with Rejection},
  author={Ni, C. and Charoenphakdee, N. and Honda, J. and Sugiyama, M.},
  journal={arXiv preprint arXiv:1901.10655},
  year={2019},
  order={2},
  arxiv={1901.10655}
}

@article{lee2019adaptation,
  title={Domain Discrepancy Measure Using Complex Models in Unsupervised Domain Adaptation},
  author={Lee, J. and Charoenphakdee, N. and Kuroki, S. and Sugiyama, M.},
  journal={arXiv preprint arXiv:1901.10654},
  year={2019},
  order={1},
  arxiv={1901.10654}
}

repository: nolfwin/al-folio

repo_name: nolfwin/al-folio


text:
package jitter

import (
	scrap "github.com/zairza-cetb/bench-routes/src/lib/filters/scraps"
	"github.com/zairza-cetb/bench-routes/src/lib/utils"
	"github.com/zairza-cetb/bench-routes/tsdb"
	"log"
	"strconv"
	"sync"
)

const (
	// PathJitter stores the defualt address of storage directory of jitter data
	PathJitter = "storage/jitter"
)

//HandleJitter handles the url and calculate the jitter for that url
func HandleJitter(globalChain []*tsdb.Chain, url string, packets int, tsdbNameHash string, wg *sync.WaitGroup, isTest bool) {
	tsdbNameHash = PathJitter + "/" + "chunk_jitter_" + tsdbNameHash + ".json"
	resp, err := utils.CLIPing(url, packets)
	if err != nil {
		log.Printf("Failure occured for %s", url)
		wg.Done()
		return
	}
	result := scrap.CLIJitterScrap(resp)
	newBlock := *tsdb.GetNewBlock("jitter", fToS(result))
	urlExists := false
	for index := range globalChain {
		if globalChain[index].Path == tsdbNameHash {
			urlExists = true
			globalChain[index] = globalChain[index].Append(newBlock)
			globalChain[index].Commit()
			break
		}
	}
	if !urlExists && !isTest {
		panic("faulty hashing! impossible to look for a hash match.")
	}
	wg.Done()
}

func fToS(v float64) string {
	return strconv.FormatFloat(v, 'f', 6, 64)
}


text:
require ${BPN}.inc

PR = "${INC_PR}.0"

SRC_URI += "file://0001-Use-proc-self-exe-for-swig-swiglib-on-non-Win32-plat.patch"

SRC_URI[md5sum] = "6d5e7ad05b4a404e5e85db9befb70c9a"
SRC_URI[sha256sum] = "d1eef329e867124ce60838b5ad07c763146b6c8f250dd22a861ead7406f78e63"

repository: ExorEmbedded/exor-workspace

repo_name: ExorEmbedded/exor-workspace

gha_language: Python


text:
set(HAVE_CXX_FILESYSTEM 0)
set(HAVE_CXX_EXPERIMENTAL_FILESYSTEM 0)
set(HAVE_BOOST_FILESYSTEM 0)
set(CXX_FILESYSTEM_LIBS)

file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/CMakeTemp/test_cxx_filesystem.cc
"#include <filesystem>\n"
"namespace fs = std::filesystem;\n"
"int main() {\n"
"  fs::path current{ \".\" };\n"
"  return 0;\n"
"}\n"
)
message(STATUS "Detecting CXX std::filesystem support")
try_compile(HAVE_CXX_FILESYSTEM
  ${CMAKE_CURRENT_BINARY_DIR}/CMakeTemp/HaveCxxFilesystem
  ${CMAKE_CURRENT_BINARY_DIR}/CMakeTemp/test_cxx_filesystem.cc
  CXX_STANDARD 17
  CXX_STANDARD_REQUIRED ON
  OUTPUT_VARIABLE OUTPUT
)
if (HAVE_CXX_FILESYSTEM)
  message(STATUS "Detecting CXX std::filesystem support -- found")
else ()
  message(STATUS "Detecting CXX std::filesystem support -- NOT FOUND")
endif ()

if (NOT HAVE_CXX_FILESYSTEM)
  file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/CMakeTemp/test_cxx_experimental_filesystem.cc
  "#include <experimental/filesystem>\n"
  "namespace fs = std::experimental::filesystem;\n"
  "int main() {\n"
  "  fs::path current{ \".\" };\n"
  "  return 0;\n"
  "}\n"
  )
  message(STATUS "Detecting CXX std::experimental::filesystem support")
  if (NOT MSVC)
    set(TEMP_FILESYSTEM_LIBS stdc++fs)
  endif ()
  try_compile(HAVE_CXX_EXPERIMENTAL_FILESYSTEM
    ${CMAKE_CURRENT_BINARY_DIR}/CMakeTemp/HaveCxxExperimentalFilesystem
    ${CMAKE_CURRENT_BINARY_DIR}/CMakeTemp/test_cxx_experimental_filesystem.cc
    CXX_STANDARD 17
    CXX_STANDARD_REQUIRED ON
    LINK_LIBRARIES ${TEMP_FILESYSTEM_LIBS}
    OUTPUT_VARIABLE OUTPUT
  )
  if (HAVE_CXX_EXPERIMENTAL_FILESYSTEM)
    set(CXX_FILESYSTEM_LIBS ${TEMP_FILESYSTEM_LIBS})
    message(STATUS "Detecting CXX std::experimental::filesystem support -- found")
  else ()
    message(STATUS "Detecting CXX std::experimental::filesystem support -- NOT FOUND")
  endif ()
endif ()

if (NOT HAVE_CXX_EXPERIMENTAL_FILESYSTEM)
  message(STATUS "Detecting CXX boost::filesystem support")
  find_package(Boost QUIET COMPONENTS filesystem system)
  if (Boost_FOUND STREQUAL "1")
    set(HAVE_BOOST_FILESYSTEM 1)
    set(CXX_FILESYSTEM_LIBS Boost::filesystem Boost::system)
    message(STATUS "Detecting CXX boost::filesystem support -- found")
  else ()
    message(STATUS "Detecting CXX boost::filesystem support -- NOT FOUND")
  endif ()
endif ()

repository: danyill/spaghetti

repo_name: danyill/spaghetti

extension: cmake


text:
package apostle

type Mail struct {
	Data       map[string]interface{} `json:"data"`
	Email      string                 `json:"-"`
	From       string                 `json:"from"`
	Headers    map[string][]string    `json:"headers"`
	LayoutId   string                 `json:"layout_id"`
	Name       string                 `json:"name"`
	ReplyTo    string                 `json:"reply_to"`
	TemplateId string                 `json:"template_id"`
}

func NewMail(t string, e string) (m Mail, err error) {
	if len(t) == 0 {
		err = NoTemplateError{}
		return
	}
	if len(e) == 0 {
		err = NoEmailError{}
		return
	}
	return Mail{
		TemplateId: t,
		Email:      e,
		Headers:    make(map[string][]string),
		Data:       make(map[string]interface{}),
	}, nil
}

func (m *Mail) Deliver() error {
	q := NewQueue()
	q.Add(*m)
	return q.Deliver()
}


text:
@online{smith_revolutions._nodate,
	title = {Revolutions. News about R, statistics and the world of open source from the staff of {REvolution} Computing},
	url = {http://blog.revolution-computing.com/},
	author = {Smith, David},
	urldate = {2009-03-13},
	keywords = {R software}
}

@online{sonego_one_nodate,
	title = {One R Tip A Day},
	url = {http://onertipaday.blogspot.com/},
	author = {Sonego, Paolo},
	urldate = {2009-03-13},
	keywords = {R software}
}

@article{vance_data_2009,
	title = {Data Analysts Captivated by R’s Power},
	issn = {0362-4331},
	url = {http://www.nytimes.com/2009/01/07/technology/business-computing/07program.html},
	journaltitle = {The New York Times},
	author = {Vance, Ashlee},
	urldate = {2009-01-07},
	date = {2009-01-07},
	keywords = {R software}
}


text:
DESCRIPTION = "GeographicLib is a small set of C++ classes for performing conversions between geographic, UTM, UPS, MGRS, geocentric, and local cartesian coordinates, for gravity (e.g., EGM2008), geoid height, and geomagnetic field (e.g., WMM2010) calculations, and for solving geodesic problems."
SECTION = "devel"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=beda1cf298e14fa7de56a07a83308905"

DEPENDS = ""

SRC_URI = "${SOURCEFORGE_MIRROR}/${BPN}/distrib/GeographicLib-${PV}.tar.gz"
SRC_URI[md5sum] = "e99153cf41bf64998cc4f91c00aea167"
SRC_URI[sha256sum] = "7203d56123b6f6fb31842295d57b2418f79fb0db9a06f2f65ee9e415c6f0cb70"

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

PACKAGE_BEFORE_PN += "${PN}-tools"

FILES:${PN}-tools = " \
    ${bindir} \
    ${sbindir} \
"

PACKAGES += "${PN}-matlab ${PN}-node ${PN}-python"
FILES:${PN}-matlab = "${datadir}/matlab"
FILES:${PN}-node = "${libdir}/node_modules"
FILES:${PN}-python = "${libdir}/python"

inherit cmake

# enable both shared and static libraries (static is required by robot-localization-2.6.9-1 in melodic)
# Ensure geographiclib is configured to the proper folder to look for data files.
EXTRA_OECMAKE += "-DGEOGRAPHICLIB_LIB_TYPE=BOTH -DGEOGRAPHICLIB_DATA=/usr/share/GeographicLib"

# stage bindir to keep CMake happy
# | -- Reading /jenkins/mjansa/build/ros/webos-melodic-hardknott/tmp-glibc/work/qemux86-webos-linux/robot-localization/2.6.9-1-r0/recipe-sysroot/usr/lib/cmake/GeographicLib/geographiclib-config.cmake
# | -- GeographicLib configuration, version 1.48
# | CMake Error at /jenkins/mjansa/build/ros/webos-melodic-hardknott/tmp-glibc/work/qemux86-webos-linux/robot-localization/2.6.9-1-r0/recipe-sysroot/usr/lib/cmake/GeographicLib/geographiclib-targets.cmake:123 (message):
# |   The imported target "CartConvert" references the file
# |
# |      "/jenkins/mjansa/build/ros/webos-melodic-hardknott/tmp-glibc/work/qemux86-webos-linux/robot-localization/2.6.9-1-r0/recipe-sysroot/usr/bin/CartConvert"
# |
# |   but this file does not exist.  Possible reasons include:
# OE doesn't stage ${bindir} for target recipes, but in this case the CartConvert isn't
# being called during the cross-build, so we can include it just to keep CMake happy
sysroot_stage_all:append() {
    sysroot_stage_dir ${D}${bindir} ${SYSROOT_DESTDIR}${bindir}
}

SRC_URI += "file://0001-Fix-build-with-gcc-11.patch"

repository: DasRoteSkelett/meta-ros

repo_name: DasRoteSkelett/meta-ros


text:
package main

import (
	"testing"
)

func TestParametrizedString(t *testing.T) {

	cases := []struct {
		inString, inTpl string
		inParams        []string
		want            string
	}{
		{"{0}|{1}", "{%d}", []string{"param0", "param1"}, "param0|param1"},
		{"{res0}|{res1}", "{res%d}", []string{"param0", "param1"}, "param0|param1"},
		{"{res1}|{res1}", "{res%d}", []string{"param0", "param1"}, "param1|param1"},
	}

	for _, c := range cases {
		got := parameterizedString(c.inString, c.inTpl, c.inParams)
		if got != c.want {
			t.Errorf("parametrizedString(%q, %q, %q) == %q, want %q", c.inString, c.inTpl, c.inParams, got, c.want)
		}
	}
}

func TestFormatRes(t *testing.T) {

	cases := []struct {
		inFormat, inInput, inCnn, inStatus string
		inValues                           []string
		want                               string
	}{
		{"", "", "", "success", []string{"param0", "param1"}, "param0\tparam1"},
		{"{status}|{res}", "", "", "success", []string{"param0", "param1"}, "success|param0\tparam1"},
		{"{res2};{res1};{res0}", "", "", "", []string{"param0", "param1"}, "{res2};param1;param0"},
		{"{input}|{res}|{cnn}|{status}|{res0}", "i", "cnn", "success", []string{"r0", "r1"}, "i|r0\tr1|cnn|success|r0"},
	}

	for _, c := range cases {
		got := formatRes(c.inFormat, c.inInput, c.inCnn, c.inStatus, c.inValues)
		if got != c.want {
			t.Errorf("formatRes(%q, %q, %q, %q, %q) == %q, want %q",
				c.inFormat, c.inInput, c.inCnn, c.inStatus, c.inValues, got, c.want)
		}
	}
}

func TestValidateArgs(t *testing.T) {

	var err error

	connectionStringArg = ""
	err = validateArgs()
	if err == nil || err.Error() != "'cnn' arg is required" {
		t.Errorf("validateArgs: 'cnn' is empty")
	}

	connectionStringArg = "validcnn"

	queryArg, execArg = "", ""
	err = validateArgs()
	if err == nil || err.Error() != "it should be one of the arguments 'query' or 'exec'" {
		t.Errorf("validateArgs: 'query' & 'exec' is empty")
	}

	queryArg, execArg = "validquery", ""
	err = validateArgs()
	if err != nil {
		t.Errorf("validateArgs: valid 'query' fail")
	}

	queryArg, execArg = "", "validexec"
	err = validateArgs()
	if err != nil {
		t.Errorf("validateArgs: valid 'exec' fail")
	}

	queryArg, execArg = "validquery", "validexec"
	err = validateArgs()
	if err == nil || err.Error() != "it should be only one of the arguments 'query' or 'exec'" {
		t.Errorf("validateArgs: given both args 'exec' & 'query'")
	}
}

repository: karamani/massquery

repo_name: karamani/massquery


text:
SUMMARY = "Photobooth Application"
DESCRIPTION = "Photobooth Application"

LICENSE = "CLOSED"

SRC_URI = " \
    file://CMakeLists.txt \
    file://hello.cpp \
    file://hello.h \
    file://main.cpp \
"

S = "${WORKDIR}"

inherit cmake

EXTRA_OECMAKE = ""

repository: chrusel/meta-photobooth

repo_name: chrusel/meta-photobooth


text:
@inproceedings{Wang:2015:AAD:2731186.2731202,
 author = {Wang, Hui and Isci, Canturk and Subramanian, Lavanya and Choi, Jongmoo and Qian, Depei and Mutlu, Onur},
 title = {A-DRM: Architecture-aware Distributed Resource Management of Virtualized Clusters},
 booktitle = {Proceedings of the 11th ACM SIGPLAN/SIGOPS International Conference on Virtual Execution Environments},
 series = {VEE '15},
 year = {2015},
 isbn = {978-1-4503-3450-1},
 location = {Istanbul, Turkey},
 pages = {93--106},
 numpages = {14},
 url = {http://doi.acm.org/10.1145/2731186.2731202},
 doi = {10.1145/2731186.2731202},
 acmid = {2731202},
 publisher = {ACM},
 address = {New York, NY, USA},
 keywords = {live migration, microarchitecture, performance counters, resource management, virtualization},
}


text:
SECTION = "openmoko/libs"
DEPENDS = "gtk+"
PV = "0.1.0+svnr${SRCREV}"
PR = "r2"

inherit openmoko2

LICENSE = "LGPL"

do_configure_prepend() {
        touch gtk-doc.make
}

do_stage() {
        autotools_stage_all
}


text:
@Article{Bayala_2014,
  doi = {10.1016/j.cosust.2013.10.004},
  url = {https://doi.org/10.1016/j.cosust.2013.10.004},
  year = {2014},
  month = {feb},
  publisher = {Elsevier {BV}},
  volume = {6},
  pages = {28--34},
  author = {J Bayala and J Sanou and Z Teklehaimanot and A Kalinganire and SJ Ou{\a'e}draogo},
  title = {Parklands for buffering climate risk and sustaining agricultural production in the Sahel of West Africa},
  journal = {Current Opinion in Environmental Sustainability},
}

@Article{D_AGNES_2010,
  doi = {10.1017/s0376892910000779},
  url = {https://doi.org/10.1017/s0376892910000779},
  year = {2010},
  month = {nov},
  publisher = {Cambridge University Press ({CUP})},
  volume = {37},
  number = {04},
  pages = {398--409},
  author = {LEONA D\textquotesingleAGNES and HEATHER D\textquotesingleAGNES and J. BRAD SCHWARTZ and MARIA LOURDES AMARILLO and JOAN CASTRO},
  title = {Integrated management of coastal resources and human health yields added value: a comparative study in Palawan (Philippines)},
  journal = {Envir. Conserv.},
}

@Article{Green_2010,
  doi = {10.1080/14888386.2010.9712649},
  url = {https://doi.org/10.1080/14888386.2010.9712649},
  year = {2010},
  month = {sep},
  publisher = {Informa {UK} Limited},
  volume = {11},
  number = {1-2},
  pages = {62--70},
  author = {Michael J.B. Green and Manoj Misra and Arun K. Bansal and R. Raghu Prasad},
  title = {Eco-development in Orissa{\textquotesingle}s protected areas: a participatory approach to conserving forest biodiversity and alleviating poverty piloted in Satkosia},
  journal = {Biodiversity},
}

@Article{Almeyda_2010,
  doi = {10.1002/jtr.797},
  url = {https://doi.org/10.1002/jtr.797},
  year = {2010},
  month = {nov},
  publisher = {Wiley-Blackwell},
  volume = {12},
  number = {6},
  pages = {803--819},
  author = {Angelica M. Almeyda and Eben N. Broadbent and Miriam S. Wyman and William H. Durham},
  title = {Ecotourism impacts in the Nicoya Peninsula, Costa Rica},
  journal = {International Journal of Tourism Research},
}

@Article{Bruyere_2008,
  doi = {10.1007/s00267-008-9190-7},
  url = {https://doi.org/10.1007/s00267-008-9190-7},
  year = {2008},
  month = {sep},
  publisher = {Springer Science $\mathplus$ Business Media},
  volume = {43},
  number = {1},
  pages = {49--59},
  author = {Brett L. Bruyere and Adam W. Beh and Geoffrey Lelengula},
  title = {Differences in Perceptions of Communication, Tourism Benefits, and Management Issues in a Protected Area of Rural Kenya},
  journal = {Environmental Management},
}

@Article{Stronza_2008,
  doi = {10.1016/j.annals.2008.01.002},
  url = {https://doi.org/10.1016/j.annals.2008.01.002},
  year = {2008},
  month = {apr},
  publisher = {Elsevier {BV}},
  volume = {35},
  number = {2},
  pages = {448--468},
  author = {Amanda Stronza and Javier Gordillo},
  title = {Community views of ecotourism},
  journal = {Annals of Tourism Research},
}

@Article{D_Agnes_2005,
  doi = {10.1080/08920750500217989},
  url = {https://doi.org/10.1080/08920750500217989},
  year = {2005},
  month = {oct},
  publisher = {Informa {UK} Limited},
  volume = {33},
  number = {4},
  pages = {447--458},
  author = {Heather D\textquotesingleAgnes and Joan Castro and Leona D\textquotesingleAgnes and Rhona Montebon},
  title = {Gender Issues within the Population-Environment Nexus in Philippine Coastal Areas},
  journal = {Coastal Management},
}

@Article{Gjertsen_2005,
  doi = {10.1016/j.worlddev.2004.07.009},
  url = {https://doi.org/10.1016/j.worlddev.2004.07.009},
  year = {2005},
  month = {feb},
  publisher = {Elsevier {BV}},
  volume = {33},
  number = {2},
  pages = {199--217},
  author = {Heidi Gjertsen},
  title = {Can Habitat Protection Lead to Improvements in Human Well-Being? Evidence from Marine Protected Areas in the Philippines},
  journal = {World Development},
}

@Article{Ndoye_2004,
  doi = {10.1080/14004080410034047},
  url = {https://doi.org/10.1080/14004080410034047},
  year = {2004},
  month = {jan},
  publisher = {Informa {UK} Limited},
  volume = {19},
  number = {sup004},
  pages = {36--44},
  author = {Ousseynou Ndoye and Julius Chupezi Tieguhong},
  title = {Forest Resources and Rural Livelihoods: The Conflict Between Timber and Non-timber Forest Products in the Congo Basin},
  journal = {Scandinavian Journal of Forest Research},
}

repository: marty-downs/evidence-based-heatmap

repo_name: marty-downs/evidence-based-heatmap


text:
@book{oy,
  title={Оптимальное управление. Линейная теория и приложения},
  author={Киселев Ю. Н., Аввакумов С. Н., Орлов М. В.},
  year={2007},
  publisher={М.:МАКС Пресс},
  isbn={9785317020385}
}


text:
package main

/*
#cgo CFLAGS: -I/usr/include/mysql -DMYSQL_DYNAMIC_PLUGIN -DMYSQL_ABI_CHECK
#include <stdio.h>
#include <mysql.h>
#include <string.h>

static int is_arg_string(UDF_ARGS *args,int arg_num) {
	if (args->arg_count > arg_num &&
		args->arg_type[arg_num] == STRING_RESULT) {
		return 1;
	}
	return 0;
}

static char* get_string_val(UDF_ARGS *args, int arg_num) {
	if (args->arg_count > arg_num) {
		return args->args[arg_num];
	}
}

static long long get_int_val(UDF_ARGS *args, int arg_num) {
	long long int_val;
	if (args->arg_count > arg_num) {
		int_val = *((long long*) args->args[arg_num]);
	}
	return int_val;
}

*/
import "C"

import (
	"encoding/json"
	"log"
	"strconv"
	"strings"
)

var w *worker

const (
	pubKey = "pub-c-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
	subKey = "sub-c-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
	secKey = "sec-c-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
)

type (
	publishMessage struct {
		Channel string // Channel
		Store   bool   // Store in history
		Online  bool   // Send only if active grants on chan
		Message []byte // Json message
	}

	grantMessage struct {
		Channel              string // Channel
		Auth                 string // Auth key
		Read, Write, Manager bool   // Rights
		Ttl                  int    // TTL
	}
)

func main() {}

//export pubnub_grant_init
func pubnub_grant_init(
	initid *C.UDF_INIT,
	args *C.UDF_ARGS,
	message *C.char,
) C.my_bool {

	if args.arg_count != 4 {
		C.strcpy(message, C.CString("pubnub_grant(channel string, auth string, rights string, ttl int ). \n"))
		return 1
	}

	if C.is_arg_string(args, 0) == 0 {
		C.strcpy(message, C.CString("channel param is not string\n"))
		return 1
	}

	if C.is_arg_string(args, 1) == 0 {
		C.strcpy(message, C.CString("auth param is not string\n"))
		return 1
	}

	if C.is_arg_string(args, 2) == 0 {
		C.strcpy(message, C.CString("rights param is not string\n"))
		return 1
	}

	return 0
}

//export pubnub_grant
func pubnub_grant(
	initid *C.UDF_INIT,
	args *C.UDF_ARGS,
	result *C.char,
	length *C.ulong,
	is_null *C.char,
	error *C.char,
) C.longlong {

	chann, auth, rights, ttlString :=
		C.GoString(C.get_string_val(args, 0)),
		C.GoString(C.get_string_val(args, 1)),
		C.GoString(C.get_string_val(args, 2)),
		C.GoString(C.get_string_val(args, 3))

	channel, v := validate(chann)
	if !v {
		log.Printf("Invalid channel name %q for grant %q !", chann, channel)
		return 1
	}

	ttl, err := strconv.Atoi(ttlString)
	if err != nil {
		// Default TTL value (from Pubnub doc)
		ttl = 1440
	}

	w.Grant(chann, auth, rights, ttl)

	return 0
}

//export pubnub_publish_init
func pubnub_publish_init(
	initid *C.UDF_INIT,
	args *C.UDF_ARGS,
	message *C.char,
) C.my_bool {

	if args.arg_count < 2 {
		C.strcpy(message, C.CString("pubnub_publish(channel string, message string, [flags string]). \n"))
		return 1
	}

	if C.is_arg_string(args, 0) == 0 {
		C.strcpy(message, C.CString("channel param is not string\n"))
		return 1
	}

	if C.is_arg_string(args, 1) == 0 {
		C.strcpy(message, C.CString("message param is not string\n"))
		return 1
	}

	return 0
}

//export pubnub_publish
func pubnub_publish(
	initid *C.UDF_INIT,
	args *C.UDF_ARGS,
	result *C.char,
	length *C.ulong,
	is_null *C.char,
	error *C.char,
) C.longlong {

	chann, message, flags :=
		C.GoString(C.get_string_val(args, 0)),
		C.GoString(C.get_string_val(args, 1)),
		""

	if args.arg_count > 2 {
		flags = C.GoString(C.get_string_val(args, 2))
	}

	payload := []byte(message)
	var js map[string]interface{}
	if err := json.Unmarshal(payload, &js); err != nil {
		log.Printf("Failed to decode json %q : %s", payload, err)
		return 1
	}

	// Avoid putting in queue messages with invalid payload
	channel, v := validate(chann)
	if !v {
		log.Printf("Invalid channel name %q for publish %q!", chann, channel)
		return 1
	}

	w.Publish(channel, payload, flags)
	return 0

}

func validate(channel string) (string, bool) {
	l := len(channel)
	if l < 1 || l > 92 {
		return channel, false
	}
	channel = strings.Map(func(r rune) rune {
		switch {
		case r >= 'A' && r <= 'Z':
			return r
		case r >= 'a' && r <= 'z':
			return r
		case r >= '0' && r <= '9':
			return r
		case r == '_' || r == '-':
			return r
		}
		return -1
	}, channel)

	return channel, len(channel) == l
}

repository: kaixinbuyu/mysql-udf-pubnub

repo_name: kaixinbuyu/mysql-udf-pubnub


text:
require u-boot-mkimage-socfpga.inc

U_BOOT_SRC_DIR ?= "${WORKDIR}"
U_BOOT_DIR_NAME ?= "${@(d.getVar('U_BOOT_SRC_DIR', True).rstrip('/').split('/')[-1])}"

SRC_URI = "file://${U_BOOT_SRC_DIR}"

S="${WORKDIR}/${U_BOOT_DIR_NAME}"


text:
package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/hiroyky/nikki_backend/config"
)

func AdminBasicAuth() gin.HandlerFunc {
	return gin.BasicAuth(gin.Accounts{
		config.Env.AdminUserName: config.Env.AdminPassword,
	})
}


text:
@InProceedings{zhou16,
  supplementary = {Supplementary:zhou16-supp.pdf},
  title = {On Convergence of Model Parallel Proximal Gradient Algorithm for Stale Synchronous Parallel System},
  author = {Zhou, Yi and Yu, Yaoliang and Dai, Wei and Liang, Yingbin and Xing, Eric},
  pages = {713-722},
  abstract = {With ever growing data volume and model size, an error-tolerant, communication efficient, yet versatile parallel algorithm has become a vital part for the success of many large-scale applications. In this work we propose mspg, an extension of the flexible proximal gradient algorithm to the model parallel and stale synchronous setting. The worker machines of mspg operate asynchronously as long as they are not too far apart, and they communicate efficiently through a dedicated parameter server. Theoretically, we provide a rigorous analysis of the various convergence properties of mspg, and a salient feature of our analysis is its seamless generality that allows both nonsmooth and nonconvex functions. Under mild conditions, we prove the whole iterate sequence of mspg converges to a critical point (which is optimal under convexity assumptions). We further provide an economical implementation of mspg, completely bypassing the need of keeping a local full model. We confirm our theoretical findings through numerical experiments.},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX