text:
package main

import (
	"flag"
	"log"
	"os"
	"time"

	"github.com/vesoft-inc/nebula-importer/pkg/cmd"
	"github.com/vesoft-inc/nebula-importer/pkg/config"
	"github.com/vesoft-inc/nebula-importer/pkg/errors"
	"github.com/vesoft-inc/nebula-importer/pkg/web"
)

var configuration = flag.String("config", "", "Specify importer configure file path")
var port = flag.Int("port", -1, "HTTP server port")
var callback = flag.String("callback", "", "HTTP server callback address")

func main() {
	errCode := 0
	defer func() {
		// Just for filebeat log fetcher to differentiate following logs from others
		time.Sleep(1 * time.Second)
		log.Println("--- END OF NEBULA IMPORTER ---")
		os.Exit(errCode)
	}()

	log.Println("--- START OF NEBULA IMPORTER ---")

	flag.Parse()

	if port != nil && *port > 0 && callback != nil && *callback != "" {
		// Start http server
		svr := &web.WebServer{
			Port:     *port,
			Callback: *callback,
		}

		if err := svr.Start(); err != nil {
			panic(err)
		}
	} else {
		if configuration == nil {
			panic("please configure yaml file")
		}

		conf, err := config.Parse(*configuration)
		if err != nil {
			e := err.(errors.ImporterError)
			log.Println(e.ErrMsg.Error())
			errCode = e.ErrCode
			return
		}

		runner := &cmd.Runner{}

		{
			now := time.Now()
			defer func() {
				time.Sleep(500 * time.Millisecond)
				if runner.Error() != nil {
					e := runner.Error().(errors.ImporterError)
					errCode = e.ErrCode
					log.Println(e.ErrMsg.Error())
				} else {
					log.Printf("Finish import data, consume time: %.2fs", time.Since(now).Seconds())
				}
			}()

			runner.Run(conf)
		}
	}
}


text:
# Copyright (c) 2011, Christian Rorvik
# Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

vpm_include_directories(${CMAKE_CURRENT_LIST_DIR}/include)

if(WIN32)
  # Check if Visual Leak Detector is installed
  if(${CMAKE_SIZEOF_VOID_P} EQUAL 4)
    set(_vldLibDir "Win32")
  else()
    set(_vldLibDir "Win64")
  endif()
  find_path(_vldHeaderPath "vld.h" PATHS "$ENV{PROGRAMFILES}/Visual Leak Detector/include")
  find_path(_vldLibPath "vld.lib" PATHS "$ENV{PROGRAMFILES}/Visual Leak Detector/lib/${_vldLibDir}")
  if(NOT ${_vldHeaderPath} STREQUAL _vldHeaderPath-NOTFOUND)
    if(NOT ${_vldLibPath} STREQUAL _vldLibPath-NOTFOUND)
      include_directories(${_vldHeaderPath})
      link_directories(${_vldLibPath})
      set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DCRUNCH_VLD_ENABLED")
    endif()
  endif()
endif()

license_type: permissive

branch_name: refs/heads/master

extension: cmake


text:
require linux-libc-headers.inc

# untested for non nios2 systems
DEFAULT_PREFERENCE = "-1"
DEFAULT_PREFERENCE_nios2 = "1"
INHIBIT_DEFAULT_DEPS = "1"
DEPENDS += "unifdef-native"
PR = "r2"

COMPATIBLE_TARGET_SYS = "."

SRC_URI = "${KERNELORG_MIRROR}/pub/linux/kernel/v2.6/linux-${PV}.tar.bz2 \
	  "

# For nios2 the source comes from sopc.et.ntust.edu.tw, but as this one is very slow
# a tarball is placed at opensource.axon.tv
#SRC_URI_nios2 = "git://sopc.et.ntust.edu.tw/git/linux-2.6.git;branch=nios2mmu;protocol=http;tag=a32ca88c4f3f3850c5c9789db2afab2530c6856d;protocol=http \
SRC_URI_nios2 = "ftp://opensource.axon.nl/mirror/git_sopc.et.ntust.edu.tw.linux-2.6.git_a32ca88c4f3f3850c5c9789db2afab2530c6856d.tar.gz;name=nios2tarball \
	  "

SRC_URI[md5sum] = "10eebcb0178fb4540e2165bfd7efc7ad"
SRC_URI[sha256sum] = "fa395fec7de633df1cb85b6248b8f35af98380ed128a8bc465fb48bc4d252633"

# nios2 checksums
SRC_URI[nios2tarball.md5sum] = "ad27c6ddfe5b2bb0f81968c0155d072d"
SRC_URI[nios2tarball.sha256sum] = "7c99c5ee4bf26d08fde030c605c618454984dba5ae79c298064228ab0053e60f"

S = "${WORKDIR}/linux-2.6.34"
S_nios2 = "${WORKDIR}/linux-2.6"

do_configure() {
	cd ${S}
	oe_runmake allnoconfig ARCH=$ARCH
}

do_compile () {
}

do_install() {
	oe_runmake headers_install INSTALL_HDR_PATH=${D}${exec_prefix} ARCH=$ARCH
	rm -f ${D}${exec_prefix}/include/scsi/scsi.h
}

license: MIT

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
// Same copyright and license as the rest of the files in this project

//GVariant : GVariant — strongly typed value datatype
// https://developer.gnome.org/glib/2.26/glib-GVariant.html

package glib

// #cgo pkg-config: glib-2.0 gobject-2.0
// #include <glib.h>
// #include <glib-object.h>
// #include "glib.go.h"
// #include "gvariant.go.h"
//import "C"
//import "unsafe"

/*
 * GVariantDict
 */
/* todo fix bugs
// VariantDict is a representation of GLib's VariantDict.
type VariantDict struct {
	GVariantDict *C.GVariantDict
}

func (v *VariantDict) toGVariantDict() *C.GVariantDict {
	if v == nil {
		return nil
	}
	return v.native()
}

func (v *VariantDict) toVariantDict() *VariantDict {
	return v
}

// newVariantDict creates a new VariantDict from a GVariantDict pointer.
func newVariantDict(p *C.GVariantDict) *VariantDict {
	return &VariantDict{GVariantDict: p}
}

// native returns a pointer to the underlying GVariantDict.
func (v *VariantDict) native() *C.GVariantDict {
	if v == nil || v.GVariantDict == nil {
		return nil
	}
	p := unsafe.Pointer(v.GVariantDict)
	return C.toGVariantDict(p)
}

// Native returns a pointer to the underlying GVariantDict.
func (v *VariantDict) Native() uintptr {
	return uintptr(unsafe.Pointer(v.native()))
}
*/

license: ISC

gha_language: Go

extension: go


text:
package pty

import (
	"io"
)

type pipe struct {
	chunks chan [][]byte
	empty  chan bool
}

type pipeWriter struct {
	pipe *pipe
}

type pipeReader struct {
	pipe *pipe
}

func newPipe() (io.WriteCloser, io.ReadCloser) {
	chunks := make(chan [][]byte, 1)
	empty := make(chan bool, 1)
	empty <- true
	pipe := &pipe{chunks: chunks, empty: empty}
	return &pipeWriter{pipe}, &pipeReader{pipe}
}

func (pipe *pipeWriter) Write(p []byte) (n int, err error) {
	n = len(p)
	if n == 0 {
		return 0, nil
	}

	dup := make([]byte, n)
	copy(dup, p)

	var chunks [][]byte
	select {
	case chunks = <-pipe.pipe.chunks:
	case <-pipe.pipe.empty:
	}

	chunks = append(chunks, dup)
	pipe.pipe.chunks <- chunks
	return n, nil
}

func (pipe *pipeWriter) Close() error {
	var chunks [][]byte
	select {
	case chunks = <-pipe.pipe.chunks:
	case <-pipe.pipe.empty:
	}
	chunks = append(chunks, []byte{})
	pipe.pipe.chunks <- chunks
	return nil
}

func (pipe *pipeReader) Read(p []byte) (n int, err error) {
	chunks := <-pipe.pipe.chunks

	want := len(p)
	offset := 0

	if len(chunks) > 0 && len(chunks[0]) == 0 {
		pipe.pipe.chunks <- chunks
		return 0, io.EOF
	}

	for len(chunks) > 0 && want > 0 {
		chunk := chunks[0]
		have := len(chunk)
		if have == 0 {
			break
		}
		if have > want {
			// we have to read only parts of the chunk
			copy(p[offset:offset+want], chunk)
			chunks[0] = chunk[want:]
			want = 0
		} else {
			copy(p[offset:offset+have], chunk)
			chunks = chunks[1:]
			want = want - have
			offset += have
		}
	}

	if len(chunks) == 0 {
		pipe.pipe.empty <- true
	} else {
		pipe.pipe.chunks <- chunks
	}

	return len(p) - want, nil
}

func (pipe *pipeReader) Close() error {
	return nil
}

repository: dueckminor/mypi-tools

repo_name: dueckminor/mypi-tools

gha_license_id: MIT


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

package cmd

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

	"github.com/pkg/errors"
	"sigs.k8s.io/yaml"

	"github.com/erda-project/erda/apistructs"
	"github.com/erda-project/erda/tools/cli/command"
)

var EXTENSIONSRETAG = command.Command{
	Name:       "retag",
	ParentName: "EXT",
	ShortHelp:  "generate retag script",
	Example:    "$ erda-cli ext retag -d extensions -r registry.default.svc.cluster.local:5000 -o retag.sh",
	Flags: []command.Flag{
		command.StringFlag{Short: "d", Name: "dir", Doc: "the extension dir", DefaultValue: "."},
		command.StringFlag{Short: "r", Name: "registry", Doc: "the new registry", DefaultValue: "registry.default.svc.cluster.local:5000"},
		command.StringFlag{Short: "o", Name: "output", Doc: "the output script file", DefaultValue: "retag.sh"},
	},
	Run: RunExtensionsReTag,
}

type ExtensionInfo struct {
	Path    string
	Spec    apistructs.Spec
	Dice    map[string]interface{}
	DiceErr error
	SpecErr error
}

func RunExtensionsReTag(ctx *command.Context, dir string, registry string, output string) error {
	outTxt := ""
	if checkPath(dir) != nil {
		ctx.Fail(fmt.Sprintf("path not exist: %s \n", dir))
		return nil
	}
	extMetas := GetExtMetas(dir)
	for _, extMeta := range extMetas {
		if extMeta.DiceErr == nil && extMeta.SpecErr == nil {
			if extMeta.Spec.Type == "action" {
				jobs, ok := extMeta.Dice["jobs"].(map[string]interface{})
				if !ok {
					continue
				}
				for _, job := range jobs {
					cfg := job.(map[string]interface{})
					originalImage := cfg["image"].(string)
					newImage := newDockerImage(originalImage, registry)
					outTxt += generateReTagCmd(originalImage, newImage)
				}
			} else if extMeta.Spec.Type == "addon" {
				services, ok := extMeta.Dice["services"].(map[string]interface{})
				if !ok {
					continue
				}
				for _, v := range services {
					cfg := v.(map[string]interface{})
					_, exist := cfg["image"]
					if !exist {
						continue
					}
					originalImage := cfg["image"].(string)
					newImage := newDockerImage(originalImage, registry)
					outTxt += generateReTagCmd(originalImage, newImage)
				}
			}
		}
	}
	err := ioutil.WriteFile(output, []byte(outTxt), os.ModePerm)
	if err != nil {
		return err
	}
	ctx.Succ(fmt.Sprintf("script %s generate success\n", output))
	return nil
}

func checkPath(path string) error {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return err
	}
	return nil
}

func generateReTagCmd(oldImage, newImage string) string {
	return fmt.Sprintf("docker pull %s\n", oldImage) +
		fmt.Sprintf("docker tag %s %s\n", oldImage, newImage) +
		fmt.Sprintf("docker push %s\n", newImage)
}

func GetExtMetas(dir string) []ExtensionInfo {
	result := []ExtensionInfo{}
	filepath.Walk(dir, func(relPath string, info os.FileInfo, err error) error {
		if info.IsDir() {
			specFile := path.Join(relPath, "spec.yml")
			diceFile := path.Join(relPath, "dice.yml")
			ext := ExtensionInfo{
				Path: relPath,
			}
			if checkPath(specFile) == nil {
				specBytes, err := ioutil.ReadFile(specFile)
				if err != nil {
					ext.SpecErr = err
				}
				spec := apistructs.Spec{}
				err = yaml.Unmarshal(specBytes, &spec)
				if err != nil {
					ext.SpecErr = errors.Wrap(err, "failed to parse spec "+specFile)
				}
				ext.Spec = spec

				if checkPath(diceFile) == nil {
					diceBytes, err := ioutil.ReadFile(diceFile)
					if err != nil {
						ext.DiceErr = errors.Wrap(err, "failed to read dice "+diceFile)
					}
					var diceData map[string]interface{}
					err = yaml.Unmarshal(diceBytes, &diceData)
					if err != nil {
						ext.DiceErr = errors.Wrap(err, "failed to parse dice "+diceFile)
					}
					ext.Dice = diceData
				}
				result = append(result, ext)
			}
		}
		return nil
	})
	return result
}

repository: erda-project/erda

repo_name: erda-project/erda


text:
SUMMARY = "Hello bitbake-layers recipe"
DESCRIPTION = "Hello Recipe created by bitbake-layers"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

python do_display_banner() {
    bb.plain("***********************************************");
    bb.plain("*                                             *");
    bb.plain("*  Example recipe created by bitbake-layers   *");
    bb.plain("*                                             *");
    bb.plain("***********************************************");
}
SRC_URI = "file://hello.c"

S = "${WORKDIR}"
do_compile(){
	${CC} ${LDFLAGS} hello.c -o hello
}

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

addtask display_banner before do_build


text:
package main

import (
	"html/template"
	"net/http"
)

func main() {
	templates := template.Must(template.ParseFiles("templates/index.html", "templates/pch.html"))

  http.HandleFunc("/pch", func(w http.ResponseWriter, r *http.Request){
		if err := templates.ExecuteTemplate(w, "pch.html", nil); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
  })
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if err := templates.ExecuteTemplate(w, "index.html", nil); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
	http.ListenAndServe(":80", nil)
}


text:
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.

# - Find LZ4 (lz4.h, liblz4.a, liblz4.so, and liblz4.so.0)
# This module defines
#  LZ4_INCLUDE_DIR, directory containing headers
#  LZ4_SHARED_LIB, path to liblz4 shared library
#  LZ4_STATIC_LIB, path to liblz4 static library
#  LZ4_FOUND, whether lz4 has been found

if( NOT "${LZ4_HOME}" STREQUAL "")
    file( TO_CMAKE_PATH "${LZ4_HOME}" _native_path )
    list( APPEND _lz4_roots ${_native_path} )
elseif ( Lz4_HOME )
    list( APPEND _lz4_roots ${Lz4_HOME} )
endif()

if (MSVC AND NOT DEFINED LZ4_MSVC_STATIC_LIB_SUFFIX)
  set(LZ4_MSVC_STATIC_LIB_SUFFIX "_static")
endif()

set(LZ4_STATIC_LIB_SUFFIX
  "${LZ4_MSVC_STATIC_LIB_SUFFIX}${CMAKE_STATIC_LIBRARY_SUFFIX}")

set(LZ4_STATIC_LIB_NAME
  ${CMAKE_STATIC_LIBRARY_PREFIX}lz4${LZ4_STATIC_LIB_SUFFIX})

find_path(LZ4_INCLUDE_DIR NAMES lz4.h
  PATHS ${_lz4_roots}
  NO_DEFAULT_PATH
  PATH_SUFFIXES "include" )
find_library(LZ4_STATIC_LIB NAMES ${LZ4_STATIC_LIB_NAME} lib${LZ4_STATIC_LIB_NAME}
  PATHS ${_lz4_roots}
  NO_DEFAULT_PATH
  PATH_SUFFIXES "lib" )

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(LZ4 REQUIRED_VARS
  LZ4_STATIC_LIB LZ4_INCLUDE_DIR)

repository: dremio/arrow

repo_name: dremio/arrow

branch_name: refs/heads/dremio


text:
@InProceedings{entner13a,
  pdf = {http://jmlr.org/proceedings/papers/v31/entner13a.pdf},
  supplementary = {Supplementary:entner13a-supp.pdf},
  title = {Data-driven covariate selection for nonparametric estimation of causal effects},
  author = {Entner, Doris and Hoyer, Patrik and Spirtes, Peter},
  pages = {256--264},
  abstract = {The estimation of causal effects from non-experimental data is a fundamental problem in many fields of science. One of the main obstacles concerns confounding by observed or latent covariates, an issue which is typically tackled by adjusting for some set of observed covariates. In this contribution, we analyze the problem of inferring whether a given variable has a causal effect on another and, if it does, inferring an adjustment set of covariates that yields a consistent and unbiased estimator of this effect, based on the (conditional) independence and dependence relationships among the observed variables. We provide two elementary rules that we show to be both sound and complete for this task, and compare the performance of a straightforward application of these rules with standard alternative procedures for selecting adjustment sets.},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX

extension: bib


text:
package core

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
	"github.com/kataras/iris/v12/core/router"
	"github.com/markbates/pkger"
	"html"
	"html/template"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"path"
	"sort"
	"strings"
)

type TemplateOption struct {
	TemplatePath string
}

// generate navigator urls from request path
func requestPath2Nav(rpath string) []NavInfo {
	navs := make([]NavInfo, 1)
	navs[0] = NavInfo{
		Label: "/",
		Url:   "/",
	}

	if rpath == "/" {
		return navs
	}

	pathSlice := strings.Split(rpath[1:], "/")
	urlBuilder := new(strings.Builder)
	for idx, fpath := range pathSlice {
		urlBuilder.WriteString("/")
		urlBuilder.WriteString(fpath)
		label := "/" + fpath
		if idx == 0 {
			label = fpath
		}

		label, _ = url.PathUnescape(label)
		navs = append(navs, NavInfo{
			Label: label,
			Url:   urlBuilder.String(),
		})
	}
	return navs
}

// show file list form a template file
func TemplateDirList(opts ...TemplateOption) router.DirListFunc {
	var option TemplateOption
	if len(opts) > 0 {
		option = opts[0]
	}

	var f io.Reader
	if option.TemplatePath == "" {
		option.TemplatePath = "/template/dirlist.tmpl"
		f, _ = pkger.Open(option.TemplatePath)
	} else {
		f, _ = os.Open(option.TemplatePath)
	}

	content, _ := ioutil.ReadAll(f)
	templateContent := string(content)

	return func(ctx *context.Context, dirOptions iris.DirOptions, dirName string, dir http.File) error {
		dirs, err := dir.Readdir(-1)
		if err != nil {
			return err
		}

		pagData := PageData{
			Files: make([]FileInfo, 0),
			Navs:  requestPath2Nav(ctx.RequestPath(true)),
		}

		dirSlice := make([]FileInfo, 0)
		fileSlice := make([]FileInfo, 0)

		for _, d := range dirs {
			if !dirOptions.ShowHidden && router.IsHidden(d) {
				continue
			}

			name := ToBaseName(d.Name())
			upath := path.Join(ctx.Request().RequestURI, url.PathEscape(name))

			viewName := name
			if d.IsDir() {
				viewName += "/"
				dirSlice = append(dirSlice, FileInfo{d, upath, html.EscapeString(viewName)})
			} else {
				fileSlice = append(fileSlice, FileInfo{d, upath, html.EscapeString(viewName)})
			}
		}

		sort.Slice(dirSlice, func(i, j int) bool {
			return dirSlice[i].Name() < dirSlice[j].Name()
		})

		sort.Slice(fileSlice, func(i, j int) bool {
			return fileSlice[i].Name() < fileSlice[j].Name()
		})
		pagData.Files = append(pagData.Files, dirSlice...)
		pagData.Files = append(pagData.Files, fileSlice...)

		tmpl, err := template.New("default").Parse(templateContent)
		if err != nil {
			return err
		}
		return tmpl.Execute(ctx, pagData)
	}
}

branch_name: refs/heads/main


text:
#ifndef RandomtXiGunProducer_H
#define RandomtXiGunProducer_H

#include "IOMC/ParticleGuns/interface/BaseRandomtXiGunProducer.h"
#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"

namespace edm {

  class RandomtXiGunProducer : public BaseRandomtXiGunProducer {

  public:
    RandomtXiGunProducer(const ParameterSet &);
    ~RandomtXiGunProducer() override;

  private:

    void produce(Event & e, const EventSetup& es) override;

    HepMC::FourVector make_particle(double t,double Xi,double phi,int PartID, int direction);
    double Minimum_t(double xi) {double partE = fpEnergy*(1.-xi);
                                 double massSQ= pow(PData->mass().value(),2);
                                 double partP = sqrt(partE*partE-massSQ);
                                 return -2.*(sqrt(fpEnergy*fpEnergy-massSQ)*partP-fpEnergy*partE+massSQ);
                                };

  protected :

    // data members

    double            fMint   ;
    double            fMaxt   ;
    double            fMinXi  ;
    double            fMaxXi  ;

  };
}
#endif

repository: CMS-TMTT/cmssw

repo_name: CMS-TMTT/cmssw

extension: h


text:
package mydata

// ProductEffect 结构体
type ProductEffect struct {
	// 产品效果
	Effects []EffectEntity `json:"effects,omitempty" xml:"effects>effect_entity,omitempty"`
	// 返回结果数量
	TotalCount int64 `json:"total_count,omitempty" xml:"total_count,omitempty"`
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao


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

package log

import (
	"context"
	"encoding/hex"
	"strconv"
	"sync"

	"github.com/golang/protobuf/proto"
	log "go.chromium.org/luci/common/logging"
	"go.chromium.org/luci/logdog/api/logpb"
	"go.chromium.org/luci/logdog/client/butler/bootstrap"
	"go.chromium.org/luci/logdog/client/butler/output"
	"go.chromium.org/luci/logdog/common/types"
)

// logOutput is an Output implementation that logs messages to its contexts'
// Logger instance.
type logOutput struct {
	sync.Mutex
	ctx context.Context

	// bundleSize is the maximum size of the Butler bundle to use.
	bundleSize int

	stats output.StatsBase
}

// logOutput implements output.Output.
var _ output.Output = (*logOutput)(nil)

// New instantes a new log output instance.
func New(ctx context.Context, bundleSize int) output.Output {
	o := logOutput{
		ctx:        ctx,
		bundleSize: bundleSize,
	}
	o.ctx = log.SetFields(o.ctx, log.Fields{
		"output": &o,
	})
	return &o
}

func (o *logOutput) String() string { return "log" }

func (o *logOutput) SendBundle(bundle *logpb.ButlerLogBundle) error {
	o.Lock()
	defer o.Unlock()

	for _, e := range bundle.Entries {
		path := types.StreamName(bundle.Prefix).Join(types.StreamName(e.Desc.Name))
		ctx := log.SetField(o.ctx, "streamPath", path)

		log.Fields{
			"count":      len(e.Logs),
			"descriptor": e.Desc.String(),
		}.Infof(ctx, "Received stream logs.")

		for _, le := range e.Logs {
			log.Fields{
				"timeOffset":  le.TimeOffset.AsDuration(),
				"prefixIndex": le.PrefixIndex,
				"streamIndex": le.StreamIndex,
				"sequence":    le.Sequence,
			}.Infof(ctx, "Received message.")
			if c := le.GetText(); c != nil {
				for idx, l := range c.Lines {
					log.Infof(ctx, "Line %d) %s (%s)", idx, l.Value, strconv.Quote(l.Delimiter))
				}
			}
			if c := le.GetBinary(); c != nil {
				log.Infof(ctx, "Binary) %s", hex.EncodeToString(c.Data))
			}
			if c := le.GetDatagram(); c != nil {
				if cp := c.Partial; cp != nil {
					log.Infof(ctx, "Datagram (%#v) (%d bytes): %s", cp, cp.Size, hex.EncodeToString(c.Data))
				} else {
					log.Infof(ctx, "Datagram (%d bytes): %s", len(c.Data), hex.EncodeToString(c.Data))
				}
			}

			o.stats.F.SentMessages++
		}
	}
	o.stats.F.SentBytes += int64(proto.Size(bundle))

	return nil
}

func (o *logOutput) MaxSendBundles() int {
	return 1
}

func (o *logOutput) MaxSize() int {
	return o.bundleSize
}

func (o *logOutput) Stats() output.Stats {
	o.Lock()
	defer o.Unlock()

	st := o.stats
	return &st
}

func (o *logOutput) URLConstructionEnv() bootstrap.Environment {
	return bootstrap.Environment{}
}

func (o *logOutput) Close() {}

repository: luci/luci-go

repo_name: luci/luci-go


text:
package gigasecond

import "time"

func AddGigasecond(t time.Time) time.Time {

	return t.Add(time.Duration(1e9) * time.Second)
}


text:
DESCRIPTION = "evopedia is an offline Wikipedia viewer "
AUTHOR = "Christian Reitwießner"
HOMEPAGE = "http://www.reitwiessner.de/openmoko/evopedia.html"
PRIORITY = "optional"
LICENSE = "GPL"
RRECOMMENDS_${PN} = "midori"
RRECOMMENDS_${PN}_shr = "eve"

PV = "0.4.2+gitr${SRCPV}"
PR = "r1"

SRC_URI = "git://gitorious.org/evopedia/evopedia.git;protocol=git;branch=master"

SRCREV = "36ca70acb457762d623e8e6c83039256dbe5c7f4"
S = "${WORKDIR}/git"

inherit qt4x11

EXTRA_QMAKEVARS_PRE += " PREFIX=/usr"

FILES_${PN}-dbg += "${bindir}/.debug"

do_install() {
       oe_runmake install INSTALL_ROOT=${D}
}


text:
package main

import (
	"fmt"
	"os"

	"github.com/bitfield/checkly"
	"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

// Provider makes the provider available to Terraform.
func Provider() *schema.Provider {
	return &schema.Provider{
		Schema: map[string]*schema.Schema{
			"api_key": {
				Type:        schema.TypeString,
				Required:    true,
				DefaultFunc: schema.EnvDefaultFunc("CHECKLY_API_KEY", nil),
			},
		},
		ResourcesMap: map[string]*schema.Resource{
			"checkly_check": resourceCheck(),
		},
		ConfigureFunc: func(r *schema.ResourceData) (interface{}, error) {
			client := checkly.NewClient(r.Get("api_key").(string))
			debugLog := os.Getenv("CHECKLY_DEBUG_LOG")
			if debugLog != "" {
				debugFile, err := os.OpenFile(debugLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
				if err != nil {
					panic(fmt.Sprintf("can't write to debug log file: %v", err))
				}
				client.Debug = debugFile
			}
			return &client, nil
		},
	}
}

repository: bitfield/terraform-provider-checkly

repo_name: bitfield/terraform-provider-checkly


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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
 *
 *   https://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 spi

import (
	"context"
	"fmt"
	"time"
)

type Expectation interface {
	fmt.Stringer
	GetContext() context.Context
	GetCreationTime() time.Time
	GetExpiration() time.Time
	GetAcceptsMessage() AcceptsMessage
	GetHandleMessage() HandleMessage
	GetHandleError() HandleError
}

// AcceptsMessage If this function returns true, the message is forwarded to the message handler
type AcceptsMessage func(message Message) bool

// HandleMessage Function for handling the message, returns an error if anything goes wrong
type HandleMessage func(message Message) error

// HandleError Function for handling the message, returns an error if anything goes wrong
type HandleError func(err error) error

// MessageCodec handles sending and retrieving of messages
type MessageCodec interface {
	// Deprecated: use ConnectWithContext
	// Connect connects this codec
	Connect() error
	// ConnectWithContext connects this codec with the supplied context
	ConnectWithContext(ctx context.Context) error
	// Disconnect disconnects this codec
	Disconnect() error
	// IsRunning returns true if the codec (workers are running)
	IsRunning() bool

	// Send is sending a given message
	Send(message Message) error
	// Expect Wait for a given timespan for a message to come in, which returns 'true' for 'acceptMessage'
	// and is then forwarded to the 'handleMessage' function
	Expect(ctx context.Context, acceptsMessage AcceptsMessage, handleMessage HandleMessage, handleError HandleError, ttl time.Duration) error
	// SendRequest A combination that sends a message first and then waits for a response. !!!Important note: the callbacks are blocking calls
	SendRequest(ctx context.Context, message Message, acceptsMessage AcceptsMessage, handleMessage HandleMessage, handleError HandleError, ttl time.Duration) error

	// GetDefaultIncomingMessageChannel gives back the chan where unexpected messages arrive
	GetDefaultIncomingMessageChannel() chan Message
}

branch_name: refs/heads/develop

gha_language: Java


text:
require recipes/uhd/uhd-firmware.inc

PR = "${INC_PR}.0"

SRC_URI[md5sum] = "6db20f93e3c4646395bd6e8260e2261f"
SRC_URI[sha256sum] = "4c73655519cd9f4e49e5727f094b463850b03db13d91a8b0429b789e74a9deea"


text:
SUMMARY = "CRM shell for the pacemaker cluster manager"
DESCRIPTION = "The crm shell is an advanced command-line interface for High-Availability \
 cluster management in GNU/Linux. Effortlessly configure, manage and \
 troubleshoot your clusters from the command line, with full tab completion \
 and extensive help. crmsh also provides advanced features like low-level \
 cluster configuration, cluster scripting and package management, and \
 history exploration tools giving you an instant view of what your cluster \
 is doing."
HOMEPAGE = "http://crmsh.github.io/"

# Override value of DEBIAN_GIT_BRANCH variable in debian-package class
DEBIAN_GIT_BRANCH = "jessie-backports-master"

inherit debian-package

PR = "r0"
PV = "2.3.2"
LICENSE = "GPLv2+ & MIT"
LIC_FILES_CHKSUM = "\
	file://COPYING;md5=751419260aa954499f7abaabaa882bbe \
	file://crmsh/orderedset.py;endline=20;md5=d197d7a986883ab3cb2d725327b806e9 \
	"

DEPENDS += "pacemaker debconf"
inherit pythonnative
#export some variable from poky, to use for python command
export BUILD_SYS
export HOST_SYS
export STAGING_INCDIR
export STAGING_LIBDIR
export DEB_HOST_MULTIARCH

KEEP_NONARCH_BASELIB = "1"

# base on debian/rules
EXTRA_OECONF += "--docdir=${docdir}/${PN} --htmldir=${docdir}/${PN}/html"

inherit autotools-brokensep
do_install_append() {
	# base on debian/rules
	rm ${D}${libdir}/python*/*/${PN}/*.pyc
}
# base on debian/postinst
pkg_postinst_${PN}() {
	. ${STAGING_DATADIR}/debconf/confmodule
	${PYTHON} -m compileall $D${PYTHON_SITEPACKAGES_DIR}/${PN}
}

FILES_${PN} += "${libdir}/*"
RDEPENDS_${PN} += "\
	pacemaker-cli-utils python-lxml python-yaml python-compression \
	python-datetime python-doctest python-json python-core python-shell \
	python-netclient python-io python-lang python-math python-profile \
	python-subprocess python-codecs python-tests python-pprint python-unixadmin \
	python-textutils python-crypt python-distutils python-difflib python-netserver\
	"

RRECOMMENDS_${PN} += "pacemaker"

repository: meta-debian/meta-debian-extra

repo_name: meta-debian/meta-debian-extra

branch_name: refs/heads/morty

gha_language: BitBake


text:
package config

import (
	"fmt"
)

func dbConfig() string {
	c := GetBDConfig()
	s := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s", c.Username, c.Password, c.Host, c.Dbname, c.Params)
	return s
}


text:
SUMMARY = "Default Fru"
DESCRIPTION = "Builds a default FRU file at runtime based on board ID"

inherit obmc-phosphor-systemd
inherit cmake

SRC_URI = "file://checkFru.sh;subdir=${BP} \
           file://decodeBoardID.sh;subdir=${BP} \
           file://mkfru.cpp;subdir=${BP} \
           file://CMakeLists.txt;subdir=${BP} \
           "
SYSTEMD_SERVICE:${PN} = "SetBaseboardFru.service"

LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "\
    file://${INTELBASE}/COPYING.apache-2.0;md5=34400b68072d710fecd0a2940a0d1658 \
    file://mkfru.cpp;beginline=2;endline=14;md5=c451359f18a13ee69602afce1588c01a \
    "

RDEPENDS:${PN} = "bash"

do_install:append() {
    install -d ${D}${bindir}
    install -m 0755 ${S}/checkFru.sh ${D}${bindir}/checkFru.sh
    install -m 0755 ${S}/decodeBoardID.sh ${D}${bindir}/decodeBoardID.sh
}

repository: Intel-BMC/openbmc

repo_name: Intel-BMC/openbmc

gha_license_id: NOASSERTION

gha_language: Python


text:
package server

import (
	"fmt"
	"net"
	"testing"
	"time"

	"github.com/cheekybits/is"
	"github.com/go-kit/kit/log"
)

func TestLineProtocolServer(t *testing.T) {
	is := is.New(t)

	logger := testLogger()

	var lines []string

	fn := func(line string) {
		lines = append(lines, line)
	}

	s, err := NewLineProtocolServer(log.With(logger, "component", "line_protocol_server"), ":8095", fn)
	is.NoErr(s.Run())
	defer s.Stop()

	conn, err := net.Dial("tcp", ":8095")
	is.NoErr(err)
	fmt.Fprintf(conn, "this is line 1\n")
	fmt.Fprintf(conn, "this is line 2\n")
	fmt.Fprintf(conn, "\n")
	conn.Close()

	time.Sleep(300 * time.Millisecond)

	is.Equal(len(lines), 2)
	is.Equal("this is line 1", lines[0])
	is.Equal("this is line 2", lines[1])
}

repository: alrs/amproxy

repo_name: alrs/amproxy


text:
DESCRIPTION = "A Python Wrapper for libid3."
SECTION = "devel/python"
PRIORITY = "optional"
LICENSE = "LGPL"
DEPENDS = "id3lib"
SRCNAME = "pyid3lib"
PR = "r1"

SRC_URI = "${SOURCEFORGE_MIRROR}/pyid3lib/${SRCNAME}-${PV}.tar.bz2"
S = "${WORKDIR}/${SRCNAME}-${PV}"

inherit distutils


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

package service

import "github.com/triggermesh/tm/pkg/file"

// Service represents knative service structure
type Service struct {
	Annotations    map[string]string
	BuildArgs      []string
	BuildTimeout   string
	BuildOnly      bool
	Concurrency    int
	Env            []string
	EnvSecrets     []string
	Labels         []string
	Name           string
	Namespace      string
	PullPolicy     string
	Revision       string
	ResultImageTag string
	// Originally knative/buildtemplate, but now also tekton/task
	Runtime string
	Source  string
	// TODO: get rid of file package dependency
	Schedule []file.Schedule
}

repository: triggermesh/tm

repo_name: triggermesh/tm


text:
DESCRIPTION = "pyparted is a set of Python modules that provide Python programmers \
an interface to libparted, the GNU parted library for disk partitioning and \
filesystem manipulation."
SUMMARY = "Python bindings for libparted"
HOMEPAGE = "https://fedorahosted.org/pyparted/"
LICENSE = "GPL-2.0+"
LIC_FILES_CHKSUM = "\
    file://COPYING;md5=8ca43cbc842c2336e835926c2166c28b \
    file://src/_pedmodule.c;startline=10;endline=22;md5=70c62bd73782a03f56a0571a9f08ea46 \
"
DEPENDS += "parted"

SRC_URI = "https://fedorahosted.org/releases/p/y/pyparted/pyparted-${PV}.tar.gz"
SRC_URI[md5sum] = "f16c7ef7f5fa4a43fcb2a4654b487e39"
SRC_URI[sha256sum] = "a56712e3d058ce3d859c158236dbbf45224018919efd3d880ea80f9e0d0bebbb"
S = "${WORKDIR}/pyparted-${PV}"

inherit distutils

RDEPENDS_${PN} += "python-stringold python-codecs python-math"
RDEPENDS_${PN}_class-native = ""

BBCLASSEXTEND += "native"

branch_name: refs/heads/fido


text:
#pragma once

#ifdef  __cplusplus
extern "C" {
#endif

namespace max7311{

#define PIN_0  0x0001
#define PIN_1  0x0002
#define PIN_2  0x0004
#define PIN_3  0x0008
#define PIN_4  0x0010
#define PIN_5  0x0020
#define PIN_6  0x0040
#define PIN_7  0x0080

#define PIN_8  0x0100
#define PIN_9  0x0200
#define PIN_10 0x0400
#define PIN_11 0x0800
#define PIN_12 0x1000
#define PIN_13 0x2000
#define PIN_14 0x4000
#define PIN_15 0x8000

#define PIN_K1 0x0003
#define PIN_K2 0x000C
#define PIN_K3 0x0030
#define PIN_K4 0x00C0
#define PIN_K5 0x0300
#define PIN_K6 0x0C00

    int  initController(const char *i2c_dev_path,  char address);
    int  initControllerDefault();

    char getDefaultAddress();

    /*Sets the output current value.
    If an error occurs then the value will be -1*/
    int  setPIN(unsigned short pin,bool state);

    /*Returns the status value of the port.
    If an error occurs then the value will be -1*/
    int  getPIN(unsigned short pin);

    /*Sets the output current value.
    If an error occurs then the value will be -1*/
    int  setPIN_EX(const char *i2c_dev_path,  char address, unsigned short pin,bool state);

    /*Returns the status value of the port.
    If an error occurs then the value will be -1*/
    int  getPIN_EX(const char *i2c_dev_path,  char address, unsigned short pin);

    /* Sets the sleep time to switch the relay. The default value is below 1000 ms. */
    void setSleepTime(unsigned long time);

    /*Used to set a group of flags.
    State can take a value within -1, 0, 1
    where a value of -1 will set 00
    1 will set 01
    0 will set 10
    If an error occurs then the value will be -1*/
    int setPIN_GROUP(unsigned short pin_group,int state);

    /*Used to set a group of flags.
    State can take a value within -1, 0, 1
    where a value of -1 will set 00
    1 will set 01
    0 will set 10
    If an error occurs then the value will be -1*/
    int setPIN_GROUP_EX(const char *i2c_dev_path,  char address, unsigned short pin_group,int state);
}

namespace rp_max7311{

#define RP_MAX7311_IN1 0x01
#define RP_MAX7311_IN2 0x02

#define RP_MAX7311_OUT1 0x01
#define RP_MAX7311_OUT2 0x02

// Flags for AC DC mode
#define RP_AC_MODE 0x01
#define RP_DC_MODE 0x00

#define RP_ATTENUATOR_1_1  0x01
#define RP_ATTENUATOR_1_20 0x00

#define RP_GAIN_2V  0x00
#define RP_GAIN_10V 0x01

/* If an error occurs then the value will be -1*/

    int  rp_initController();

    /* Sets the AC / DC modes for input.
    Corresponds to the switches K1 and K2 on the circuit.
    Where K1 corresponds to PIN_0 PIN_1 pins on the chip.
    Where K2 corresponds to PIN_2 PIN_3 pins on the chip. */
    int  rp_setAC_DC(char port,char mode);

    /* Sets the attenuator modes for input.
    Corresponds to the switches K3 and K4 on the circuit.
    Where K3 corresponds to PIN_4 PIN_5 pins on the chip.
    Where K4 corresponds to PIN_6 PIN_7 pins on the chip. */
    int  rp_setAttenuator(char port,char mode);

    /* Sets the gain modes for output.
    Corresponds to the switches K5 and K6 on the circuit.
    Where K5 corresponds to PIN_8 PIN_9 pins on the chip.
    Where K6 corresponds to PIN_10 PIN_11 pins on the chip. */
    int  rp_setGainOut(char port,char mode);

    /* Sets the sleep time to switch the relay. The default value is below 1000 ms. */
    void rp_setSleepTime(unsigned long time);

    /* Check  0x08 register status
    This function is used to check if an LCR meter is connected.
    If the board revision is 1.2 then the function always returns zero.
    If the revision of the board is less than 1.2, then the value from register 0x8 is returned
    */
    char rp_check();
}

#ifdef  __cplusplus
}
#endif

repository: RedPitaya/RedPitaya

repo_name: RedPitaya/RedPitaya

gha_language: C


text:
package vnfmsdk

import (
	"fmt"
	"strings"

	"github.com/op/go-logging"
	"github.com/openbaton/go-openbaton/catalogue"
	"github.com/openbaton/go-openbaton/catalogue/messages"
	"github.com/openbaton/go-openbaton/sdk"
	"github.com/streadway/amqp"
)

//The worker struct allows the VNFM SDK to invoke implementation specific of VNFMs
type worker struct {
	l          *logging.Logger
	handler    HandlerVnfm
	Allocate   bool
	Connection *amqp.Connection
}

type vnfmError struct {
	msg   string
	vnfr  *catalogue.VirtualNetworkFunctionRecord
	nsrID string
}

func (worker *worker) handleConfigure(genericMessage *messages.OrGeneric) (messages.NFVMessage, *vnfmError) {
	nfvMessage, err := messages.New(catalogue.ActionConfigure, &messages.VNFMGeneric{
		VNFR: genericMessage.VNFR,
	})
	if err != nil {
		worker.l.Panic("BUG: shouldn't happen")
	}

	return nfvMessage, nil
}

func (worker *worker) handleError(errorMessage *messages.OrError) *vnfmError {
	vnfr := errorMessage.VNFR
	nsrID := vnfr.ParentNsID

	worker.l.Errorf("received an error from the NFVO")

	if err := worker.handler.HandleError(errorMessage.VNFR); err != nil {
		return &vnfmError{err.Error(), vnfr, nsrID}
	}

	return nil
}

func (worker *worker) handleHeal(healMessage *messages.OrHealVNFRequest) (messages.NFVMessage, *vnfmError) {
	vnfr := healMessage.VNFR
	nsrID := vnfr.ParentNsID
	vnfcInstance := healMessage.VNFCInstance

	vnfrObtained, err := worker.handler.Heal(vnfr, vnfcInstance, healMessage.Cause)
	if err != nil {
		return nil, &vnfmError{err.Error(), vnfr, nsrID}
	}

	nfvMessage, err := messages.New(catalogue.ActionHeal, &messages.VNFMHealed{
		VNFR:         vnfrObtained,
		VNFCInstance: vnfcInstance,
	})
	if err != nil {
		worker.l.Panic("BUG: shouldn't happen")
	}

	return nfvMessage, nil
}

func (worker *worker) handleInstantiate(instantiateMessage *messages.OrInstantiate) (messages.NFVMessage, *vnfmError) {

	worker.l.Debug("received extensions: %v", instantiateMessage.Extension)

	worker.l.Debug("received keys: %v", instantiateMessage.Keys)

	vimInstances := instantiateMessage.VIMInstances

	var flavorKey string

	if instantiateMessage.VNFDFlavour != nil {
		flavorKey = instantiateMessage.VNFDFlavour.FlavourKey
	} else {
		flavorKey = ""
	}
	var recvVNFR *catalogue.VirtualNetworkFunctionRecord

	var resultVNFR *catalogue.VirtualNetworkFunctionRecord

	var err error

	var nfvMessage messages.NFVMessage

	if instantiateMessage.VNFR == nil {
		// this is the normal instantiate case
		vnfr, err := catalogue.NewVNFR(
			instantiateMessage.VNFD,
			flavorKey,
			instantiateMessage.VLRs,
			instantiateMessage.Extension,
			vimInstances)

		msg, err := messages.New(catalogue.ActionGrantOperation, &messages.VNFMGeneric{
			VNFR: vnfr,
		})
		if err != nil {
			worker.l.Panic("BUG: shouldn't happen")
		}

		resp, err := worker.executeRpc("vnfm.nfvo.actions.reply", msg)

		if err != nil {
			return nil, &vnfmError{err.Error(), vnfr, vnfr.ParentNsID}
		}

		respContent, ok := resp.Content().(*messages.OrGrantLifecycleOperation)
		if !ok {
			return nil, &vnfmError{
				msg:   fmt.Sprintf("expected OrGrantLifecycleOperation, got %T", resp.Content()),
				nsrID: vnfr.ParentNsID,
				vnfr:  vnfr,
			}
		}

		recvVNFR = respContent.VNFR
		vimInstanceChosen := respContent.VDUVIM

		worker.l.Debug("Received VNFR after GRANT_OPERATION")

		if !worker.Allocate {
			allocatedVNFR, err := worker.allocateResources(recvVNFR, vimInstanceChosen, instantiateMessage.Keys)
			if err != nil {
				return nil, err
			}

			recvVNFR = allocatedVNFR
		}

		if instantiateMessage.VNFPackage != nil {
			pkg := instantiateMessage.VNFPackage

			if pkg.ScriptsLink != "" {

				resultVNFR, err = worker.handler.Instantiate(recvVNFR, pkg.ScriptsLink, vimInstances)
			} else {
				resultVNFR, err = worker.handler.Instantiate(recvVNFR, pkg.Scripts, vimInstances)
			}
		} else {
			resultVNFR, err = worker.handler.Instantiate(recvVNFR, nil, vimInstances)
		}

		if err != nil {
			return nil, &vnfmError{
				msg:   err.Error(),
				nsrID: recvVNFR.ParentNsID,
				vnfr:  recvVNFR,
			}
		}
		nfvMessage, err = messages.New(catalogue.ActionInstantiate, &messages.VNFMInstantiate{
			VNFR: resultVNFR,
		})
	} else {
		// this will only happen if a VNFR is restarted.
		// in this case we return an Update message instead of an Instantiate message
		// it is a (not so elegant) workaround because otherwise the NFVO would run its
		// instantiateTask which in the end triggers the creation of a new container.
		// just returning an update message prevents that and has no impact on the service
		// as the update task only saves the unmodified vnfr.
		// returning no message at all is unfortunately not an option as then the NSR's status stays NULL
		worker.l.Debug("Received INSTANTIATE in context of restartVNFR. Sending back UPDATE message for avoiding the usual INSTANTIATE -> MODIFY -> START procedure and setting the VNFR's status back to ACTIVE.")
		resultVNFR = instantiateMessage.VNFR
		nfvMessage, err = messages.New(catalogue.ActionUpdate, &messages.VNFMInstantiate{
			VNFR: resultVNFR,
		})
	}
	if err != nil {
		return nil, &vnfmError{err.Error(), resultVNFR, resultVNFR.ParentNsID}
	}

	return nfvMessage, nil
}

func (worker *worker) executeRpc(queue string, message messages.NFVMessage) (messages.NFVMessage, error) {
	body, err := sdk.Rpc(
		queue,
		message,
		worker.Connection,
		worker.l)

	if err != nil {
		return nil, err
	}
	return messages.Unmarshal(body, messages.NFVO)
}

func (worker *worker) handleModify(genericMessage *messages.OrGeneric) (messages.NFVMessage, *vnfmError) {
	vnfr := genericMessage.VNFR
	nsrID := vnfr.ParentNsID

	resultVNFR, err := worker.handler.Modify(vnfr, genericMessage.VNFRDependency)
	if err != nil {
		return nil, &vnfmError{err.Error(), vnfr, nsrID}
	}

	nfvMessage, err := messages.New(catalogue.ActionModify, &messages.VNFMGeneric{
		VNFR: resultVNFR,
	})
	if err != nil {
		return nil, &vnfmError{err.Error(), resultVNFR, nsrID}
	}

	return nfvMessage, nil
}

func (worker *worker) handleReleaseResources(genericMessage *messages.OrGeneric) (messages.NFVMessage, *vnfmError) {
	vnfr := genericMessage.VNFR
	nsrID := vnfr.ParentNsID

	resultVNFR, err := worker.handler.Terminate(vnfr)
	if err != nil {
		return nil, &vnfmError{err.Error(), vnfr, nsrID}
	}

	nfvMessage, err := messages.New(catalogue.ActionReleaseResources, &messages.VNFMGeneric{
		VNFR: resultVNFR,
	})
	if err != nil {
		return nil, &vnfmError{err.Error(), resultVNFR, nsrID}
	}

	return nfvMessage, nil
}

func (worker *worker) handleResume(genericMessage *messages.OrGeneric) (messages.NFVMessage, *vnfmError) {
	vnfr := genericMessage.VNFR
	vnfrDependency := genericMessage.VNFRDependency
	nsrID := vnfr.ParentNsID

	if actionForResume := worker.handler.ActionForResume(vnfr, nil); actionForResume != catalogue.NoActionSpecified {
		resumedVNFR, err := worker.handler.Resume(vnfr, nil, vnfrDependency)
		if err != nil {
			return nil, &vnfmError{err.Error(), vnfr, nsrID}
		}

		nfvMessage, err := messages.New(actionForResume, &messages.VNFMGeneric{
			VNFR: resumedVNFR,
		})
		if err != nil {
			worker.l.Panic("BUG: shouldn't happen")
		}

		worker.l.Debug("Resuming VNFR")

		return nfvMessage, nil
	}

	return nil, nil
}

func (worker *worker) handleScaleIn(scalingMessage *messages.OrScaling) *vnfmError {
	vnfr := scalingMessage.VNFR
	nsrID := vnfr.ParentNsID

	vnfcInstanceToRemove := scalingMessage.VNFCInstance

	if _, _, err := worker.handler.Scale(scalingMessage.VIMInstance, catalogue.ActionScaleIn, vnfr, vnfcInstanceToRemove, nil, nil); err != nil {
		return &vnfmError{err.Error(), vnfr, nsrID}
	}

	return nil
}

func (worker *worker) handleScaleOut(scalingMessage *messages.OrScaling) (messages.NFVMessage, *vnfmError) {
	vnfr := scalingMessage.VNFR
	nsrID := vnfr.ParentNsID
	component := scalingMessage.Component

	worker.l.Debug("received VNFR")

	worker.l.Info("Adding VNFComponent")

	var newVNFCInstance *catalogue.VNFCInstance
	if !worker.Allocate {
		newMsg, err := messages.New(&messages.VNFMScaling{
			VNFR:     vnfr,
			UserData: worker.handler.UserData(),
		})

		if err != nil {
			return nil, &vnfmError{err.Error(), vnfr, nsrID}
		}

		respMsg, err := worker.executeRpc("vnfm.nfvo.actions.reply", newMsg)
		if err != nil {
			return nil, &vnfmError{err.Error(), vnfr, nsrID}
		}

		var replyVNFR *catalogue.VirtualNetworkFunctionRecord

		switch content := respMsg.Content().(type) {
		case *messages.OrGeneric:
			replyVNFR = content.VNFR
			worker.l.Debug("got reply VNFR")

		case *messages.OrError:
			if err := worker.handler.HandleError(content.VNFR); err != nil {
				return nil, &vnfmError{err.Error(), content.VNFR, nsrID}
			}

			return nil, nil

		default:
			worker.l.Warning("got a weird message on reply to SCALING")

			replyVNFR = vnfr
		}

		if newVNFCInstance = replyVNFR.FindComponentInstance(component); newVNFCInstance == nil {
			return nil, &vnfmError{"no new VNFCInstance found. This should not happen.", replyVNFR, nsrID}
		}

		worker.l.Debug("VNFComponentInstance found")

		if strings.EqualFold(scalingMessage.Mode, "STANDBY") {
			newVNFCInstance.State = "STANDBY"
		}

		vnfr = replyVNFR
	} else {
		worker.l.Warning("wk.allocate is set. No new VNFCInstance has been instantiated by the NFVO.")
	}

	var scripts interface{}
	switch {
	case scalingMessage.VNFPackage == nil:
		scripts = []*catalogue.Script{}

	case scalingMessage.VNFPackage.ScriptsLink != "":
		scripts = scalingMessage.VNFPackage.ScriptsLink

	default:
		scripts = scalingMessage.VNFPackage.Scripts
	}

	var err error
	var resultVNFR *catalogue.VirtualNetworkFunctionRecord

	if !worker.Allocate {
		resultVNFR, newVNFCInstance, err = worker.handler.Scale(scalingMessage.VIMInstance, catalogue.ActionScaleOut, vnfr, newVNFCInstance, scripts, scalingMessage.Dependency)
	} else {
		resultVNFR, newVNFCInstance, err = worker.handler.Scale(scalingMessage.VIMInstance, catalogue.ActionScaleOut, vnfr, component, scripts, scalingMessage.Dependency)
	}

	if err != nil {
		return nil, &vnfmError{err.Error(), vnfr, nsrID}
	}

	nfvMessage, err := messages.New(catalogue.ActionScaled, &messages.VNFMScaled{
		VNFR:         resultVNFR,
		VNFCInstance: newVNFCInstance,
	})

	if err != nil {
		return nil, &vnfmError{err.Error(), resultVNFR, nsrID}
	}

	return nfvMessage, nil
}

func (worker *worker) handleStart(startStopMessage *messages.OrStartStop) (messages.NFVMessage, *vnfmError) {
	vnfr := startStopMessage.VNFR
	nsrID := vnfr.ParentNsID
	vnfcInstance := startStopMessage.VNFCInstance

	startStop := &messages.VNFMStartStop{VNFCInstance: vnfcInstance}

	var err error

	if vnfcInstance == nil { // Start the VNF Record
		startStop.VNFR, err = worker.handler.Start(vnfr)
	} else { // Start the VNFC Instance
		startStop.VNFR, err = worker.handler.StartVNFCInstance(vnfr, vnfcInstance)
	}

	if err != nil {
		return nil, &vnfmError{err.Error(), vnfr, nsrID}
	}

	nfvMessage, err := messages.New(catalogue.ActionStart, startStop)
	if err != nil {
		worker.l.Panic("BUG: shouldn't happen")
	}

	return nfvMessage, nil
}

func (worker *worker) handleStop(startStopMessage *messages.OrStartStop) (messages.NFVMessage, *vnfmError) {
	vnfr := startStopMessage.VNFR
	nsrID := vnfr.ParentNsID
	vnfcInstance := startStopMessage.VNFCInstance

	startStop := &messages.VNFMStartStop{VNFCInstance: vnfcInstance}

	var err error
	if vnfcInstance == nil { // Start the VNF Record
		startStop.VNFR, err = worker.handler.Stop(vnfr)
	} else { // Start the VNFC Instance
		startStop.VNFR, err = worker.handler.StopVNFCInstance(vnfr, vnfcInstance)
	}

	if err != nil {
		return nil, &vnfmError{err.Error(), vnfr, nsrID}
	}

	nfvMessage, err := messages.New(catalogue.ActionStop, startStop)
	if err != nil {
		worker.l.Panic("BUG: shouldn't happen")
	}

	return nfvMessage, nil
}

func (worker *worker) handleUpdate(updateMessage *messages.OrUpdate) (messages.NFVMessage, *vnfmError) {
	vnfr := updateMessage.VNFR
	nsrID := vnfr.ParentNsID
	script := updateMessage.Script

	replyVNFR, err := worker.handler.UpdateSoftware(script, vnfr)
	if err != nil {
		return nil, &vnfmError{err.Error(), vnfr, nsrID}
	}

	nfvMessage, err := messages.New(catalogue.ActionUpdate, &messages.VNFMGeneric{
		VNFR: replyVNFR,
	})
	if err != nil {
		worker.l.Panic("BUG: shouldn't happen")
	}

	return nfvMessage, nil
}

func (worker *worker) allocateResources(
	vnfr *catalogue.VirtualNetworkFunctionRecord,
	vimInstances map[string]interface{},
	keyPairs []*catalogue.Key) (*catalogue.VirtualNetworkFunctionRecord, *vnfmError) {

	worker.l.Debug("allocating resources for the VNFR")

	userData := worker.handler.UserData()

	worker.l.Debug("will send to NFVO UserData")

	msg, err := messages.New(&messages.VNFMAllocateResources{
		VNFR:         vnfr,
		VIMInstances: vimInstances,
		Userdata:     userData,
		KeyPairs:     keyPairs,
	})
	if err != nil {
		worker.l.Panicf("BUG")
	}

	nfvoResp, err := worker.executeRpc("vnfm.nfvo.actions.reply", msg)
	if err != nil {
		worker.l.Error("exchange error")

		return nil, &vnfmError{
			msg:   "Unable to allocate Resources",
			nsrID: vnfr.ParentNsID,
			vnfr:  vnfr,
		}
	}

	if nfvoResp != nil {
		if nfvoResp.Action() == catalogue.ActionError {
			errorMessage := nfvoResp.Content().(*messages.OrError)

			worker.l.Error("received error message from the NFVO")

			errVNFR := errorMessage.VNFR

			return nil, &vnfmError{
				msg:   fmt.Sprintf("Unable to allocate Resources. Reason: %s", errorMessage.Message),
				vnfr:  errVNFR,
				nsrID: vnfr.ParentNsID,
			}
		}

		message := nfvoResp.Content().(*messages.OrGeneric)
		worker.l.Debug("received a VNFR from ALLOCATE")

		return message.VNFR, nil
	}

	return nil, &vnfmError{
		msg:   "received an empty message from the NFVO",
		nsrID: vnfr.ParentNsID,
		vnfr:  vnfr,
	}
}

repository: openbaton/go-openbaton

repo_name: openbaton/go-openbaton


text:
require recipes-kernel/linux/linux-yocto.inc

KERNEL_IMAGETYPE = "zImage"

COMPATIBLE_MACHINE = "icev2"

RDEPENDS_kernel-base += "kernel-devicetree"

KERNEL_DEVICETREE_icev2 = "am335x-icev2.dtb"

LINUX_VERSION = "4.9"

FILESEXTRAPATHS_prepend := "${THISDIR}/ti-linux_${LINUX_VERSION}:"

S = "${WORKDIR}/git"

PV = "4.9.44"
SRCREV= "c3148e7628f9dd0fdb237854e7275b5fdc1193db"
SRC_URI = " \
    git://git.ti.com/ti-linux-kernel/ti-linux-kernel.git;branch=ti-linux-4.9.y \
    file://defconfig \
    file://0001-ARM-dts-am335x-icev2-enable-leds-iio-node.patch \
    file://0002-ARM-dts-am335x-icev2-add-ssd1306fb-LCD-node.patch \
    file://0003-fs-jffs2-Add-setup-code-for-spi-nor-flash.patch \
"


text:
package crm

import (
	"encoding/xml"

	"github.com/bububa/opentaobao/model"
)

// TaobaoCrmMemberinfoUpdateAPIResponse 编辑会员资料 API返回值
// taobao.crm.memberinfo.update
//
// 编辑会员的基本资料，接口返回会员信息修改是否成功
type TaobaoCrmMemberinfoUpdateAPIResponse struct {
	model.CommonResponse
	TaobaoCrmMemberinfoUpdateAPIResponseModel
}

// TaobaoCrmMemberinfoUpdateAPIResponseModel is 编辑会员资料 成功返回结果
type TaobaoCrmMemberinfoUpdateAPIResponseModel struct {
	XMLName xml.Name `xml:"crm_memberinfo_update_response"`
	// 平台颁发的每次请求访问的唯一标识
	RequestId string `json:"request_id,omitempty" xml:"request_id,omitempty"`
	// 会员信息修改是否成功
	IsSuccess bool `json:"is_success,omitempty" xml:"is_success,omitempty"`
}


text:
package context

import (
	"context"
	"github.com/go-logr/logr"
	v1 "k8s.io/api/core/v1"
	"k8s.io/client-go/tools/record"
	"k8s.io/cloud-provider-alibaba-cloud/pkg/controller/service/reconcile/annotation"
)

type RequestContext struct {
	Ctx      context.Context
	Service  *v1.Service
	Anno     *annotation.AnnotationRequest
	Log      logr.Logger
	Recorder record.EventRecorder
}

repository: kubernetes/cloud-provider-alibaba-cloud

repo_name: kubernetes/cloud-provider-alibaba-cloud


text:
require anki.inc

RDEPENDS_${PN} += "libanki"
PR = "r3"

export PV := "${PV}"

SRC_URI += "file://no-need-for-pyqt-at-buildtime.patch"
S = "${WORKDIR}/anki-${PV}"

SRC_URI[md5sum] = "90434860945de4c09d55cdb5dbe984fc"
SRC_URI[sha256sum] = "18a93fb46363ca34963fc2588cadf7415dd799dd647efa681859eb8b1b22f104"


text:
// +build service

package jenkins

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/ImpactInsights/valuestream/eventsources"
	"github.com/ImpactInsights/valuestream/tracers"
	"github.com/stretchr/testify/assert"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"testing"
)

var baseURL string
var jenkinsPath string

var urlEnvVar = "TEST_EVENTS_URL"
var jenkinsPathEnvVar = "TEST_EVENTS_JENKINS_PATH"

func init() {
	ok := true
	baseURL, ok = os.LookupEnv(urlEnvVar)
	if !ok {
		panic(fmt.Sprintf("requires: %q", urlEnvVar))
	}
	jenkinsPath, ok = os.LookupEnv(jenkinsPathEnvVar)
	if !ok {
		panic(fmt.Sprintf("requires: %q", jenkinsPathEnvVar))
	}
}

var eventTests = []struct {
	Name                  string
	StartEventPath        string
	EndEventPath          string
	ExpectedOperationName string
	ExpectedTags          map[string]interface{}
}{
	{
		Name:                  "build_aborted",
		StartEventPath:        "fixtures/events/build/inprogress.json",
		EndEventPath:          "fixtures/events/build/aborted.json",
		ExpectedOperationName: "build",
		ExpectedTags: map[string]interface{}{
			"build.cause":                "Started by anonymous",
			"build.ci.url":               "http://localhost:8080/jenkins/",
			"build.context_id":           float64(1.02490963e+08),
			"build.job.full_name":        "jenkins_test",
			"build.job.name":             "jenkins_test",
			"build.number":               float64(252),
			"build.parameter.someParams": "someValue",
			"build.result":               "INPROGRESS",
			"build.started.user.id":      "anonymous",
			"build.started.user.name":    "anonymous",
			"build.url":                  "aUrl",
			"error":                      true,
			"scm.branch":                 "master",
			"scm.head.sha":               "aCommitHash",
			"scm.head.url":               "aGithubUrl",
			"service":                    "jenkins",
		},
	},
	{
		Name:                  "build_success",
		StartEventPath:        "fixtures/events/build/inprogress.json",
		EndEventPath:          "fixtures/events/build/success.json",
		ExpectedOperationName: "build",
		ExpectedTags: map[string]interface{}{
			"build.cause":                "Started by anonymous",
			"build.ci.url":               "http://localhost:8080/jenkins/",
			"build.context_id":           float64(1.02490963e+08),
			"build.job.full_name":        "jenkins_test",
			"build.job.name":             "jenkins_test",
			"build.number":               float64(252),
			"build.parameter.someParams": "someValue",
			"build.result":               "INPROGRESS",
			"build.started.user.id":      "anonymous",
			"build.started.user.name":    "anonymous",
			"build.url":                  "aUrl",
			"error":                      false,
			"scm.branch":                 "master",
			"scm.head.sha":               "aCommitHash",
			"scm.head.url":               "aGithubUrl",
			"service":                    "jenkins",
		},
	},
	{
		Name:                  "deploy_success",
		StartEventPath:        "fixtures/events/deploy/inprogress.json",
		EndEventPath:          "fixtures/events/deploy/success.json",
		ExpectedOperationName: "deploy",
		ExpectedTags: map[string]interface{}{
			"build.cause":                "Started by anonymous",
			"build.ci.url":               "http://localhost:8080/jenkins/",
			"build.context_id":           float64(1.02490963e+08),
			"build.job.full_name":        "jenkins_test",
			"build.job.name":             "deploy:jenkins_test",
			"build.number":               float64(252),
			"build.parameter.someParams": "someValue",
			"build.parameter.type":       "deploy",
			"build.result":               "INPROGRESS",
			"build.started.user.id":      "anonymous",
			"build.started.user.name":    "anonymous",
			"build.url":                  "aUrl",
			"error":                      false,
			"scm.branch":                 "master",
			"scm.head.sha":               "aCommitHash",
			"scm.head.url":               "aGithubUrl",
			"service":                    "jenkins",
		},
	},
}

func TestServiceEvent_Jenkins(t *testing.T) {
	client := &http.Client{}
	u, err := url.Parse(baseURL + jenkinsPath)
	assert.NoError(t, err)

	var te *eventsources.TestEvent

	for _, tt := range eventTests {
		t.Run(tt.Name, func(t *testing.T) {
			// reset the tracer
			resp1, err := http.Get(baseURL + "/mocktracer/reset")
			assert.NoError(t, err)
			defer resp1.Body.Close()
			assert.Equal(t, http.StatusOK, resp1.StatusCode)

			eventPaths := []string{
				tt.StartEventPath,
				tt.EndEventPath,
			}
			for _, eventPath := range eventPaths {
				te, err = eventsources.NewTestEventFromFixturePath(eventPath)
				assert.NoError(t, err)

				fmt.Printf("Path: %q, payload: %q, err: %q\n", eventPath, te, err)

				rawPayload, err := json.Marshal(te.Payload)
				assert.NoError(t, err)

				req, err := http.NewRequest(
					"POST",
					u.String(),
					bytes.NewReader(rawPayload),
				)
				eventResp, err := client.Do(req)

				assert.NoError(t, err)
				eventResp.Body.Close()
				assert.Equal(t, http.StatusOK, eventResp.StatusCode)
			}

			spansResp, err := http.Get(baseURL + "/mocktracer/finished-spans")
			assert.NoError(t, err)
			assert.Equal(t, http.StatusOK, spansResp.StatusCode)

			bs, err := ioutil.ReadAll(spansResp.Body)
			assert.NoError(t, err)
			spansResp.Body.Close()

			var spans []tracers.TestSpan

			err = json.Unmarshal(bs, &spans)
			assert.NoError(t, err)

			assert.Equal(t, 1, len(spans))

			if len(spans) == 1 {
				assert.Equal(t, tt.ExpectedOperationName, spans[0].Span.OperationName)
				assert.Equal(t, tt.ExpectedTags, spans[0].Tags)
			}
		})
	}
}

repository: welll/valuestream

repo_name: welll/valuestream


text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/api/bluetooth_socket/bluetooth_api_socket.h"

#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "device/bluetooth/bluetooth_socket.h"
#include "net/base/io_buffer.h"

namespace {

const char kSocketNotConnectedError[] = "Socket not connected";
const char kSocketNotListeningError[] = "Socket not listening";

}  // namespace

namespace extensions {

// static
static base::LazyInstance<BrowserContextKeyedAPIFactory<
    ApiResourceManager<BluetoothApiSocket>>>::DestructorAtExit
    g_server_factory = LAZY_INSTANCE_INITIALIZER;

// static
template <>
BrowserContextKeyedAPIFactory<ApiResourceManager<BluetoothApiSocket> >*
ApiResourceManager<BluetoothApiSocket>::GetFactoryInstance() {
  return g_server_factory.Pointer();
}

BluetoothApiSocket::BluetoothApiSocket(const std::string& owner_extension_id)
    : ApiResource(owner_extension_id),
      persistent_(false),
      buffer_size_(0),
      paused_(false),
      connected_(false) {
  DCHECK_CURRENTLY_ON(kThreadId);
}

BluetoothApiSocket::BluetoothApiSocket(
    const std::string& owner_extension_id,
    scoped_refptr<device::BluetoothSocket> socket,
    const std::string& device_address,
    const device::BluetoothUUID& uuid)
    : ApiResource(owner_extension_id),
      socket_(socket),
      device_address_(device_address),
      uuid_(uuid),
      persistent_(false),
      buffer_size_(0),
      paused_(true),
      connected_(true) {
  DCHECK_CURRENTLY_ON(kThreadId);
}

BluetoothApiSocket::~BluetoothApiSocket() {
  DCHECK_CURRENTLY_ON(kThreadId);
  if (socket_.get())
    socket_->Disconnect(base::DoNothing());
}

void BluetoothApiSocket::AdoptConnectedSocket(
    scoped_refptr<device::BluetoothSocket> socket,
    const std::string& device_address,
    const device::BluetoothUUID& uuid) {
  DCHECK_CURRENTLY_ON(kThreadId);

  if (socket_.get())
    socket_->Disconnect(base::DoNothing());

  socket_ = socket;
  device_address_ = device_address;
  uuid_ = uuid;
  connected_ = true;
}

void BluetoothApiSocket::AdoptListeningSocket(
    scoped_refptr<device::BluetoothSocket> socket,
    const device::BluetoothUUID& uuid) {
  DCHECK_CURRENTLY_ON(kThreadId);

  if (socket_.get())
    socket_->Disconnect(base::DoNothing());

  socket_ = socket;
  device_address_ = "";
  uuid_ = uuid;
  connected_ = false;
}

void BluetoothApiSocket::Disconnect(base::OnceClosure callback) {
  DCHECK_CURRENTLY_ON(kThreadId);

  if (!socket_.get()) {
    std::move(callback).Run();
    return;
  }

  connected_ = false;
  socket_->Disconnect(std::move(callback));
  socket_.reset();
}

bool BluetoothApiSocket::IsPersistent() const {
  DCHECK_CURRENTLY_ON(kThreadId);
  return persistent_;
}

void BluetoothApiSocket::Receive(int count,
                                 ReceiveCompletionCallback success_callback,
                                 ErrorCompletionCallback error_callback) {
  DCHECK_CURRENTLY_ON(kThreadId);

  if (!socket_.get() || !IsConnected()) {
    std::move(error_callback)
        .Run(BluetoothApiSocket::kNotConnected, kSocketNotConnectedError);
    return;
  }

  socket_->Receive(
      count, std::move(success_callback),
      base::BindOnce(&OnSocketReceiveError, std::move(error_callback)));
}

// static
void BluetoothApiSocket::OnSocketReceiveError(
    ErrorCompletionCallback error_callback,
    device::BluetoothSocket::ErrorReason reason,
    const std::string& message) {
  DCHECK_CURRENTLY_ON(kThreadId);
  BluetoothApiSocket::ErrorReason error_reason =
      BluetoothApiSocket::kSystemError;
  switch (reason) {
    case device::BluetoothSocket::kIOPending:
      error_reason = BluetoothApiSocket::kIOPending;
      break;
    case device::BluetoothSocket::kDisconnected:
      error_reason = BluetoothApiSocket::kDisconnected;
      break;
    case device::BluetoothSocket::kSystemError:
      error_reason = BluetoothApiSocket::kSystemError;
      break;
  }
  std::move(error_callback).Run(error_reason, message);
}

void BluetoothApiSocket::Send(scoped_refptr<net::IOBuffer> buffer,
                              int buffer_size,
                              SendCompletionCallback success_callback,
                              ErrorCompletionCallback error_callback) {
  DCHECK_CURRENTLY_ON(kThreadId);

  if (!socket_.get() || !IsConnected()) {
    std::move(error_callback)
        .Run(BluetoothApiSocket::kNotConnected, kSocketNotConnectedError);
    return;
  }

  socket_->Send(buffer, buffer_size, std::move(success_callback),
                base::BindOnce(&OnSocketSendError, std::move(error_callback)));
}

// static
void BluetoothApiSocket::OnSocketSendError(
    ErrorCompletionCallback error_callback,
    const std::string& message) {
  DCHECK_CURRENTLY_ON(kThreadId);
  std::move(error_callback).Run(BluetoothApiSocket::kSystemError, message);
}

void BluetoothApiSocket::Accept(AcceptCompletionCallback success_callback,
                                ErrorCompletionCallback error_callback) {
  DCHECK_CURRENTLY_ON(kThreadId);

  if (!socket_.get() || IsConnected()) {
    std::move(error_callback)
        .Run(BluetoothApiSocket::kNotListening, kSocketNotListeningError);
    return;
  }

  socket_->Accept(
      std::move(success_callback),
      base::BindOnce(&OnSocketAcceptError, std::move(error_callback)));
}

// static
void BluetoothApiSocket::OnSocketAcceptError(
    ErrorCompletionCallback error_callback,
    const std::string& message) {
  DCHECK_CURRENTLY_ON(kThreadId);
  std::move(error_callback).Run(BluetoothApiSocket::kSystemError, message);
}

}  // namespace extensions

repository: chromium/chromium

repo_name: chromium/chromium

extension: cc


text:
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"regexp"
	"strings"
)

type AppConfig struct {
	SearchString                string
	SearchStringIsRegex         bool
	SearchStringIsCaseSensitive bool
	EximFormatOnly              bool
}

var (
	Config                      AppConfig
	RegexEximMsgID, RegexSetEnd *regexp.Regexp
)

func init() {
	RegexEximMsgID = regexp.MustCompile(`\b[0-9A-Za-z]{6}-[0-9A-Za-z]{6}-[0-9A-Za-z]{2}\b`)
	RegexSetEnd = regexp.MustCompile(`Completed|SMTP data timeout|rejected`)

	flag.BoolVar(&Config.SearchStringIsRegex, "r", false, "Interpret search string as regular expression instead of fixed string")
	flag.BoolVar(&Config.SearchStringIsCaseSensitive, "c", false, "Search string is case sensitive")
	//flag.BoolVar(&Config.EximFormatOnly, "e", false, "Only match exim logfiles (only match exim timestamps instead of looking for an isolated message id string)")
	flag.Parse()

	if flag.NArg() < 1 {
		log.Fatal("Please provide a search string")
	} else {
		Config.SearchString = flag.Args()[0]
	}
}

type Match struct {
	Lines       []string
	Interesting bool
}

type MatchLine func(*string) bool
type MatchMessageID func(*string) (bool, string)

func main() {
	var (
		input io.Reader
	)

	// prepare line matcher
	var matcher MatchLine
	if Config.SearchStringIsRegex {
		var (
			re       *regexp.Regexp
			restring string
			err      error
		)
		if Config.SearchStringIsCaseSensitive {
			restring = Config.SearchString
		} else {
			restring = `(?i:` + Config.SearchString + `)`
		}
		re, err = regexp.Compile(restring)
		if err != nil {
			log.Fatalf("Error compiling search string »%s« as regular expression: %s", restring, err)
		}
		matcher = func(in *string) bool { return re.MatchString(*in) }
	} else {
		if Config.SearchStringIsCaseSensitive {
			matcher = func(in *string) bool { return strings.Contains(*in, Config.SearchString) }
		} else {
			searchStringLC := strings.ToLower(Config.SearchString)
			matcher = func(in *string) bool { return strings.Contains(strings.ToLower(*in), strings.ToLower(searchStringLC)) }
		}
	}

	// prepare message id matcher
	var msgidmatcher MatchMessageID
	// generic regex version
	msgidmatcher = func(in *string) (bool, string) {
		loc := RegexEximMsgID.FindStringIndex(*in)
		if loc == nil {
			return false, ""
		} else {
			return true, (*in)[loc[0]:loc[1]]
		}
	}

	// prepare inputs
	if flag.NArg() == 1 {
		input = os.Stdin
	} else {
		var infiles []io.Reader
		for _, filename := range flag.Args()[1:] {
			reader, err := os.Open(filename)
			if err == nil {
				infiles = append(infiles, reader)
			} else {
				log.Printf("Unable to open file %s: %s", filename, err)
			}
		}
		input = io.MultiReader(infiles...)
	}

	// search input
	var (
		LinesByMsgID = make(map[string]*Match)
	)
	scanner := bufio.NewScanner(input)
	for scanner.Scan() {
		line := scanner.Text()

		// find message id
		hasID, id := msgidmatcher(&line)
		// message has message ID
		if hasID {
			// message id known?
			match, exists := LinesByMsgID[id]
			if exists {
				// add line to existing struct
				match.Lines = append(match.Lines, line)
			} else {
				// create new struct
				match = &Match{Lines: []string{line}, Interesting: false}
				LinesByMsgID[id] = match
			}
			// does the line contain the search string?
			if matcher(&line) {
				match.Interesting = true
			}
			// is line the last line in the set?
			if RegexSetEnd.MatchString(line) {
				// only print interesting sets
				if match.Interesting {
					for _, l := range match.Lines {
						fmt.Println(l)
					}
					fmt.Println("")
				}
				delete(LinesByMsgID, id)
			}
		// matching line without associated message id
		} else {
			if matcher(&line) {
				fmt.Println(line)
			}
		}
	}
}

repository: hreese/myexigrep

repo_name: hreese/myexigrep


text:
package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"

	flag "github.com/jessevdk/go-flags"
	"github.com/qlcchain/qlc-hub/config"
	"github.com/qlcchain/qlc-hub/grpc"
	pb "github.com/qlcchain/qlc-hub/grpc/proto"
	"github.com/qlcchain/qlc-hub/pkg/jwt"
	"github.com/qlcchain/qlc-hub/pkg/log"
	"github.com/qlcchain/qlc-hub/pkg/util"
)

var (
	version = "dev"
	date    = ""
	commit  = ""
)

var cfg = &config.SignerConfig{}

func main() {
	fmt.Println(logo())
	fmt.Printf("signer %s-%s.%s", version, commit, date)
	fmt.Println()

	if _, err := flag.ParseArgs(cfg, os.Args); err != nil {
		code := 1
		if fe, ok := err.(*flag.Error); ok {
			if fe.Type == flag.ErrHelp {
				code = 0
			} else {
				log.Root.Error(err)
			}
		}

		os.Exit(code)
	}

	if err := cfg.Verify(); err != nil {
		fmt.Println(util.ToIndentString(cfg))
		log.Root.Fatal(err)
	}

	if cfg.Verbose {
		cfg.LogLevel = "debug"
	}
	_ = log.Setup(cfg.LogDir(), cfg.LogLevel)

	logger := log.NewLogger("signer/main")
	logger.Info(util.ToIndentString(cfg))

	r1 := cfg.AddressList(pb.SignType_NEO)
	logger.Info("NEO: ", util.ToIndentString(r1))

	r2 := cfg.AddressList(pb.SignType_ETH)
	logger.Info("ETH: ", util.ToIndentString(r2))

	for i := 0; i < 10; i++ {
		if token, err := cfg.JwtManager.Generate(jwt.User); err == nil {
			logger.Debugf("%d: %s", i, token)
		}
	}

	server, err := grpc.NewSignerServer(cfg)
	if err != nil {
		logger.Fatal(err)
	}

	if err := server.Start(); err != nil {
		logger.Fatal(err)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
	<-c

	if server != nil {
		server.Stop()
	}
}

func logo() string {
	return `
 ____     ___   ___     ___ ______  __ __       _____ ____   ____  ____     ___  ____
|    \   /  _] /   \   /  _]      ||  |  |     / ___/|    | /    ||    \   /  _]|    \
|  _  | /  [_ |     | /  [_|      ||  |  |    (   \_  |  | |   __||  _  | /  [_ |  D  )
|  |  ||    _]|  O  ||    _]_|  |_||  _  |     \__  | |  | |  |  ||  |  ||    _]|    /
|  |  ||   [_ |     ||   [_  |  |  |  |  |     /  \ | |  | |  |_ ||  |  ||   [_ |    \
|  |  ||     ||     ||     | |  |  |  |  |     \    | |  | |     ||  |  ||     ||  .  \
|__|__||_____| \___/ |_____| |__|  |__|__|      \___||____||___,_||__|__||_____||__|\_|

`
}

repository: bcskill/qlc-hub

repo_name: bcskill/qlc-hub


text:
package slogger

import "strings"

type SloggerSettings struct {
	LogLevel     LogLevel
	LogName      string
	LogDirectory string
	LogExtension string
}

func (self *SloggerSettings) Trim() {
	for {
		length := len(self.LogDirectory)
		self.LogDirectory = strings.TrimRight(self.LogDirectory, "/")
		self.LogDirectory = strings.TrimRight(self.LogDirectory, "\\")
		if length == len(self.LogDirectory) {
			return
		}
	}
}

repository: flowtumn/slogger

repo_name: flowtumn/slogger


text:
SUMMARY = "The Cython compiler for writing C extensions for the Python language."
DESCRIPTION = "Cython is a language specially designed for writing Python extension modules. \
It's designed to bridge the gap between the nice, high-level, easy-to-use world of Python \
and the messy, low-level world of C."
HOMEPAGE = "https://cython.org/"
SECTION = "devel/python"

LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=e23fadd6ceef8c618fc1c65191d846fa"

SRC_URI[md5sum] = "6e2f139e30bb08d68366f9370d87964c"
SRC_URI[sha256sum] = "e4d6bb8703d0319eb04b7319b12ea41580df44fd84d83ccda13ea463c6801414"

UPSTREAM_CHECK_URI = "https://pypi.python.org/pypi/Cython/"
UPSTREAM_CHECK_REGEX = "/Cython/(?P<pver>(\d+[\.\-_]*)+)"

PYPI_PACKAGE = "Cython"

inherit pypi setuptools

RDEPENDS:${PN}:class-target += "\
    ${PYTHON_PN}-distribute \
    ${PYTHON_PN}-misc \
    ${PYTHON_PN}-netserver \
    ${PYTHON_PN}-pkgutil \
    ${PYTHON_PN}-pyparsing \
    ${PYTHON_PN}-setuptools \
    ${PYTHON_PN}-shell \
    ${PYTHON_PN}-subprocess \
    ${PYTHON_PN}-xml \
"

RDEPENDS:${PN}:class-nativesdk += "\
    nativesdk-${PYTHON_PN}-misc \
    nativesdk-${PYTHON_PN}-netserver \
    nativesdk-${PYTHON_PN}-pkgutil \
    nativesdk-${PYTHON_PN}-pyparsing \
    nativesdk-${PYTHON_PN}-setuptools \
    nativesdk-${PYTHON_PN}-shell \
    nativesdk-${PYTHON_PN}-xml \
"

do_install:append() {
	# Make sure we use /usr/bin/env python
	for PYTHSCRIPT in `grep -rIl '^#!.*python' ${D}`; do
		sed -i -e '1s|^#!.*|#!/usr/bin/env ${PYTHON_PN}|' $PYTHSCRIPT
	done
}

BBCLASSEXTEND = "native nativesdk"

SKIP_RECIPE[python-cython] ?= "${@bb.utils.contains('I_SWEAR_TO_MIGRATE_TO_PYTHON3', 'yes', '', 'python2 is out of support for long time, read https://www.python.org/doc/sunset-python-2/ https://python3statement.org/ and if you really have to temporarily use this, then set I_SWEAR_TO_MIGRATE_TO_PYTHON3 to "yes"', d)}"

branch_name: refs/heads/jansa/master


text:
#include"../../../timer.h"
#include<fmt/format.h>

int main()
{
	constexpr std::uint32_t N(10000000);
	std::size_t value{};
	{
	fast_io::timer t("fmt::format_int");
	for(std::uint32_t i{};i!=N;++i)
		value+=fmt::format_int(i).str().size();
	}
	println("value:",value);
}


text:
@article{xie,
  title = {Bookdown: {{Authoring Books}} and {{Technical Documents}} with {{R Markdown}}},
  language = {en},
  author = {Xie, Yihui},
  pages = {137},
  file = {C:\\Code\\zotero-current\\storage\\98JMRLSM\\Xie - bookdown Authoring Books and Technical Documents .pdf;C:\\Code\\zotero-current\\storage\\PY2CKASC\\Xie - bookdown Authoring Books and Technical Documents .pdf;C:\\Code\\zotero-current\\storage\\TI6WVM8C\\Xie - bookdown Authoring Books and Technical Documents .pdf;C:\\Code\\zotero-current\\storage\\BK6H7B9U\\cross-references.html}
}

@misc{subirana,
  title = {{{compareGroups}} 4.0: {{Descriptives}} by Groups},
  author = {Subirana, Isaac and Vila, Joan and Sanz, Hector},
  file = {C:\\Code\\zotero-current\\storage\\IYDY26GR\\compareGroups_vignette.html}
}


text:
package contentful_go

import "github.com/Khaledgarbaya/contentful_go/entities"

//Space a complete definition of a contentful space
type Space struct {
	Sys entities.Sys
}


text:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
unsigned long long n,m,flag=0,i=0;
cin>>n>>m;

for(int i=62;i>=0;i--)
{
if(m&((unsigned long long int )1<<i))
{
if(flag==0)
cout<<"("<<n<<"<<"<<i<<")";
else
cout<<" + ("<<n<<"<<"<<i<<")";
flag=1;
}
}
cout<<endl;
}
}

extension: cpp


text:
# ----------------------------------------------------------------------------------------------------------------------
# Functions:
# ----------------------------------------------------------------------------------------------------------------------

# Function:    arepa_get_target_sources
# Description:
#
#     Extracts a list of source files specified in a target.
#
# Arguments:
#
#     * `out_var`       - The output variable.
#     * `target_name`   - The target name.
#
function(arepa_get_target_sources out_var target_name)
	set(files "")
	foreach(target ${target_name})
		get_target_property(target_sources "${target}" SOURCES)
		list(APPEND files ${target_sources})
	endforeach()
	set("${out_var}" "${files}" PARENT_SCOPE)
endfunction(arepa_get_target_sources)

# Function:    arepa_get_target_headers
# Description:
#
#     Extracts a list of header files (roughly) specified in a target.
#
# Arguments:
#
#     * `out_var`       - The output variable.
#     * `target_name`   - The target name.
#
function(arepa_get_target_headers out_var target_name)
	set(files "")
	foreach(target ${target_name})
		get_target_property(target_dir "${target}" SOURCE_DIR)
		get_target_property(target_include_dirs "${target}" INCLUDE_DIRECTORIES)
		foreach (include_dir ${target_include_dirs})
			# If it's a generator, extract the absolute path.
			if ("${include_dir}" MATCHES "^\\$<BUILD_INTERFACE:(.*)>$")
				set(include_dir "${CMAKE_MATCH_1}")
			elseif ("${include_dir}" MATCHES "^\\$")
				# We ignore any other generators.
				continue()
			endif()

			# If it's outside the module directory, skip it.
			file(RELATIVE_PATH include_dir_relative "${target_dir}" "${include_dir}")
			if ("${include_dir_relative}" MATCHES "^\\.")
				continue()
			endif()

			# Recursively glob all the header files.
			file(GLOB_RECURSE target_headers
					"${include_dir}/*.hpp"
					"${include_dir}/*.h"
			)

			list(APPEND files ${target_headers})
		endforeach()
	endforeach()
	set("${out_var}" "${files}" PARENT_SCOPE)
endfunction(arepa_get_target_headers)

repository: selfeki/social-gaming-platform

repo_name: selfeki/social-gaming-platform


text:
package dp

import "fmt"

/*
时间：O(n^2)
空间：O(n)
方法一：dp

方法二：dp+二分
时间：O(nlogn)
空间：O(n)
*/
func LengthOfLIS1(nums []int) int {
	if len(nums) == 0 {
		return 0
	}
	// dp[i]表示长度为i+1的末尾值最小的LIS
	d := make([]int, 0)
	for _, v := range nums {
		if len(d) == 0 || v > d[len(d)-1] {
			d = append(d, v)
		} else {
			l, r := 0, len(d)-1
			for l < r {
				mid := (l + r) / 2
				if v > d[mid] {
					l = mid + 1
				} else {
					r = mid
				}
			}
			d[l] = v
		}
	}
	return len(d)
}

func LengthOfLIS(nums []int) int {
	if len(nums) == 0 {
		return 0
	}
	dp := make([]int, len(nums))
	for i := 0; i < len(nums); i++ {
		dp[i] = 1
		for j := 0; j < i; j++ {
			if nums[i] > nums[j] {
				dp[i] = max(dp[i], dp[j]+1)
			} else {
				dp[i] = max(dp[i], dp[j])
			}
		}
	}
	fmt.Println(dp)
	return dp[len(nums)-1]
}

repository: Lcoderfit/Introduction-to-algotithms

path: /GoLeetcode/dpTag/dp/300. 最长上升子序列.go

repo_name: Lcoderfit/Introduction-to-algotithms

filename: 300. 最长上升子序列.go


text:
package shared

import (
	"log"
	"os"
	"runtime"
)

// Credits to https://twinnation.org/articles/35/how-to-add-colors-to-your-console-terminal-output-in-go for colourization.

var Reset = "\033[0m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
var Purple = "\033[35m"
var Cyan = "\033[36m"
var Gray = "\033[37m"
var White = "\033[97m"

func init() {

	if runtime.GOOS == "windows" {
		Reset = ""
		Red = ""
		Green = ""
		Yellow = ""
		Blue = ""
		Purple = ""
		Cyan = ""
		Gray = ""
		White = ""
	}
}

func InfoLog(str string) {
	log.Printf(Green + "[INFO]" + Reset + ": " + str)
}

func ErrorLog(str string) {
	log.Printf(Red + "[ERROR]" + Reset + ": " + str)
}

func MessageLog(sender, method, msg string) {
	log.Printf(Cyan+"Message Received"+Reset+": %s says (via %s): %s", sender, method, msg)
}

func CheckError(err error) {

	if err != nil {
		log.Printf("<<Error>>: %s", err.Error())
		os.Exit(1)
	}

}


text:
LICENSE = "GPL"
inherit gpe

DESCRIPTION = "GPE to-do list"
DEPENDS = "gtk+ libdisplaymigration libgpewidget libgpepimc libtododb"
SECTION = "gpe"
PRIORITY = "optional"


text:
////////////////////////////////////////////////////////////////////////////////
// Filename: ApplicationMetrics.h
////////////////////////////////////////////////////////////////////////////////
#pragma once

//////////////
// INCLUDES //
//////////////
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include "Modules\VulkanWrapper\VulkanWrapper.h"
#include "ApplicationInstance.h"

///////////////
// NAMESPACE //
///////////////

/////////////
// DEFINES //
/////////////
#include <json.hpp>

////////////
// GLOBAL //
////////////

///////////////
// NAMESPACE //
///////////////

////////////////
// FORWARDING //
////////////////

////////////////////////////////////////////////////////////////////////////////
// Class name: ApplicationMetrics
////////////////////////////////////////////////////////////////////////////////
class ApplicationMetrics
{
public:

	// Our metric data
	struct MetricData
	{
		// The current build number
		uint32_t currentBuildNumber;

		// The last build normalized framerate
		uint32_t lastBuildNormalizedFramerate;

		// The last build normalized frametime
		double lastBuildNormalizedFrametime;

		// The last build normalized framerate
		uint32_t normalizedFramerate;

		// The last build normalized frametime
		double normalizedFrametime;
	};

//////////////////
// CONSTRUCTORS //
public: //////////

	// Constructor / destructor
	ApplicationMetrics();
	~ApplicationMetrics();

//////////////////
// MAIN METHODS //
public: //////////

	// Initialize
	virtual bool Initialize(const char* _metricFile);

	// Release
	virtual void Release();

	// Return the metric data
	MetricData& GetMetricData() { return m_MetricData; }

public:

	// Process a frame data
	void UpdateFrameData(uint32_t _fps, double _ft);

private:

	// Load all metric data
	bool LoadMetricData();

	// Save all metric data
	bool SaveMetricData();

///////////////
// VARIABLES //
private: //////

	// A reference to the metric file name
	const char* m_MetricFile;

	// Our metric data
	MetricData m_MetricData;

	// Our frame info
	std::vector<uint32_t> m_FramerateVector;
	std::vector<double> m_FrametimeVector;
};

repository: RodrigoHolztrattner/Wonderland

repo_name: RodrigoHolztrattner/Wonderland


text:
#pragma once

#include <dodbm/builders/operation.hpp>
#include <dodbm/operations/update_data.hpp>

#include <dodbm/builders/helpers/has_schema.hpp>
#include <dodbm/builders/helpers/has_table.hpp>

namespace dodbm
{
    namespace builders
    {
        class update_data : public builders::operation<operations::update_data>
            , public helpers::has_schema<update_data>
            , public helpers::has_table<update_data>
        {
        public:

            using operation::operation;

            template<typename T>
            const update_data& set(const std::string& column, const T& value) const
            {
                return set({ { column, value } });
            }

            const update_data& set(std::initializer_list<db_data> data) const;
        };
    }
}

repository: WopsS/dodbm

repo_name: WopsS/dodbm

extension: hpp


text:
SUMMARY = "Rubber Band Library library for audio time-stretching and pitch-shifting"
HOMEPAGE = "http://breakfastquay.com/rubberband/"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://COPYING;md5=45422928b8a498b809772c5bac1ba4ed"

inherit autotools-brokensep pkgconfig

DEPENDS = "libsndfile1"

SRC_URI = " \
    https://code.soundsoftware.ac.uk/attachments/download/1520/${BPN}-${PV}.tar.gz \
    file://0001-do-not-perform-test-it-tries-to-run-cross-binaries.patch \
"
SRC_URI[md5sum] = "200d6f5980d8d8877d296975a7e2890b"
SRC_URI[sha256sum] = "d0d3578137ac0c1e63f31561081a8d61da526a81152bc1dc9383b629bc07f85f"

do_compile() {
    oe_runmake sdk plugins host rdfgen
}

FILES_${PN} += "${libdir}/vamp"


text:
// Copyright (c) 2017 AnUnnamedProject
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.

package framework

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

// TestRule
// TODO:
func TestRule(t *testing.T) {

}

// TestRules
// TODO:
func TestRules(t *testing.T) {

}

func TestValidForm(t *testing.T) {
	r, _ := http.NewRequest("GET", "/", nil)
	c := NewContext(NewResponseWriter(httptest.NewRecorder()), &Request{Request: r})
	c.ParseForm()

	c.Request.Form.Add("required", "1")

	valid := NewValidator(c)
	valid.Rule("required", "required", "Required", "")
	err := valid.ValidForm()
	if err != nil {
		t.Error(err)
	}
}

func TestValidJSON(t *testing.T) {
	r, _ := http.NewRequest("GET", "/", nil)
	r.Header.Add("Content-Type", "application/json")

	c := NewContext(NewResponseWriter(httptest.NewRecorder()), &Request{Request: r})

	c.Request.JSON = &JSONData{
		m: make(map[string]*JSONValue),
	}

	c.Request.JSON.Set("required", "1")
	c.Request.JSON.Set("required2", 1)
	c.Request.JSON.Set("required4", 1.2)
	c.Request.JSON.Set("required3", true)

	valid := NewValidator(c)
	valid.Rule("required", "required", "Required", "")
	err := valid.ValidJSON()
	if err != nil {
		t.Error(err)
	}
}

func TestRequired(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    interface{}
		expected bool
	}{
		{nil, false},
		{"", false},
		{"ok", true},
		{true, true},
		{false, true},
		{0, false},
		{1, true},
	}
	for _, test := range tests {
		actual := valid.Required(test.value)
		if actual != test.expected {
			t.Errorf("Required(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestMin(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    int
		length   int
		expected bool
	}{
		{-1, 0, false},
		{1, 0, true},
	}
	for _, test := range tests {
		actual := valid.Min(test.value, test.length)
		if actual != test.expected {
			t.Errorf("Min(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestMinLength(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		length   int
		expected bool
	}{
		{"", 1, false},
		{"ok", 2, true},
	}
	for _, test := range tests {
		actual := valid.MinLength(test.value, test.length)
		if actual != test.expected {
			t.Errorf("MinLength(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestMax(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    int
		length   int
		expected bool
	}{
		{1, 0, false},
		{-1, 0, true},
	}
	for _, test := range tests {
		actual := valid.Max(test.value, test.length)
		if actual != test.expected {
			t.Errorf("Max(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestMaxLength(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		length   int
		expected bool
	}{
		{"", 1, true},
		{"ok", 1, false},
		{"ok", 2, true},
	}
	for _, test := range tests {
		actual := valid.MaxLength(test.value, test.length)
		if actual != test.expected {
			t.Errorf("MaxLength(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestExact(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    int
		length   int
		expected bool
	}{
		{0, 1, false},
		{1, 1, true},
	}
	for _, test := range tests {
		actual := valid.Exact(test.value, test.length)
		if actual != test.expected {
			t.Errorf("Exact(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestExactLength(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		length   int
		expected bool
	}{
		{"", 1, false},
		{"OK", 2, true},
	}
	for _, test := range tests {
		actual := valid.ExactLength(test.value, test.length)
		if actual != test.expected {
			t.Errorf("ExactLength(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestAlpha(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"\n", false},
		{"\r", false},
		{"", true},
		{"abc1", false},
		{"abc", true},
		{"ABC", true},
		{"123", false},
		{"0", false},
		{"123.123", false},
		{" ", false},
		{".", false},
		{"-", false},
	}
	for _, test := range tests {
		actual := valid.Alpha(test.value)
		if actual != test.expected {
			t.Errorf("Alpha(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestAlphaNumeric(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"\n", false},
		{"\r", false},
		{"", true},
		{"abc1", true},
		{"abc", true},
		{"ABC", true},
		{"123", true},
		{"0", true},
		{"123.123", false},
		{" ", false},
		{".", false},
		{"-", false},
	}
	for _, test := range tests {
		actual := valid.AlphaNumeric(test.value)
		if actual != test.expected {
			t.Errorf("AlphaNumeric(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestNumeric(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"\n", false},
		{"\r", false},
		{"", true},
		{"abc1", false},
		{"abc", false},
		{"ABC", false},
		{"123", true},
		{"0", true},
		{"123.123", false},
		{" ", false},
		{".", false},
		{"-", false},
	}
	for _, test := range tests {
		actual := valid.Numeric(test.value)
		if actual != test.expected {
			t.Errorf("Numeric(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestFloat(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"\n", false},
		{"\r", false},
		{"", true},
		{"abc1", false},
		{"abc", false},
		{"ABC", false},
		{"123", true},
		{"0", true},
		{"123.123", true},
		{" ", false},
		{".", true},
		{"-", false},
		{"-20", true},
	}
	for _, test := range tests {
		actual := valid.Float(test.value)
		if actual != test.expected {
			t.Errorf("Float(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestURL(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"", false},
		{"http://example.com#", true},
		{"http://example.com", true},
		{"https://example.com", true},
		{"example.com", true},
		{"http://example.info/", true},
		{"http://example.org/", true},
		{"http://example.ORG", true},
		{"http://example.org:80/", true},
		{"ftp://example.com/", true},
		{"ftp.example.com", true},
		{"http://user:pass@www.example.com/", true},
		{"http://user:pass@www.example.com/path", true},
		{"http://127.0.0.1/", true},
		{"http://localhost:8000/", true},
		{"http://example.com/?foo=bar&bar=foo", true},
		{"invalid.", false},
		{".com", false},
		{"mailto:me@example.com", true},
		{"/local/dir", false},
		{"http://example .org", false},
		{"example", false},
		{"http://.example.com", false},
		{"http://cant-end-with-hyphen-.example.com", false},
		{"http://-cant-start-with-hyphen.example.com", false},
		{"http://www.domain-can-contain-dashes.com", true},
	}
	for _, test := range tests {
		actual := valid.URL(test.value)
		if actual != test.expected {
			t.Errorf("URL(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestEmail(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"", false},
		{"x@x.x", true},
		{"me@example.com", true},
		{"me+alias@example.com", true},
		{"me@example.co.uk", true},
		{"me@example.travel", true},
		{"invalid@", false},
		{"invalid.com", false},
		{"@invalid.com", false},
	}
	for _, test := range tests {
		actual := valid.Email(test.value)
		if actual != test.expected {
			t.Errorf("Email(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestIP(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"", false},
		{"127.0.0.1", true},
		{"::1", true},
		{"255.255.255.256", false},
	}
	for _, test := range tests {
		actual := valid.IP(test.value)
		if actual != test.expected {
			t.Errorf("IP(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

func TestBase64(t *testing.T) {
	t.Parallel()

	valid := &Validator{}

	var tests = []struct {
		value    string
		expected bool
	}{
		{"", false},
		{"12345", false},
		{"SGVsbG8=", true},
	}
	for _, test := range tests {
		actual := valid.Base64(test.value)
		if actual != test.expected {
			t.Errorf("Base64(%q) is expected to be %v, got %v", test.value, test.expected, actual)
		}
	}
}

repository: AnUnnamedProject/framework

repo_name: AnUnnamedProject/framework


text:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteMiddle(ListNode* head) {
        int sz = 0;
        ListNode* h = head;
        while (h) h = h -> next, sz++;
        if (sz == 1) return nullptr;
        int del = sz / 2;
        h = head;
        int i = 1;
        while (i < del) i++, h = h -> next;
        h -> next = h -> next -> next;
        return head;

    }
};

repository: dezhonger/LeetCode

repo_name: dezhonger/LeetCode


text:
/*
 * \file Key.h
 * \copyright (C) 2020 Special Technological Center Ltd
 * \author : Bardashevsky A.K.
 * \date : 27.12.2020
 * \time : 22:01
 */

#pragma once

#include "Event.h"

namespace bard::Events {

struct Key : public Event
{
    EVENT_CLASS_CATEGORY( Category::Keyboard | Category::Input )
    const int keycode;

protected:
    explicit Key( int keycode) : keycode( keycode ) {}
};

struct KeyPressed : public Key
{
    EVENT_CLASS_TYPE( Type::KeyPressed )
    KeyPressed( int keycode, int repeatCount )
            : Key( keycode ), repeatCount( repeatCount ) { }

    const int repeatCount;
};

struct KeyReleased : public Key
{
    EVENT_CLASS_TYPE( Type::KeyReleased )
    explicit KeyReleased( int keycode ) : Key( keycode ) { }
};

struct KeyTyped : public Key
{
    EVENT_CLASS_TYPE( Type::KeyTyped )
    explicit KeyTyped( int keycode) : Key( keycode ) {}
};

}


text:
package art

import (
	"github.com/llgcode/draw2d/draw2dimg"
	"image"
	"image/color"
	"image/draw"
	"image/png"

	"crypto/md5"
	"io"
)

var encoder = png.Encoder{CompressionLevel: png.BestSpeed}

type Request struct {
	bytes         []byte
	width, height int
	numLeaves     int
}

func NewRequest(seed string) Request {
	sum := md5.Sum([]byte(seed))
	r := Request{
		bytes:  sum[:],
		width:  400,
		height: 400,
	}
	r.numLeaves = r.Consume()%5 + 3 // [3-7]
	return r
}
func (r *Request) Consume() int {
	first := r.bytes[0]
	r.bytes = r.bytes[1:]
	return int(first)
}

func (r *Request) SetSize(size int) {
	r.width = size
	r.height = size
}

func (r *Request) RenderPNG(w io.Writer) {
	bg_color := color.RGBA{0x55, 0, 0, 0xff}
	img := image.NewRGBA(image.Rect(0, 0, r.width, r.height))
	draw.Draw(img, img.Bounds(), &image.Uniform{bg_color}, image.ZP, draw.Src)

	// Draw actual spiro
	gc := draw2dimg.NewGraphicContext(img)
	t := NewTracer(r)
	// This doesn't work as expected.
	// TODO: Palettes!
	for opacity := 0xff; opacity > 0; opacity -= 0x30 {
		t.Draw(gc, color.RGBA{0xff, 0xff, uint8(opacity), 0xff})
		t.Step()
	}

	encoder.Encode(w, img)
}


text:
package data

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

//MongoClient for Database handling.
type MongoClient struct{
	ctx *context.Context
	client *mongo.Client
}

// New Client initialization.
func NewMongoClient(ct *context.Context, clt *mongo.Client) *MongoClient{
	return &MongoClient{
		ctx: ct,
		client: clt,
	}
}

//getting data from db.
func (p* MongoClient)GetData() (Plist, error){
	collection := p.client.Database("users").Collection("info")

	var personsData Plist
	ctx,cancel := context.WithTimeout(context.TODO(),10*time.Second)
	defer cancel()
	curr, err := collection.Find(ctx, bson.M{},options.Find().SetProjection(bson.M{"_id":0,"password":0,"username":0}))

	if err!=nil{
		return nil, err
	}
	if err = curr.All(ctx,&personsData);err!=nil{
		return nil, err
	}

	return personsData,nil
}

func (p* MongoClient)FindUser(route *string) (*Person,error){

	coll := p.client.Database("users").Collection("info")
	ctx,cancel := context.WithTimeout(context.TODO(), 5*time.Second)
	defer cancel()
	var personData Person

	err := coll.FindOne(
		ctx,
		bson.M{"route":route},
		options.FindOne().SetProjection(bson.M{"_id":0}),
	).Decode(&personData)

	if err!=nil{
		return nil,err
	}
	return &personData, nil
}

repository: bisakhmondal/LabBackend

repo_name: bisakhmondal/LabBackend