text:
package driver

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"strings"

	"github.com/edgexfoundry/go-mod-core-contracts/clients/logger"
)

type GPIODev struct {
	lc   logger.LoggingClient
	gpio int
}

func NewGPIODev(lc logger.LoggingClient) *GPIODev {
	return &GPIODev{lc: lc, gpio: -1}
}

func (dev *GPIODev) ExportGPIO(gpio int) error {
	err := exportgpio(gpio)
	if err == nil {
		dev.gpio = gpio
	}
	return err
}

func (dev *GPIODev) UnexportGPIO(gpio int) error {
	err := unexportgpio(gpio)
	if err == nil {
		dev.gpio = -1
	}
	return err
}

func (dev *GPIODev) SetDirection(direction string) error {
	if dev.gpio == -1 {
		return errors.New("Please export gpio first")
	}
	return setgpiodirection(dev.gpio, direction)
}

func (dev *GPIODev) GetDirection() (string, error) {
	if dev.gpio == -1 {
		return "", errors.New("Please export gpio first")
	}
	direction, err := getgpiodirection(dev.gpio)
	if err != nil {
		return "", err
	} else {
		res, _ := json.Marshal(map[string]interface{}{"gpio": dev.gpio, "direction": direction})
		return string(res), err
	}
}

func (dev *GPIODev) SetGPIO(gpio int, value bool) error {
	if gpio < 0 || gpio > 255 {
		return errors.New("gpio out of range")
	}

	exportgpio(gpio)
	err := setgpiodirection(gpio, "out")
	if err == nil {
		return setgpiovalue(gpio, value)
	}

	return err
}

func (dev *GPIODev) GetGPIO(gpio int) (string, error) {

	if gpio < 0 || gpio > 255 {
		return "", errors.New("gpio out of range")
	}

	exportgpio(gpio)
	err := setgpiodirection(gpio, "in")
	if err == nil {
		gpiovalue, err := getgpiovalue(gpio)
		if err != nil {
			return "", err
		} else {
			if gpiovalue == 0 {
				return "false", nil
			} else {
				return "true", nil
			}
		}
	}
	return "", err
}

func exportgpio(gpioNum int) error {
	path := fmt.Sprintf("/sys/class/gpio/gpio%d", gpioNum)
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		return nil
	} else {
		return ioutil.WriteFile("/sys/class/gpio/export", []byte(fmt.Sprintf("%d\n", gpioNum)), 0644)
	}
}

func unexportgpio(gpioNum int) error {
	path := fmt.Sprintf("/sys/class/gpio/gpio%d", gpioNum)
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		return ioutil.WriteFile("/sys/class/gpio/unexport", []byte(fmt.Sprintf("%d\n", gpioNum)), 0644)
	} else {
		return nil
	}
}

func setgpiodirection(gpioNum int, direction string) error {
	path := fmt.Sprintf("/sys/class/gpio/gpio%d", gpioNum)
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		var way string
		if direction == "in" {
			way = "in"
		} else {
			way = "out"
		}
		return ioutil.WriteFile(fmt.Sprintf("/sys/class/gpio/gpio%d/direction", gpioNum), []byte(way), 0644)
	} else {
		return errors.New("Please export gpio first")
	}
}

func getgpiodirection(gpioNum int) (string, error) {
	path := fmt.Sprintf("/sys/class/gpio/gpio%d", gpioNum)
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		direction, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/gpio/gpio%d/direction", gpioNum))
		if err != nil {
			return "", err
		} else {
			return strings.Replace(string(direction), "\n", "", -1), err
		}
	} else {
		return "", errors.New("Please export gpio first")
	}
}

func setgpiovalue(gpioNum int, value bool) error {
	path := fmt.Sprintf("/sys/class/gpio/gpio%d", gpioNum)
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		var tmp string
		if value == false {
			tmp = "0"
		} else {
			tmp = "1"
		}
		return ioutil.WriteFile(fmt.Sprintf("/sys/class/gpio/gpio%d/value", gpioNum), []byte(tmp), 0644)
	} else {
		return errors.New("Please export gpio first")
	}
}

func getgpiovalue(gpioNum int) (int, error) {
	path := fmt.Sprintf("/sys/class/gpio/gpio%d", gpioNum)
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		ret, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/gpio/gpio%d/value", gpioNum))
		if err != nil {
			return 0, err
		} else {
			value, _ := strconv.Atoi(strings.Replace(string(ret), "\n", "", -1))
			return value, err
		}
	} else {
		return -1, errors.New("Please export gpio first")
	}
}

repository: rddigital/device-mqtt-go

repo_name: rddigital/device-mqtt-go


text:
#pragma once

#include "..\..\abstract\Beverage.h"

class DarkRoast : public Beverage
{
public:
	DarkRoast();
	~DarkRoast();

	virtual float Cost() const;
};

license: MIT

repository: alissonads/Design-Patterns-cplusplus

license_type: permissive

repo_name: alissonads/Design-Patterns-cplusplus

branch_name: refs/heads/master

extension: h


text:
// Copyright 2018 Saferwall. All rights reserved.
// Use of this source code is governed by Apache v2 license
// license that can be found in the LICENSE file.

package mcafee

import (
	"context"
	"regexp"
	"strings"

	multiav "github.com/saferwall/saferwall/internal/multiav"
	"github.com/saferwall/saferwall/internal/utils"
)

const (
	cmd          = "/opt/mcafee/uvscan"
	regVersion   = `Linux64 Version: ([\\d\\.]+)[\\s\\S]+Engine version: ([\\d\\.]+)[\\s\\S]+set version: ([\\d\\.]+)`
	regDetection = `Found (the|potentially unwanted program|trojan or variant) (.*)( !!!|\.)`
)

// Scanner represents an empty struct that can be used to a method received.
type Scanner struct{}

// Version represents all mcafee components' versions
type Version struct {
	AVEngineVersion string `json:"scancl_version"`
	VDFVersion      string `json:"vdf_version"`
	ProgramVersion  string `json:"program_version"`
}

// GetVersion get Anti-Virus scanner version.
func GetVersion() (Version, error) {

	out, err := utils.ExecCmd(cmd, "--version")

	// McAfee VirusScan Command Line for Linux64 Version: 6.0.4.564
	// Copyright (C) 2013 McAfee, Inc.

	// AV Engine version: 5600.1067 for Linux64.
	// Dat set version: 9118 created Dec 26 2018
	// Scanning for 668680 viruses, trojans and variants.

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

	v := Version{}
	re := regexp.MustCompile(regVersion)
	l := re.FindStringSubmatch(out)
	if len(l) > 2 {
		v.ProgramVersion, v.AVEngineVersion, v.VDFVersion = l[1], l[2], l[3]
	}

	return v, nil
}

// ScanFile scans a given file.
func (Scanner) ScanFile(filepath string, opts multiav.Options) (multiav.Result, error) {

	var err error
	res := multiav.Result{}

	if opts.ScanTimeout == 0 {
		opts.ScanTimeout = multiav.DefaultScanTimeout
	}

	// Create a new context and add a timeout to it.
	ctx, cancel := context.WithTimeout(
		context.Background(), opts.ScanTimeout)
	defer cancel()

	// Execute the scanner with the given file path
	// --ANALYZE                  : Turn on heuristic analysis for programs and macros
	// --ASCII                    : Display filenames as ASCII text.
	// --MANALYZE                 : Turn on macro heuristics.
	// --MACRO-HEURISTICS         : Turn on macro heuristics.
	// --UNZIP                    : Scan inside archive files, such as those saved in ZIP,
	//                              LHA, PKarc, ARJ, TAR, CHM, and RAR.
	// --PROGRAM                  : Scan for potentially unwanted applications

	// /opt/mcafee/uvscan --ANALYZE --ASCII --MANALYZE --MACRO-HEURISTICS --UNZIP sample
	res.Out, err = utils.ExecCmdWithContext(ctx, cmd, "--ANALYZE", "--ASCII",
		"--MANALYZE", "--MACRO-HEURISTICS", "--UNZIP", filepath)

	// Exit codes:
	//  0 The scanner found no viruses or other potentially unwanted software,
	//    and returned no errors.
	//  2 Integrity check on DAT file failed.
	//  6 A general problem occurred.
	//  8 The scanner was unable to find a DAT file.
	//  10 A virus was found in memory.
	//  12 The scanner tried to clean a file, the attempt failed, and the file is still infected.
	//  13 The scanner found one or more viruses or hostile objects such as a
	//     Trojan-horse program, joke program, or test file.
	//  15 The scanner’s self-check failed; the scanner may be infected or damaged.
	//  19 The scanner succeeded in cleaning all infected files.
	//  20 Scanning was prevented because of the /FREQUENCY option.
	//  21 Computer requires a reboot to clean the infection.

	if err != nil && err.Error() != "exit status 13" {
		return res, err
	}

	// McAfee VirusScan Command Line for Linux64 Version: 6.0.4.564
	// Copyright (C) 2013 McAfee, Inc.
	// (408) 988-3832 EVALUATION COPY - December 27 2018

	// AV Engine version: 5600.1067 for Linux64.
	// Dat set version: 9118 created Dec 26 2018
	// Scanning for 668680 viruses, trojans and variants.

	// /samples/0000c0018968d974c61f143cfb8f0c60f79f261485fde74f24581e1d8e300051 \
	// ... Found potentially unwanted program Adware-HotBar.d.
	// /samples/0000280440c145d1b0cdaa2ef6dde37ef82435eeb73719353e46169fd9f16eda \
	// ... Found the W32/Virut.j.gen virus !!!
	// /samples/0000b374791e3b7d2baa3e05695f6633869b4bdf25cc3dedfe76d3a72a53517f \
	// ... Found the PWS-Zbot.gen.cr trojan !!!
	// /samples/0000e69606177daf097465df30b759c6ea10818f6948bd49b8fc4abddbe4962d/00014a4c.js \
	//... Found trojan or variant JS/HideLink.A !!!

	// Time: 00:00.00

	// Grab the detection result
	re := regexp.MustCompile(regDetection)
	l := re.FindStringSubmatch(res.Out)
	if len(l) > 1 {
		output := l[2]
		output = strings.TrimSuffix(output, " virus")
		output = strings.TrimSuffix(output, " trojan")
		res.Output = output
		res.Infected = true
	}
	return res, nil
}

repository: saferwall/saferwall

repo_name: saferwall/saferwall

branch_name: refs/heads/main

gha_language: Go

extension: go


text:
# Copyright (C) 2014 Matthias Lay <matthias.lay@securepoint.de>
# Released under the MIT license (see COPYING.MIT for the terms)

DESCRIPTION = "luaposix is a POSIX binding, including curses, for Lua 5.1 and 5.2; like most libraries it simply binds to C APIs on the underlying system, so it won't work on non-POSIX systems. However, it does try to detect the level of POSIX conformance of the underlying system and bind only available APIs."
HOMEPAGE = "https://github.com/luaposix/luaposix"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://COPYING;md5=0de24acdcec9cb21ff095356966cbef2"

SECTION = "lualibs"
DEPENDS = "lua5.1 lua5.1-native libgcrypt"
PR = "r0"

RDEPENDS_${PN} += "luabitop"
SRC_URI = "git://github.com/luaposix/luaposix;protocol=https;branch=master"
SRCREV = "${PV}"
S = "${WORKDIR}/git"

inherit autotools-brokensep pkgconfig

EXTRA_OEMAKE += " DESTDIR=${D} datadir=${datadir}/lua/5.1 libdir=${libdir}/lua/5.1"
PARALLEL_MAKE = ""

do_configure_prepend(){
    #the bootstraps clones the gnulib from gnu.org. the url
    # is not configurable, so if download fails, the next line can be used to
    # get the sources from somewhere else

    #git clone git://github.com/gagern/gnulib ./gnulib

    ./bootstrap --gnulib-srcdir=./gnulib
}

FILES_${PN}-dbg += "${libdir}/lua/5.1/.debug"
FILES_${PN} += "${libdir}/lua/5.1/ ${datadir}/lua/5.1/"

repository: Securepoint/yocto-meta-securepoint

repo_name: Securepoint/yocto-meta-securepoint

extension: bb


text:
package gdengine

import (
	geinterfaces "github.com/eshu0/gdengine/interfaces"
)

//This structs has the mapping of the column indexs
type GDColumMapping struct {
	ColumnIndexes []geinterfaces.IGDColumnIndex `json:"columnindexes,omitempty"`
}

// This struct is the column index
// it can be based around the name or an integer index
// the name will be read by the header row
type GDColumnIndex struct {
	geinterfaces.IGDColumnIndex

	Index int `json:"index"`

	Name string `json:"name"`
	// do we need to associate other columns with this column?
	// for example: column 1 is the first name and column 2 is the second name they should be associated
	RelatedIndexes []geinterfaces.IGDColumnIndex `json:"relatedindexes,omitempty"`
}


text:
package expr

import (
	"errors"
	"fmt"

	"github.com/shanzi/gexpr/values"
)

type Expr interface {
	Eval(context ExprContext) (values.Value, error)

	String() string
}

type ExprNode interface {
	Value(context ExprContext) values.Value
	String() string
}

type _expr struct {
	root    ExprNode
	exprStr string
}

func New(root ExprNode, exprStr string) Expr {
	return &_expr{root, exprStr}
}

func (self *_expr) Eval(context ExprContext) (v values.Value, e error) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println(r)
			v = nil
			if msg, ok := r.(string); ok {
				e = errors.New(msg)
			} else {
				e = errors.New("Can not evaluate expression")
			}
		}
	}()
	return self.root.Value(context), nil
}

func (self *_expr) String() string {
	return self.root.String()
}

repository: shanzi/gexpr

repo_name: shanzi/gexpr


text:
// ***********************************************************************
//                      DO NOT EDIT THIS FILE !!!
// ***********************************************************************
//   This file is automatically generated from the grib_api templates. All
//   changes will be overridden. If you want to do permanent changes then
//   you should write them into the 'TransverseMercatorImpl.*' files.
// ***********************************************************************

#include "TransverseMercator.h"
#include "../../common/GeneralDefinitions.h"
#include "../../common/GeneralFunctions.h"
#include <boost/functional/hash.hpp>
#include <iostream>
#include <macgyver/Exception.h>

namespace SmartMet {
namespace GRIB2 {

/*! \brief The constructor of the class. */

TransverseMercator::TransverseMercator() {
  try {
    mScaleFactorAtReferencePoint = 0;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The destructor of the class. */

TransverseMercator::~TransverseMercator() {
}

/*! \brief The method reads and initializes all data related to the current object.

        \param memoryReader  This object controls the access to the memory mapped file.
*/

void TransverseMercator::read(MemoryReader &memoryReader) {
  try {
    mEarthShape.read(memoryReader);
    mNi = memoryReader.read_UInt32_opt();
    mNj = memoryReader.read_UInt32_opt();
    mLatitudeOfReferencePoint = memoryReader.read_Int32_opt();
    mLongitudeOfReferencePoint = memoryReader.read_Int32_opt();
    mResolution.read(memoryReader);
    mScaleFactorAtReferencePoint = memoryReader.read_float();
    mXR = memoryReader.read_Int32_opt();
    mYR = memoryReader.read_Int32_opt();
    mScanningMode.read(memoryReader);
    mDi = memoryReader.read_UInt32_opt();
    mDj = memoryReader.read_UInt32_opt();
    mX1 = memoryReader.read_Int32_opt();
    mY1 = memoryReader.read_Int32_opt();
    mX2 = memoryReader.read_Int32_opt();
    mY2 = memoryReader.read_Int32_opt();
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method writes all data related to the current object.

        \param dataWriter  This object is used for writing the object data.
*/

void TransverseMercator::write(DataWriter &dataWriter) {
  try {
    mEarthShape.write(dataWriter);
    dataWriter << mNi;
    dataWriter << mNj;
    dataWriter << mLatitudeOfReferencePoint;
    dataWriter << mLongitudeOfReferencePoint;
    mResolution.write(dataWriter);
    dataWriter << mScaleFactorAtReferencePoint;
    dataWriter << mXR;
    dataWriter << mYR;
    mScanningMode.write(dataWriter);
    dataWriter << mDi;
    dataWriter << mDj;
    dataWriter << mX1;
    dataWriter << mY1;
    dataWriter << mX2;
    dataWriter << mY2;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method is used for collecting the current class attributeList.

    \param prefix         The prefix of the each attributeList parameter.
    \param attributeList  The attributeList storage.
*/

void TransverseMercator::getAttributeList(const std::string &prefix, T::AttributeList &attributeList) const {
  try {
    char name[300];
    sprintf(name, "%sTransverseMercator.", prefix.c_str());
    mEarthShape.getAttributeList(name, attributeList);
    sprintf(name, "%sTransverseMercator.Ni", prefix.c_str());
    attributeList.addAttribute(name, toString(mNi));
    sprintf(name, "%sTransverseMercator.Nj", prefix.c_str());
    attributeList.addAttribute(name, toString(mNj));
    sprintf(name, "%sTransverseMercator.LatitudeOfReferencePoint", prefix.c_str());
    attributeList.addAttribute(name, toString(mLatitudeOfReferencePoint));
    sprintf(name, "%sTransverseMercator.LongitudeOfReferencePoint", prefix.c_str());
    attributeList.addAttribute(name, toString(mLongitudeOfReferencePoint));
    sprintf(name, "%sTransverseMercator.", prefix.c_str());
    mResolution.getAttributeList(name, attributeList);
    sprintf(name, "%sTransverseMercator.ScaleFactorAtReferencePoint", prefix.c_str());
    attributeList.addAttribute(name, toString(mScaleFactorAtReferencePoint));
    sprintf(name, "%sTransverseMercator.XR", prefix.c_str());
    attributeList.addAttribute(name, toString(mXR));
    sprintf(name, "%sTransverseMercator.YR", prefix.c_str());
    attributeList.addAttribute(name, toString(mYR));
    sprintf(name, "%sTransverseMercator.", prefix.c_str());
    mScanningMode.getAttributeList(name, attributeList);
    sprintf(name, "%sTransverseMercator.Di", prefix.c_str());
    attributeList.addAttribute(name, toString(mDi));
    sprintf(name, "%sTransverseMercator.Dj", prefix.c_str());
    attributeList.addAttribute(name, toString(mDj));
    sprintf(name, "%sTransverseMercator.X1", prefix.c_str());
    attributeList.addAttribute(name, toString(mX1));
    sprintf(name, "%sTransverseMercator.Y1", prefix.c_str());
    attributeList.addAttribute(name, toString(mY1));
    sprintf(name, "%sTransverseMercator.X2", prefix.c_str());
    attributeList.addAttribute(name, toString(mX2));
    sprintf(name, "%sTransverseMercator.Y2", prefix.c_str());
    attributeList.addAttribute(name, toString(mY2));
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method is used for getting attribute values by their names.

    \param attributeName  The name of the attribute.
    \param attributeValue The value of the attribute (string).
*/

bool TransverseMercator::getAttributeValue(const char *attributeName, std::string &attributeValue) const {
  try {
    if (attributeName == nullptr)
      return false;
    if (mEarthShape.getAttributeValue(attributeName, attributeValue))
      return true;
    if (strcasecmp(attributeName, "Ni") == 0) {
      attributeValue = toString(mNi);
      return true;
    }
    if (strcasecmp(attributeName, "Nj") == 0) {
      attributeValue = toString(mNj);
      return true;
    }
    if (strcasecmp(attributeName, "LatitudeOfReferencePoint") == 0) {
      attributeValue = toString(mLatitudeOfReferencePoint);
      return true;
    }
    if (strcasecmp(attributeName, "LongitudeOfReferencePoint") == 0) {
      attributeValue = toString(mLongitudeOfReferencePoint);
      return true;
    }
    if (mResolution.getAttributeValue(attributeName, attributeValue))
      return true;
    if (strcasecmp(attributeName, "ScaleFactorAtReferencePoint") == 0) {
      attributeValue = toString(mScaleFactorAtReferencePoint);
      return true;
    }
    if (strcasecmp(attributeName, "XR") == 0) {
      attributeValue = toString(mXR);
      return true;
    }
    if (strcasecmp(attributeName, "YR") == 0) {
      attributeValue = toString(mYR);
      return true;
    }
    if (mScanningMode.getAttributeValue(attributeName, attributeValue))
      return true;
    if (strcasecmp(attributeName, "Di") == 0) {
      attributeValue = toString(mDi);
      return true;
    }
    if (strcasecmp(attributeName, "Dj") == 0) {
      attributeValue = toString(mDj);
      return true;
    }
    if (strcasecmp(attributeName, "X1") == 0) {
      attributeValue = toString(mX1);
      return true;
    }
    if (strcasecmp(attributeName, "Y1") == 0) {
      attributeValue = toString(mY1);
      return true;
    }
    if (strcasecmp(attributeName, "X2") == 0) {
      attributeValue = toString(mX2);
      return true;
    }
    if (strcasecmp(attributeName, "Y2") == 0) {
      attributeValue = toString(mY2);
      return true;
    }
    return false;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method is used for checking if the attribute value matches to the given value.

    \param attributeName  The name of the attribute.
    \param attributeValue The value of the attribute (string).
*/

bool TransverseMercator::hasAttributeValue(const char *attributeName, const char *attributeValue) const {
  try {
    if (attributeName == nullptr || attributeValue == nullptr)
      return false;
    if (mEarthShape.hasAttributeValue(attributeName, attributeValue))
      return true;
    if (strcasecmp(attributeName, "Ni") == 0 && strcasecmp(attributeValue, toString(mNi).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "Nj") == 0 && strcasecmp(attributeValue, toString(mNj).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "LatitudeOfReferencePoint") == 0 && strcasecmp(attributeValue, toString(mLatitudeOfReferencePoint).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "LongitudeOfReferencePoint") == 0 && strcasecmp(attributeValue, toString(mLongitudeOfReferencePoint).c_str()) == 0)
      return true;
    if (mResolution.hasAttributeValue(attributeName, attributeValue))
      return true;
    if (strcasecmp(attributeName, "ScaleFactorAtReferencePoint") == 0 && strcasecmp(attributeValue, toString(mScaleFactorAtReferencePoint).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "XR") == 0 && strcasecmp(attributeValue, toString(mXR).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "YR") == 0 && strcasecmp(attributeValue, toString(mYR).c_str()) == 0)
      return true;
    if (mScanningMode.hasAttributeValue(attributeName, attributeValue))
      return true;
    if (strcasecmp(attributeName, "Di") == 0 && strcasecmp(attributeValue, toString(mDi).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "Dj") == 0 && strcasecmp(attributeValue, toString(mDj).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "X1") == 0 && strcasecmp(attributeValue, toString(mX1).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "Y1") == 0 && strcasecmp(attributeValue, toString(mY1).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "X2") == 0 && strcasecmp(attributeValue, toString(mX2).c_str()) == 0)
      return true;
    if (strcasecmp(attributeName, "Y2") == 0 && strcasecmp(attributeValue, toString(mY2).c_str()) == 0)
      return true;
    return false;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method prints the content of the current object into the given stream.

    \param ostream      The output stream.
    \param level        The print level (used when printing multi-level structures).
    \param optionFlags  The printing options expressed in flag-bits.
*/

void TransverseMercator::print(std::ostream &stream, uint level, uint optionFlags) const {
  try {
    stream << space(level) << "TransverseMercator\n";
    mEarthShape.print(stream, level + 1, optionFlags);
    stream << space(level) << "- Ni = " << toString(mNi) << "\n";
    stream << space(level) << "- Nj = " << toString(mNj) << "\n";
    stream << space(level) << "- LatitudeOfReferencePoint = " << toString(mLatitudeOfReferencePoint) << "\n";
    stream << space(level) << "- LongitudeOfReferencePoint = " << toString(mLongitudeOfReferencePoint) << "\n";
    mResolution.print(stream, level + 1, optionFlags);
    stream << space(level) << "- ScaleFactorAtReferencePoint = " << toString(mScaleFactorAtReferencePoint) << "\n";
    stream << space(level) << "- XR = " << toString(mXR) << "\n";
    stream << space(level) << "- YR = " << toString(mYR) << "\n";
    mScanningMode.print(stream, level + 1, optionFlags);
    stream << space(level) << "- Di = " << toString(mDi) << "\n";
    stream << space(level) << "- Dj = " << toString(mDj) << "\n";
    stream << space(level) << "- X1 = " << toString(mX1) << "\n";
    stream << space(level) << "- Y1 = " << toString(mY1) << "\n";
    stream << space(level) << "- X2 = " << toString(mX2) << "\n";
    stream << space(level) << "- Y2 = " << toString(mY2) << "\n";
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method counts the hash value of the current object. */

T::Hash TransverseMercator::countHash() const {
  try {
    std::size_t seed = 0;
    if (mNi)
      boost::hash_combine(seed, *mNi);
    if (mNj)
      boost::hash_combine(seed, *mNj);
    if (mLatitudeOfReferencePoint)
      boost::hash_combine(seed, *mLatitudeOfReferencePoint);
    if (mLongitudeOfReferencePoint)
      boost::hash_combine(seed, *mLongitudeOfReferencePoint);
    boost::hash_combine(seed, mScaleFactorAtReferencePoint);
    if (mXR)
      boost::hash_combine(seed, *mXR);
    if (mYR)
      boost::hash_combine(seed, *mYR);
    if (mDi)
      boost::hash_combine(seed, *mDi);
    if (mDj)
      boost::hash_combine(seed, *mDj);
    if (mX1)
      boost::hash_combine(seed, *mX1);
    if (mY1)
      boost::hash_combine(seed, *mY1);
    if (mX2)
      boost::hash_combine(seed, *mX2);
    if (mY2)
      boost::hash_combine(seed, *mY2);
    return seed;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method return the template number of the current class. */

uint TransverseMercator::getTemplateNumber() const {
  return 12;
}

GridDefinition *TransverseMercator::createGridDefinition() const {
  try {
    return static_cast<GridDefinition *>(new TransverseMercator(*this));
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the pointer to the {@link mEarthShape} attribute. */

EarthShapeSettings *TransverseMercator::getEarthShape() const {
  try {
    return static_cast<EarthShapeSettings *>(&mEarthShape);
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mNi} attribute. */

const T::UInt32_opt &TransverseMercator::getNi() const {
  try {
    return mNi;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mNj} attribute. */

const T::UInt32_opt &TransverseMercator::getNj() const {
  try {
    return mNj;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mLatitudeOfReferencePoint} attribute. */

const T::Int32_opt &TransverseMercator::getLatitudeOfReferencePoint() const {
  try {
    return mLatitudeOfReferencePoint;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mLongitudeOfReferencePoint} attribute. */

const T::Int32_opt &TransverseMercator::getLongitudeOfReferencePoint() const {
  try {
    return mLongitudeOfReferencePoint;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the pointer to the {@link mResolution} attribute. */

ResolutionSettings *TransverseMercator::getResolution() const {
  try {
    return static_cast<ResolutionSettings *>(&mResolution);
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mScaleFactorAtReferencePoint} attribute. */

float TransverseMercator::getScaleFactorAtReferencePoint() const {
  try {
    return mScaleFactorAtReferencePoint;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mXR} attribute. */

const T::Int32_opt &TransverseMercator::getXR() const {
  try {
    return mXR;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mYR} attribute. */

const T::Int32_opt &TransverseMercator::getYR() const {
  try {
    return mYR;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the pointer to the {@link mScanningMode} attribute. */

ScanningModeSettings *TransverseMercator::getScanningMode() const {
  try {
    return static_cast<ScanningModeSettings *>(&mScanningMode);
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mDi} attribute. */

const T::UInt32_opt &TransverseMercator::getDi() const {
  try {
    return mDi;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mDj} attribute. */

const T::UInt32_opt &TransverseMercator::getDj() const {
  try {
    return mDj;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mX1} attribute. */

const T::Int32_opt &TransverseMercator::getX1() const {
  try {
    return mX1;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mY1} attribute. */

const T::Int32_opt &TransverseMercator::getY1() const {
  try {
    return mY1;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mX2} attribute. */

const T::Int32_opt &TransverseMercator::getX2() const {
  try {
    return mX2;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

/*! \brief The method returns the value of the {@link mY2} attribute. */

const T::Int32_opt &TransverseMercator::getY2() const {
  try {
    return mY2;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setEarthShape(EarthShapeSettings &earthShape) {
  try {
    mEarthShape = earthShape;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setNi(T::UInt32_opt ni) {
  try {
    mNi = ni;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setNj(T::UInt32_opt nj) {
  try {
    mNj = nj;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setLatitudeOfReferencePoint(T::Int32_opt latitudeOfReferencePoint) {
  try {
    mLatitudeOfReferencePoint = latitudeOfReferencePoint;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setLongitudeOfReferencePoint(T::Int32_opt longitudeOfReferencePoint) {
  try {
    mLongitudeOfReferencePoint = longitudeOfReferencePoint;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setResolution(ResolutionSettings &resolution) {
  try {
    mResolution = resolution;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setScaleFactorAtReferencePoint(float scaleFactorAtReferencePoint) {
  try {
    mScaleFactorAtReferencePoint = scaleFactorAtReferencePoint;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setXR(T::Int32_opt xR) {
  try {
    mXR = xR;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setYR(T::Int32_opt yR) {
  try {
    mYR = yR;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setScanningMode(ScanningModeSettings &scanningMode) {
  try {
    mScanningMode = scanningMode;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setDi(T::UInt32_opt di) {
  try {
    mDi = di;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setDj(T::UInt32_opt dj) {
  try {
    mDj = dj;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setX1(T::Int32_opt x1) {
  try {
    mX1 = x1;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setY1(T::Int32_opt y1) {
  try {
    mY1 = y1;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setX2(T::Int32_opt x2) {
  try {
    mX2 = x2;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

void TransverseMercator::setY2(T::Int32_opt y2) {
  try {
    mY2 = y2;
  } catch (...) {
    throw Fmi::Exception(BCP, "Operation failed", nullptr);
  }
}

} // namespace GRIB2
} // namespace SmartMet

repository: fmidev/smartmet-library-grid-files

repo_name: fmidev/smartmet-library-grid-files

gha_license_id: MIT

extension: cpp


text:
DESCRIPTION = "Provides test pruss firmware for uio based tests"
LICENSE = "BSD-3-Clause"
PV = "1.0.2.0"
require recipes-ti/includes/ti-paths.inc

S = "${WORKDIR}/git"

DEPENDS = "ti-cgt-pru-native"

BRANCH = "master"
LIC_FILES_CHKSUM = "file://Makefile;startline=1;endline=31;md5=0ee4f2c42eb6b04e37859bb55a18b144"

UIO_TEST_PRUSS_GIT_URI = "git://git.ti.com/processor-sdk/uio-test-pruss.git"
UIO_TEST_PRUSS_GIT_PROTOCOL = "git"
SRC_URI = "${UIO_TEST_PRUSS_GIT_URI};protocol=${UIO_TEST_PRUSS_GIT_PROTOCOL};branch=${BRANCH}"

# Corresponds to version 01.00.02.00
UIO_TEST_PRUSS_SRCREV = "e52a7b099d7203ca52519650df51419e9fef7e0c"

SRCREV = "${UIO_TEST_PRUSS_SRCREV}"

PR = "r0"

COMPATIBLE_MACHINE = "omap-a15|ti33x|ti43x|k2g"

PACKAGE_ARCH = "${MACHINE_ARCH}"

DEVICE_NAME = ""
DEVICE_NAME_append_am57xx-evm = "am57xx"
DEVICE_NAME_append_ti33x = "am33xx"
DEVICE_NAME_append_ti43x = "am43xx"
DEVICE_NAME_append_k2g = "k2g"

EXTRA_OEMAKE = "CGT_PRU=${TI_CGT_PRU_INSTALL_DIR} DEVICE=${DEVICE_NAME}"

do_install() {
    install -d ${D}${bindir}/
    cp -r *.bin ${D}${bindir}/
}

repository: bjornwilliam/meta-ti

repo_name: bjornwilliam/meta-ti


text:
package chronos_test

import (
	"errors"
	"testing"
	"time"

	"github.com/paketo-buildpacks/packit/chronos"
	"github.com/sclevine/spec"

	. "github.com/onsi/gomega"
)

func testClock(t *testing.T, context spec.G, it spec.S) {
	var Expect = NewWithT(t).Expect

	context("Now", func() {
		it("returns the value from the given Now function", func() {
			now := time.Now()

			clock := chronos.NewClock(func() time.Time {
				return now
			})

			Expect(clock.Now()).To(Equal(now))
		})
	})

	context("Measure", func() {
		var clock chronos.Clock

		it.Before(func() {
			now := time.Now()
			times := []time.Time{now, now.Add(20 * time.Second)}

			clock = chronos.NewClock(func() time.Time {
				t := time.Now()

				if len(times) > 0 {
					t = times[0]
					times = times[1:]
				}

				return t
			})
		})

		it("returns the duration taken to perform the operation", func() {
			duration, err := clock.Measure(func() error {
				return nil
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(duration).To(Equal(20 * time.Second))
		})

		context("when the operation errors", func() {
			it("returns that error", func() {
				_, err := clock.Measure(func() error {
					return errors.New("operation failed")
				})
				Expect(err).To(MatchError("operation failed"))
			})
		})
	})
}


text:
// Code generated by lark_sdk_gen. DO NOT EDIT.

package lark

import (
	"context"
)

// GetVCRoomConfig 查询一个范围内的会议室配置。
//
// 根据查询范围传入对应的参数
//
// doc: https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/vc-v1/room_config/query
func (r *VCService) GetVCRoomConfig(ctx context.Context, request *GetVCRoomConfigReq, options ...MethodOptionFunc) (*GetVCRoomConfigResp, *Response, error) {
	if r.cli.mock.mockVCGetVCRoomConfig != nil {
		r.cli.log(ctx, LogLevelDebug, "[lark] VC#GetVCRoomConfig mock enable")
		return r.cli.mock.mockVCGetVCRoomConfig(ctx, request, options...)
	}

	req := &RawRequestReq{
		Scope:                 "VC",
		API:                   "GetVCRoomConfig",
		Method:                "GET",
		URL:                   "https://open.feishu.cn/open-apis/vc/v1/room_configs/query",
		Body:                  request,
		MethodOption:          newMethodOption(options),
		NeedTenantAccessToken: true,
	}
	resp := new(getVCRoomConfigResp)

	response, err := r.cli.RawRequest(ctx, req, resp)
	return resp.Data, response, err
}

func (r *Mock) MockVCGetVCRoomConfig(f func(ctx context.Context, request *GetVCRoomConfigReq, options ...MethodOptionFunc) (*GetVCRoomConfigResp, *Response, error)) {
	r.mockVCGetVCRoomConfig = f
}

func (r *Mock) UnMockVCGetVCRoomConfig() {
	r.mockVCGetVCRoomConfig = nil
}

type GetVCRoomConfigReq struct {
	Scope      int64   `query:"scope" json:"-"`       // 查询节点范围, 示例值：5, 可选值有: `1`：租户, `2`：国家/地区, `3`：城市, `4`：建筑, `5`：楼层, `6`：会议室
	CountryID  *string `query:"country_id" json:"-"`  // 国家/地区ID scope为2，3时需要此参数, 示例值："086"
	DistrictID *string `query:"district_id" json:"-"` // 城市ID scope为3时需要此参数, 示例值："001"
	BuildingID *string `query:"building_id" json:"-"` // 建筑ID scope为4，5时需要此参数, 示例值："22"
	FloorName  *string `query:"floor_name" json:"-"`  // 楼层 scope为5时需要此参数, 示例值："4"
	RoomID     *string `query:"room_id" json:"-"`     // 会议室ID scope为6时需要此参数, 示例值："6383786266263"
}

type getVCRoomConfigResp struct {
	Code int64                `json:"code,omitempty"` // 错误码，非 0 表示失败
	Msg  string               `json:"msg,omitempty"`  // 错误描述
	Data *GetVCRoomConfigResp `json:"data,omitempty"`
}

type GetVCRoomConfigResp struct {
	RoomBackground    string                             `json:"room_background,omitempty"`    // 飞书会议室背景图
	DisplayBackground string                             `json:"display_background,omitempty"` // 飞书签到板背景图
	DigitalSignage    *GetVCRoomConfigRespDigitalSignage `json:"digital_signage,omitempty"`    // 飞书会议室数字标牌
}

type GetVCRoomConfigRespDigitalSignage struct {
	Enable       bool                                         `json:"enable,omitempty"`        // 是否开启数字标牌功能
	Mute         bool                                         `json:"mute,omitempty"`          // 是否静音播放
	StartDisplay int64                                        `json:"start_display,omitempty"` // 日程会议开始前n分钟结束播放
	StopDisplay  int64                                        `json:"stop_display,omitempty"`  // 会议结束后n分钟开始播放
	Materials    []*GetVCRoomConfigRespDigitalSignageMaterial `json:"materials,omitempty"`     // 素材列表
}

type GetVCRoomConfigRespDigitalSignageMaterial struct {
	ID           string `json:"id,omitempty"`            // 素材ID
	Name         string `json:"name,omitempty"`          // 素材名称
	MaterialType int64  `json:"material_type,omitempty"` // 素材类型, 可选值有: `1`：图片, `2`：视频, `3`：GIF
	URL          string `json:"url,omitempty"`           // 素材url
	Duration     int64  `json:"duration,omitempty"`      // 播放时长（单位sec）
	Cover        string `json:"cover,omitempty"`         // 素材封面url
	Md5          string `json:"md5,omitempty"`           // 素材文件md5
}


text:
package os_test

import (
	"fmt"

	"github.com/kubevirt/vm-import-operator/pkg/providers/ovirt/os"

	. "github.com/onsi/ginkgo"
	"github.com/onsi/ginkgo/extensions/table"
	ovirtsdk "github.com/ovirt/go-ovirt"

	. "github.com/onsi/gomega"
)

var (
	getOSMaps func() (map[string]string, map[string]string, error)
	finder    = os.OVirtOSFinder{OsMapProvider: &mockOsMapProvider{}}
)

var _ = Describe("OS finder ", func() {
	BeforeEach(func() {
		getOSMaps = func() (map[string]string, map[string]string, error) {
			guest2common := map[string]string{"Red Hat Enterprise Linux Server": "rhel"}
			os2common := map[string]string{"rhel_6": "rhel6.9"}
			return guest2common, os2common, nil
		}
	})

	It("should find OS from Guest OS information", func() {
		vm := ovirtsdk.NewVmBuilder().
			GuestOperatingSystemBuilder(
				ovirtsdk.NewGuestOperatingSystemBuilder().
					Distribution("Red Hat Enterprise Linux Server").
					VersionBuilder(ovirtsdk.NewVersionBuilder().FullVersion("7.7"))).
			MustBuild()

		os, err := finder.FindOperatingSystem(vm)

		Expect(err).ToNot(HaveOccurred())
		Expect(os).To(BeEquivalentTo("rhel7.7"))
	})

	It("should find OS from OS type and mapping present", func() {
		vm := ovirtsdk.NewVmBuilder().
			OsBuilder(
				ovirtsdk.NewOperatingSystemBuilder().
					Type("rhel_6")).
			MustBuild()

		os, err := finder.FindOperatingSystem(vm)

		Expect(err).ToNot(HaveOccurred())
		Expect(os).To(BeEquivalentTo("rhel6.9"))
	})

	table.DescribeTable("should find default OS from OS type and no mapping for the type", func(osType string, expectedOs string) {
		vm := ovirtsdk.NewVmBuilder().
			OsBuilder(
				ovirtsdk.NewOperatingSystemBuilder().
					Type(osType)).
			MustBuild()

		os, err := finder.FindOperatingSystem(vm)

		Expect(err).ToNot(HaveOccurred())
		Expect(os).To(BeEquivalentTo(expectedOs))
	},
		table.Entry("for generic Linux", "linux X", "rhel8.2"),
		table.Entry("for RHEL", "rhel X", "rhel8.2"),

		table.Entry("for generic Windows", "windows", "win10"),
		table.Entry("for windows_7", "windows_7", "win10"),
	)

	It("should return error for os map provider error", func() {
		getOSMaps = func() (map[string]string, map[string]string, error) {
			zero := map[string]string{}
			return zero, zero, fmt.Errorf("Boom!")
		}

		vm := ovirtsdk.NewVmBuilder().
			OsBuilder(
				ovirtsdk.NewOperatingSystemBuilder().
					Type("linux")).
			MustBuild()

		_, err := finder.FindOperatingSystem(vm)

		Expect(err).To(HaveOccurred())
	})

	It("should return error for no OS found", func() {
		vm := ovirtsdk.NewVmBuilder().MustBuild()

		_, err := finder.FindOperatingSystem(vm)

		Expect(err).To(HaveOccurred())
	})
})

type mockOsMapProvider struct{}

func (m *mockOsMapProvider) GetOSMaps() (map[string]string, map[string]string, error) {
	return getOSMaps()
}

repository: kubevirt/vm-import-operator

repo_name: kubevirt/vm-import-operator


text:
package algtest

import (
	"math/big"
	"testing"

	"github.com/mmcloughlin/addchain"
	"github.com/mmcloughlin/addchain/alg"
	"github.com/mmcloughlin/addchain/internal/bigints"
)

// References:
//
//	[curvechains]       Brian Smith. The Most Efficient Known Addition Chains for Field Element and
//	                    Scalar Inversion for the Most Popular and Most Unpopular Elliptic Curves. 2017.
//	                    https://briansmith.org/ecc-inversion-addition-chains-01 (accessed June 30, 2019)
//	[hehcc:exp]         Christophe Doche. Exponentiation. Handbook of Elliptic and Hyperelliptic Curve
//	                    Cryptography, chapter 9. 2006.
//	                    http://koclab.cs.ucsb.edu/teaching/ecc/eccPapers/Doche-ch09.pdf
//	[pairingsfinalexp]  Michael Scott, Naomi Benger, Manuel Charlemagne, Luis J. Dominguez Perez and
//	                    Ezekiel J. Kachisa. On the final exponentiation for calculating pairings on
//	                    ordinary elliptic curves. Cryptology ePrint Archive, Report 2008/490. 2008.
//	                    https://eprint.iacr.org/2008/490

// SequenceAlgorithmSuite builds a generic suite of tests for an addition
// sequence algorithm.
type SequenceAlgorithmSuite struct {
	// Algorithm under test.
	Algorithm alg.SequenceAlgorithm

	// AcceptsLargeInputs indicates whether the algorithm can tolerate large
	// inputs. As a rule of thumb, set this to true if the algorithm is
	// logarithmic in the largest input.
	AcceptsLargeInputs bool
}

// Tests builds the test suite function. Suitable to run as a subtest with
// testing.T.Run.
func (s SequenceAlgorithmSuite) Tests() func(t *testing.T) {
	return func(t *testing.T) {
		t.Run("known_sequences", checkKnownSequences(s.Algorithm))
		if s.AcceptsLargeInputs {
			t.Run("as_chain_algorithm", ChainAlgorithmSuite(alg.AsChainAlgorithm(s.Algorithm)))
		}
	}
}

func checkKnownSequences(a alg.SequenceAlgorithm) func(t *testing.T) {
	cases := []struct {
		Targets  []*big.Int
		Solution addchain.Chain
	}{
		// Example 9.39 in [hehcc:exp].
		{
			Targets:  bigints.Int64s(47, 117, 343, 499, 933, 5689),
			Solution: addchain.Int64s(1, 2, 4, 8, 10, 11, 18, 36, 47, 55, 91, 109, 117, 226, 343, 434, 489, 499, 933, 1422, 2844, 5688, 5689),
		},
		// [pairingsfinalexp] page 5.
		{
			Targets:  bigints.Int64s(6, 12, 18, 30, 36),
			Solution: addchain.Int64s(1, 2, 3, 6, 12, 18, 30, 36),
		},
		// [pairingsfinalexp] page 8.
		{
			Targets:  bigints.Int64s(4, 5, 7, 10, 15, 26, 28, 30, 55, 75, 80, 100, 108, 144),
			Solution: addchain.Int64s(1, 2, 4, 5, 7, 10, 15, 25, 26, 28, 30, 36, 50, 55, 75, 80, 100, 108, 144),
		},
		// [pairingsfinalexp] page 9.
		{
			Targets:  bigints.Int64s(3, 5, 7, 14, 15, 21, 25, 35, 49, 54, 62, 70, 87, 98, 112, 245, 273, 319, 343, 434, 450, 581, 609, 784, 931, 1407, 1911, 4802, 6517),
			Solution: addchain.Int64s(1, 2, 3, 4, 5, 7, 8, 14, 15, 16, 21, 25, 28, 35, 42, 49, 54, 62, 70, 87, 98, 112, 147, 245, 273, 294, 319, 343, 392, 434, 450, 581, 609, 784, 931, 1162, 1407, 1862, 1911, 3724, 4655, 4802, 6517),
		},
		// Curve25519 field inversion in [curvechains].
		{
			Targets:  bigints.Int64s(1, 2, 250),
			Solution: bigints.Int64s(1, 2, 3, 5, 10, 20, 40, 50, 100, 200, 250),
		},
		// P-256 field inversion in [curvechains].
		{
			Targets:  bigints.Int64s(32, 94),
			Solution: bigints.Int64s(1, 2, 3, 6, 12, 15, 30, 32, 64, 94),
		},
		// P-384 field inversion in [curvechains].
		{
			Targets:  bigints.Int64s(30, 32, 255),
			Solution: bigints.Int64s(1, 2, 3, 6, 12, 15, 30, 32, 60, 120, 240, 255),
		},
		// secp256k1 field inversion in [curvechains].
		{
			Targets:  bigints.Int64s(22, 223),
			Solution: bigints.Int64s(1, 2, 3, 6, 9, 11, 22, 44, 88, 176, 220, 223),
		},
	}

	for _, c := range cases {
		if err := c.Solution.Superset(c.Targets); err != nil {
			panic(err)
		}
	}

	return func(t *testing.T) {
		for _, c := range cases {
			got := AssertSequenceAlgorithmProduces(t, a, c.Targets)
			t.Logf("     got: length=%d sequence=%v", len(got), got)
			t.Logf("solution: length=%d sequence=%v", len(c.Solution), c.Solution)
			if len(got) > len(c.Solution) {
				t.Logf("sub-optimal")
			}
		}
	}
}

repository: mmcloughlin/addchain

repo_name: mmcloughlin/addchain


text:
/*
Cisco Intersight

Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document.

API version: 1.0.11-13010
Contact: intersight@cisco.com
*/

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package intersight

import (
	"encoding/json"
)

// NiatelemetrySmartLicenseAllOf Definition of the list of properties defined in 'niatelemetry.SmartLicense', excluding properties defined in parent classes.
type NiatelemetrySmartLicenseAllOf struct {
	// The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.
	ClassId string `json:"ClassId"`
	// The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property.
	ObjectType string `json:"ObjectType"`
	// Indicate the mode smart license is curerntly running.
	ActiveMode *string `json:"ActiveMode,omitempty"`
	// Authorization status of the smart license.
	AuthStatus *string `json:"AuthStatus,omitempty"`
	// License Udi of the smart license.
	LicenseUdi *string `json:"LicenseUdi,omitempty"`
	// Smart licensing account name in CSSM and is retrieved from CSSM after regsitration.
	SmartAccount         *string `json:"SmartAccount,omitempty"`
	AdditionalProperties map[string]interface{}
}

type _NiatelemetrySmartLicenseAllOf NiatelemetrySmartLicenseAllOf

// NewNiatelemetrySmartLicenseAllOf instantiates a new NiatelemetrySmartLicenseAllOf object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewNiatelemetrySmartLicenseAllOf(classId string, objectType string) *NiatelemetrySmartLicenseAllOf {
	this := NiatelemetrySmartLicenseAllOf{}
	this.ClassId = classId
	this.ObjectType = objectType
	return &this
}

// NewNiatelemetrySmartLicenseAllOfWithDefaults instantiates a new NiatelemetrySmartLicenseAllOf object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewNiatelemetrySmartLicenseAllOfWithDefaults() *NiatelemetrySmartLicenseAllOf {
	this := NiatelemetrySmartLicenseAllOf{}
	var classId string = "niatelemetry.SmartLicense"
	this.ClassId = classId
	var objectType string = "niatelemetry.SmartLicense"
	this.ObjectType = objectType
	return &this
}

// GetClassId returns the ClassId field value
func (o *NiatelemetrySmartLicenseAllOf) GetClassId() string {
	if o == nil {
		var ret string
		return ret
	}

	return o.ClassId
}

// GetClassIdOk returns a tuple with the ClassId field value
// and a boolean to check if the value has been set.
func (o *NiatelemetrySmartLicenseAllOf) GetClassIdOk() (*string, bool) {
	if o == nil {
		return nil, false
	}
	return &o.ClassId, true
}

// SetClassId sets field value
func (o *NiatelemetrySmartLicenseAllOf) SetClassId(v string) {
	o.ClassId = v
}

// GetObjectType returns the ObjectType field value
func (o *NiatelemetrySmartLicenseAllOf) GetObjectType() string {
	if o == nil {
		var ret string
		return ret
	}

	return o.ObjectType
}

// GetObjectTypeOk returns a tuple with the ObjectType field value
// and a boolean to check if the value has been set.
func (o *NiatelemetrySmartLicenseAllOf) GetObjectTypeOk() (*string, bool) {
	if o == nil {
		return nil, false
	}
	return &o.ObjectType, true
}

// SetObjectType sets field value
func (o *NiatelemetrySmartLicenseAllOf) SetObjectType(v string) {
	o.ObjectType = v
}

// GetActiveMode returns the ActiveMode field value if set, zero value otherwise.
func (o *NiatelemetrySmartLicenseAllOf) GetActiveMode() string {
	if o == nil || o.ActiveMode == nil {
		var ret string
		return ret
	}
	return *o.ActiveMode
}

// GetActiveModeOk returns a tuple with the ActiveMode field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *NiatelemetrySmartLicenseAllOf) GetActiveModeOk() (*string, bool) {
	if o == nil || o.ActiveMode == nil {
		return nil, false
	}
	return o.ActiveMode, true
}

// HasActiveMode returns a boolean if a field has been set.
func (o *NiatelemetrySmartLicenseAllOf) HasActiveMode() bool {
	if o != nil && o.ActiveMode != nil {
		return true
	}

	return false
}

// SetActiveMode gets a reference to the given string and assigns it to the ActiveMode field.
func (o *NiatelemetrySmartLicenseAllOf) SetActiveMode(v string) {
	o.ActiveMode = &v
}

// GetAuthStatus returns the AuthStatus field value if set, zero value otherwise.
func (o *NiatelemetrySmartLicenseAllOf) GetAuthStatus() string {
	if o == nil || o.AuthStatus == nil {
		var ret string
		return ret
	}
	return *o.AuthStatus
}

// GetAuthStatusOk returns a tuple with the AuthStatus field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *NiatelemetrySmartLicenseAllOf) GetAuthStatusOk() (*string, bool) {
	if o == nil || o.AuthStatus == nil {
		return nil, false
	}
	return o.AuthStatus, true
}

// HasAuthStatus returns a boolean if a field has been set.
func (o *NiatelemetrySmartLicenseAllOf) HasAuthStatus() bool {
	if o != nil && o.AuthStatus != nil {
		return true
	}

	return false
}

// SetAuthStatus gets a reference to the given string and assigns it to the AuthStatus field.
func (o *NiatelemetrySmartLicenseAllOf) SetAuthStatus(v string) {
	o.AuthStatus = &v
}

// GetLicenseUdi returns the LicenseUdi field value if set, zero value otherwise.
func (o *NiatelemetrySmartLicenseAllOf) GetLicenseUdi() string {
	if o == nil || o.LicenseUdi == nil {
		var ret string
		return ret
	}
	return *o.LicenseUdi
}

// GetLicenseUdiOk returns a tuple with the LicenseUdi field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *NiatelemetrySmartLicenseAllOf) GetLicenseUdiOk() (*string, bool) {
	if o == nil || o.LicenseUdi == nil {
		return nil, false
	}
	return o.LicenseUdi, true
}

// HasLicenseUdi returns a boolean if a field has been set.
func (o *NiatelemetrySmartLicenseAllOf) HasLicenseUdi() bool {
	if o != nil && o.LicenseUdi != nil {
		return true
	}

	return false
}

// SetLicenseUdi gets a reference to the given string and assigns it to the LicenseUdi field.
func (o *NiatelemetrySmartLicenseAllOf) SetLicenseUdi(v string) {
	o.LicenseUdi = &v
}

// GetSmartAccount returns the SmartAccount field value if set, zero value otherwise.
func (o *NiatelemetrySmartLicenseAllOf) GetSmartAccount() string {
	if o == nil || o.SmartAccount == nil {
		var ret string
		return ret
	}
	return *o.SmartAccount
}

// GetSmartAccountOk returns a tuple with the SmartAccount field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *NiatelemetrySmartLicenseAllOf) GetSmartAccountOk() (*string, bool) {
	if o == nil || o.SmartAccount == nil {
		return nil, false
	}
	return o.SmartAccount, true
}

// HasSmartAccount returns a boolean if a field has been set.
func (o *NiatelemetrySmartLicenseAllOf) HasSmartAccount() bool {
	if o != nil && o.SmartAccount != nil {
		return true
	}

	return false
}

// SetSmartAccount gets a reference to the given string and assigns it to the SmartAccount field.
func (o *NiatelemetrySmartLicenseAllOf) SetSmartAccount(v string) {
	o.SmartAccount = &v
}

func (o NiatelemetrySmartLicenseAllOf) MarshalJSON() ([]byte, error) {
	toSerialize := map[string]interface{}{}
	if true {
		toSerialize["ClassId"] = o.ClassId
	}
	if true {
		toSerialize["ObjectType"] = o.ObjectType
	}
	if o.ActiveMode != nil {
		toSerialize["ActiveMode"] = o.ActiveMode
	}
	if o.AuthStatus != nil {
		toSerialize["AuthStatus"] = o.AuthStatus
	}
	if o.LicenseUdi != nil {
		toSerialize["LicenseUdi"] = o.LicenseUdi
	}
	if o.SmartAccount != nil {
		toSerialize["SmartAccount"] = o.SmartAccount
	}

	for key, value := range o.AdditionalProperties {
		toSerialize[key] = value
	}

	return json.Marshal(toSerialize)
}

func (o *NiatelemetrySmartLicenseAllOf) UnmarshalJSON(bytes []byte) (err error) {
	varNiatelemetrySmartLicenseAllOf := _NiatelemetrySmartLicenseAllOf{}

	if err = json.Unmarshal(bytes, &varNiatelemetrySmartLicenseAllOf); err == nil {
		*o = NiatelemetrySmartLicenseAllOf(varNiatelemetrySmartLicenseAllOf)
	}

	additionalProperties := make(map[string]interface{})

	if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
		delete(additionalProperties, "ClassId")
		delete(additionalProperties, "ObjectType")
		delete(additionalProperties, "ActiveMode")
		delete(additionalProperties, "AuthStatus")
		delete(additionalProperties, "LicenseUdi")
		delete(additionalProperties, "SmartAccount")
		o.AdditionalProperties = additionalProperties
	}

	return err
}

type NullableNiatelemetrySmartLicenseAllOf struct {
	value *NiatelemetrySmartLicenseAllOf
	isSet bool
}

func (v NullableNiatelemetrySmartLicenseAllOf) Get() *NiatelemetrySmartLicenseAllOf {
	return v.value
}

func (v *NullableNiatelemetrySmartLicenseAllOf) Set(val *NiatelemetrySmartLicenseAllOf) {
	v.value = val
	v.isSet = true
}

func (v NullableNiatelemetrySmartLicenseAllOf) IsSet() bool {
	return v.isSet
}

func (v *NullableNiatelemetrySmartLicenseAllOf) Unset() {
	v.value = nil
	v.isSet = false
}

func NewNullableNiatelemetrySmartLicenseAllOf(val *NiatelemetrySmartLicenseAllOf) *NullableNiatelemetrySmartLicenseAllOf {
	return &NullableNiatelemetrySmartLicenseAllOf{value: val, isSet: true}
}

func (v NullableNiatelemetrySmartLicenseAllOf) MarshalJSON() ([]byte, error) {
	return json.Marshal(v.value)
}

func (v *NullableNiatelemetrySmartLicenseAllOf) UnmarshalJSON(src []byte) error {
	v.isSet = true
	return json.Unmarshal(src, &v.value)
}

repository: CiscoDevNet/intersight-go

repo_name: CiscoDevNet/intersight-go

gha_language: Shell


text:
package cloudformation

import (
	"encoding/json"
)

// AWSCodeBuildProject_ProjectTriggers AWS CloudFormation Resource (AWS::CodeBuild::Project.ProjectTriggers)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projecttriggers.html
type AWSCodeBuildProject_ProjectTriggers struct {

	// Webhook AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projecttriggers.html#cfn-codebuild-project-projecttriggers-webhook
	Webhook *Value `json:"Webhook,omitempty"`
}

// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *AWSCodeBuildProject_ProjectTriggers) AWSCloudFormationType() string {
	return "AWS::CodeBuild::Project.ProjectTriggers"
}

func (r *AWSCodeBuildProject_ProjectTriggers) MarshalJSON() ([]byte, error) {
	return json.Marshal(*r)
}

repository: errordeveloper/goformation

repo_name: errordeveloper/goformation


text:
// Package utils provides utility functions.
package utils

import (
	"io/ioutil"

	"gopkg.in/yaml.v1"
)

// YamlUnmarshal parses a yaml file and set the result to the out interface.
func YamlUnmarshal(path string, out interface{}) error {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	if err := yaml.Unmarshal(bytes, out); err != nil {
		return err
	}
	return nil
}

repository: yosssi/goproject

repo_name: yosssi/goproject


text:
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

//go:generate mdatagen metadata.yaml

// Package haproxyreceiver implements a receiver collecting metrics from HAProxy.
package haproxyreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/haproxyreceiver"


text:
# dosfstools-native OE build file
# Copyright (C) 2004-2006, Advanced Micro Devices, Inc.  All Rights Reserved
# Released under the MIT license (see packages/COPYING)

require dosfstools_${PV}.bb
FILESDIR = "${@os.path.dirname(bb.data.getVar('FILE',d,1))}/dosfstools-${PV}"

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

PR ="r4"

SRC_URI = "ftp://ftp.uni-erlangen.de/pub/Linux/LOCAL/dosfstools/dosfstools-${PV}.src.tar.gz \
	file://mkdosfs-bootcode.patch;patch=1 \
	file://mkdosfs-dir.patch;patch=1 \
	file://alignment_hack.patch;patch=1 \
	file://dosfstools-2.10-kernel-2.6.patch;patch=1 \
	file://msdos_fat12_undefined.patch;patch=1 \
	file://dosfstools-msdos_fs-types.patch;patch=1 \
	file://include-linux-types.patch;patch=1 \
	file://2.6.20-syscall.patch;patch=1"

inherit native

do_stage() {
	install -m 755 ${S}/mkdosfs/mkdosfs ${STAGING_BINDIR}/mkdosfs
	install -m 755 ${S}/dosfsck/dosfsck ${STAGING_BINDIR}/dosfsck
}


text:
DESCRIPTION = "Python JSON Server & Client"
HOMEPAGE = "http://cpiekarski.com/2011/05/09/super-easy-python-json-client-server/"
SECTION = "devel/python"
LICENSE = "GPLV3"
LIC_FILES_CHKSUM = "file://README;md5=ee81898440c50d224a72f46bfc23dc3e"

SRCNAME = "jsocket"
PR = "r0"

SRC_URI = "https://pypi.python.org/packages/source/j/jsocket/${SRCNAME}-${PV}.tar.gz"
S = "${WORKDIR}/${SRCNAME}-${PV}"

inherit distutils

COMPATIBLE_MACHINE = "raspberrypi"

SRC_URI[md5sum] = "5460d160fab307724c929688b3e75880"
SRC_URI[sha256sum] = "1bb7a247f73cc9d7a27cd48a471d55725032fe353080eb7f926ea77feae0260b"

repository: xtacocorex/meta-rpi

repo_name: xtacocorex/meta-rpi

branch_name: refs/heads/jethro


text:
#include "gl_operator_test.h"

namespace caffe2 {

TEST(OPENGLOperatorTest, CopyFromGL) {

  for (auto dims: std::vector<std::vector<int>>{
      {1},
      {3},
      {1, 2},
      {2, 3},
      {1, 2, 3},
      {1, 2, 3, 4},
      {4, 3, 2, 1},
      {4, 9, 8, 13},
    }) {
    Workspace ws;
    PopulateCPUBlob(&ws, true, std::string("cpu_X"), dims, 1, 0.2, 0.1);

    NetDef gpu_net;
    gpu_net.set_type("opengl");
    {
      OperatorDef* def = AddOp(&gpu_net, "CopyFromGL", {"cpu_X"}, {"cpu_X2"});
      MAKE_OPENGL_OPERATOR(def);
    }
    ws.RunNetOnce(gpu_net);
    Blob *cpu_out = ws.GetBlob("cpu_X");
    Blob *gpu_out = ws.GetBlob("cpu_X2");
    EXPECT_NE(nullptr, cpu_out);
    EXPECT_NE(nullptr, gpu_out);

    auto &t1 = cpu_out->Get<TensorCPU>();
    auto &t2 = gpu_out->Get<TensorCPU>();
    double tol=0.01;
    for (auto i = 0; i < t1.size(); ++i) {
      EXPECT_NEAR(t1.data<float>()[i], t2.data<float>()[i], tol)
        << "at index " << i;
    }
  }
}

} // namespace caffe2

repository: blackxer/AICamera

repo_name: blackxer/AICamera

extension: cc


text:
@string{vldb2008 = "Proceedings of the 34th International Conference on Very Large Data Bases (VLDB'08)"}
@string{vldb2005 = "Proceedings of the 31st International Conference on Very Large Data Bases (VLDB'05)"}

@inproceedings{stonebraker:cstore:vldb2005,
    author = "Mike Stonebraker and Daniel Abadi and Adam Batkin and Xuedong Chen and Mitch Cherniack and Miguel Ferreira and Edmond Lau and Amerson Lin and Sam Madden and Elizabeth O'Neil and Pat O'Neil and Alex Rasin and Nga Tran and Stan Zdonik",
    title = "{C-Store}: A column oriented {DBMS}",
    booktitle = vldb2005,
    pages = "553-564",
    month = "September 2",
    year = "2005"
}

@inproceedings{Cooper08pnuts,
author = "Cooper, Brian F. and Ramakrishnan,  Raghu and  Srivastava, Utkarsh and  Silberstein, Adam and Bohannon, Philip and Jacobsen, Hans-Arno and Puz, Nick and Weaver, Daniel and  Yerneni, Ramana",
title = "{PNUTS}: {Y}ahoo!'s Hosted Data Serving Platform",
booktitle = vldb2008,
year = "2008",
pages = "1277--1288",
month = "August",
}

repository: dataseries/Lintel

repo_name: dataseries/Lintel

gha_license_id: NOASSERTION

gha_language: Perl

extension: bib


text:
@article{drogovoz_economic_2021,
 abstract = {Subject. This article explores the process of introducing digital technologies into the oil and gas industry production and management and getting the economic impact of such implementation.
Objectives. The article aims to identify and assess the economic impact of the introduction of digital production technologies in the oil and gas industry over the past five years, and describe the positive and negative effects of digitalization of the oil and gas industry.
Methods. For the study, we used the methods of comparative and statistical analyses, forecast data obtaining, and synthesis of results.
Results. The article reveals the main effects of the digitalization of the oil and gas industry over the past five years. It describes the positive and negative effects of the digitalization of the oil and gas industry and predicts the effectiveness of this process. The article presents developed strategic guidelines to create new competitive advantages of the oil and gas industry through the production digitalization.
Conclusions and Relevance. To maintain efficiency and create additional competitive advantages of the Russian oil and gas industry, it is necessary to actively introduce digital technologies of production and management, new IT-strategies. The findings and results obtained can be useful to scientists specializing in the digitalization of the oil and gas industry and for managers of different levels of oil and gas sphere to apply them in strategic production management.},
 author = {Drogovoz, Pavel A. and Kharin, Nikita I.},
 doi = {10.24891/fc.27.3.672},
 issn = {20714688, 23118709},
 journal = {FC},
 month = {March},
 number = {3},
 pages = {672--692},
 title = {The economic benefits of digitalization in the oil and gas industry},
 url = {https://www.fin-izdat.com/journal/fc/detail.php?ID=77058},
 urldate = {2021-04-22},
 volume = {27},
 year = {2021}
}


text:
package handler_test

import (
	"net/http"
	"net/http/httptest"

	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	"code.cloudfoundry.org/tps/handler"
	"code.cloudfoundry.org/tps/handler/handler_fakes"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
)

var _ = Describe("Middleware", func() {
	var httpHandler http.Handler
	var wrappedHandler *handler_fakes.FakeHandler
	var req *http.Request
	var res *httptest.ResponseRecorder
	var logger lager.Logger

	BeforeEach(func() {
		req = newTestRequest("")
		res = httptest.NewRecorder()
		wrappedHandler = new(handler_fakes.FakeHandler)
		logger = lagertest.NewTestLogger("test")
	})

	Describe("LogWrap", func() {
		BeforeEach(func() {
			httpHandler = handler.LogWrap(wrappedHandler, logger)
		})

		Context("when the handler serves request", func() {
			BeforeEach(func() {
				httpHandler.ServeHTTP(res, req)
			})

			It("calls the wrapped handler", func() {
				Expect(wrappedHandler.ServeHTTPCallCount()).To(Equal(1))
			})

			It("logs before serving", func() {
				Expect(logger).To(gbytes.Say("serving"))
			})

			It("logs after serving", func() {
				Expect(logger).To(gbytes.Say("done"))
			})
		})
	})
})

repository: PaaS-TA/PaaS-TA-Core

repo_name: PaaS-TA/PaaS-TA-Core


text:
package main

import (
	"github.com/broqiang/mdblog/app"
)

func main() {

	// 初始化 gin 引擎
	engine := app.Init()

	// 启动服务
	app.Run(engine)
}

repository: broqiang/mdblog

repo_name: broqiang/mdblog


text:
DESCRIPTION = "TI Image Processing Demo for KeyStone 2"
HOMEPAGE = "http://git.ti.com/cgit/cgit.cgi/keystone-demos/image-proc.git"
LICENSE = "BSD & MIT"
LIC_FILES_CHKSUM = "file://Makefile;beginline=1;endline=29;md5=ada2acff673fad7c53cbfd2598525f2a"
SECTION = "console"
COMPATIBLE_MACHINE = "keystone"

DEPENDS = "ti-ipc"

BRANCH = "master"
SRC_URI = "git://git.ti.com/keystone-demos/image-proc.git;protocol=git;branch=${BRANCH}"
#Commit corresponds to DEV.DEMO_IMAGE_PROC-01.00.00.03
SRCREV = "d1f4014d28ecedf34dbd20f04d4277eb1c4b8ae0"
PV = "1.0.0.3"

S = "${WORKDIR}/git"

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

do_install() {
	if [ ! -d ${D}/${bindir} ]
	then
		install -d ${D}${bindir}
	fi
	install -c -m 755 ${S}/ipc/master/image_processing_master.out ${D}${bindir}/image_processing_master
}

repository: varigit/meta-arago-var

repo_name: varigit/meta-arago-var


text:
require linux.inc

SECTION = "kernel"
DESCRIPTION = "Linux kernel for the Compulab EM-X270 system"
LICENSE = "GPL"
DEPENDS = "u-boot-utils-native"
PR = "r1"

KERNEL_IMAGETYPE = "uImage"

SRC_URI = "${KERNELORG_MIRROR}/pub/linux/kernel/v2.6/linux-${PV}.tar.bz2 \
	   file://em-x270.patch;patch=1 \
           file://defconfig \
	  "

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

COMPATIBLE_HOST = 'arm.*-linux'
COMPATIBLE_MACHINE = "em-x270"

inherit kernel
inherit package

ARCH = "arm"

FILES_kernel-image = ""

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


text:
package timeout

import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

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

type TimeoutSuite struct {
	suite.Suite

	server *httptest.Server
}

func (s *TimeoutSuite) SetupSuite() {
	mux := http.NewServeMux()

	mux.Handle("/hello", http.HandlerFunc(helloHandler))
	mux.Handle("/timeout", http.HandlerFunc(timeoutHandler))

	s.server = httptest.NewServer(Handler(mux, time.Second,
		DefaultTimeoutHandler))
}

func (s *TimeoutSuite) TestTimeout() {
	req, err := http.NewRequest(http.MethodGet, s.server.URL+"/timeout", nil)
	s.Nil(err)

	res, err := sendRequest(req)
	s.Nil(err)
	s.Equal(http.StatusGatewayTimeout, res.StatusCode)
	s.Equal([]byte("Service timeout"), getResRawBody(res))
}

func (s *TimeoutSuite) TestNotTimeout() {
	req, err := http.NewRequest(http.MethodGet, s.server.URL+"/hello", nil)
	s.Nil(err)

	res, err := sendRequest(req)
	s.Nil(err)
	s.Equal(http.StatusOK, res.StatusCode)
	s.Equal([]byte("Hello World"), getResRawBody(res))
}

func TestTimeout(t *testing.T) {
	suite.Run(t, new(TimeoutSuite))
}

func helloHandler(res http.ResponseWriter, req *http.Request) {
	res.WriteHeader(http.StatusOK)

	res.Write([]byte("Hello World"))
}

func timeoutHandler(res http.ResponseWriter, req *http.Request) {
	res.WriteHeader(http.StatusOK)

	res.Write([]byte("Hello World"))
	<-time.After(2 * time.Second)
}

func sendRequest(req *http.Request) (*http.Response, error) {
	cli := &http.Client{}
	return cli.Do(req)
}

func getResRawBody(res *http.Response) []byte {
	bytes, err := ioutil.ReadAll(res.Body)

	if err != nil {
		panic(err)
	}

	return bytes
}

repository: vellotis/go-http-utils-timeout

repo_name: vellotis/go-http-utils-timeout


text:
//
// (C) Copyright 2019-2020 Intel Corporation.
//
// 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.
//
// GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE
// The Government's rights to use, modify, reproduce, release, perform, display,
// or disclose this software are subject to the terms of the Apache License as
// provided in Contract No. 8F-30005.
// Any reproduction of computer software, computer software documentation, or
// portions thereof marked with this legend must also reproduce the markings.
//

package bdev

import (
	"sync"

	"github.com/pkg/errors"

	"github.com/daos-stack/daos/src/control/fault"
	"github.com/daos-stack/daos/src/control/logging"
	"github.com/daos-stack/daos/src/control/pbin"
	"github.com/daos-stack/daos/src/control/server/storage"
)

type (
	// ScanRequest defines the parameters for a Scan operation.
	ScanRequest struct {
		pbin.ForwardableRequest
		DeviceList []string
		DisableVMD bool
		Rescan     bool
	}

	// ScanResponse contains information gleaned during a successful Scan operation.
	ScanResponse struct {
		Controllers storage.NvmeControllers
	}

	// PrepareRequest defines the parameters for a Prepare operation.
	PrepareRequest struct {
		pbin.ForwardableRequest
		HugePageCount int
		PCIWhitelist  string
		PCIBlacklist  string
		TargetUser    string
		ResetOnly     bool
		DisableVFIO   bool
		DisableVMD    bool
	}

	// PrepareResponse contains the results of a successful Prepare operation.
	PrepareResponse struct {
		VmdDetected bool
	}

	// FormatRequest defines the parameters for a Format operation.
	FormatRequest struct {
		pbin.ForwardableRequest
		Class      storage.BdevClass
		DeviceList []string
		MemSize    int // size MiB memory to be used by SPDK proc
		DisableVMD bool
	}

	// DeviceFormatRequest designs the parameters for a device-specific format.
	DeviceFormatRequest struct {
		MemSize int // size MiB memory to be used by SPDK proc
		Device  string
		Class   storage.BdevClass
	}

	// DeviceFormatResponse contains device-specific Format operation results.
	DeviceFormatResponse struct {
		Formatted bool
		Error     *fault.Fault
	}

	// DeviceFormatResponses is a map of device identifiers to device Format results.
	DeviceFormatResponses map[string]*DeviceFormatResponse

	// FormatResponse contains the results of a Format operation.
	FormatResponse struct {
		DeviceResponses DeviceFormatResponses
	}

	// Backend defines a set of methods to be implemented by a Block Device backend.
	Backend interface {
		PrepareReset() error
		Prepare(PrepareRequest) (*PrepareResponse, error)
		Scan(ScanRequest) (*ScanResponse, error)
		Format(FormatRequest) (*FormatResponse, error)
		DisableVMD()
		IsVMDDisabled() bool
		UpdateFirmware(pciAddr string, path string, slot int32) error
	}

	// Provider encapsulates configuration and logic for interacting with a Block
	// Device Backend.
	Provider struct {
		sync.Mutex // ensure mutually exclusive access to scan cache
		firmwareProvider
		log       logging.Logger
		backend   Backend
		fwd       *Forwarder
		scanCache *ScanResponse
	}
)

// DefaultProvider returns an initialized *Provider suitable for use in production code.
func DefaultProvider(log logging.Logger) *Provider {
	return NewProvider(log, defaultBackend(log))
}

// NewProvider returns an initialized *Provider.
func NewProvider(log logging.Logger, backend Backend) *Provider {
	p := &Provider{
		log:     log,
		backend: backend,
		fwd:     NewForwarder(log),
	}
	p.setupFirmwareProvider(log)
	return p
}

// WithForwardingDisabled returns a provider with forwarding disabled.
func (p *Provider) WithForwardingDisabled() *Provider {
	p.fwd.Disabled = true
	return p
}

func (p *Provider) shouldForward(req pbin.ForwardChecker) bool {
	return !p.fwd.Disabled && !req.IsForwarded()
}

func (p *Provider) disableVMD() {
	p.backend.DisableVMD()
}

// IsVMDDisabled returns true if provider has disabled VMD device awareness.
func (p *Provider) IsVMDDisabled() bool {
	return p.backend.IsVMDDisabled()
}

// Scan attempts to perform a scan to discover NVMe components in the system.
func (p *Provider) Scan(req ScanRequest) (*ScanResponse, error) {
	if p.shouldForward(req) {
		req.DisableVMD = p.IsVMDDisabled()

		p.Lock()
		defer p.Unlock()

		if p.scanCache == nil || req.Rescan {
			p.log.Debug("bdev provider rescan requested")

			resp, err := p.fwd.Scan(req)
			if err != nil {
				return nil, err
			}
			p.scanCache = resp
		}

		return p.scanCache, nil
	}
	// set vmd state on remote provider in forwarded request
	if req.IsForwarded() && req.DisableVMD {
		p.disableVMD()
	}

	return p.backend.Scan(req)
}

// Prepare attempts to perform all actions necessary to make NVMe components available for
// use by DAOS.
func (p *Provider) Prepare(req PrepareRequest) (*PrepareResponse, error) {
	if p.shouldForward(req) {
		resp, err := p.fwd.Prepare(req)
		// set vmd state on local provider after forwarding request
		if err == nil && !resp.VmdDetected {
			p.disableVMD()
		}

		return resp, err
	}

	// run reset first to ensure reallocation of hugepages
	if err := p.backend.PrepareReset(); err != nil {
		return nil, errors.Wrap(err, "bdev prepare reset")
	}

	resp := new(PrepareResponse)
	// if we're only resetting, return before prep
	if req.ResetOnly {
		return resp, nil
	}

	return p.backend.Prepare(req)
}

// Format attempts to initialize NVMe devices for use by DAOS (NB: no-op for non-NVMe devices).
func (p *Provider) Format(req FormatRequest) (*FormatResponse, error) {
	if len(req.DeviceList) == 0 {
		return nil, errors.New("empty DeviceList in FormatRequest")
	}

	if p.shouldForward(req) {
		req.DisableVMD = p.IsVMDDisabled()
		return p.fwd.Format(req)
	}
	// set vmd state on remote provider in forwarded request
	if req.IsForwarded() && req.DisableVMD {
		p.disableVMD()
	}

	return p.backend.Format(req)
}

repository: chaoyongzhou/daos

repo_name: chaoyongzhou/daos


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

package scheduled_maintenances

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

import (
	"fmt"

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

// New creates a new scheduled maintenances API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
	return &Client{transport: transport, formats: formats}
}

/*
Client for scheduled maintenances API
*/
type Client struct {
	transport runtime.ClientTransport
	formats   strfmt.Registry
}

// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)

// ClientService is the interface for Client methods
type ClientService interface {
	DeleteV1ScheduledMaintenancesScheduledMaintenanceID(params *DeleteV1ScheduledMaintenancesScheduledMaintenanceIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteV1ScheduledMaintenancesScheduledMaintenanceIDNoContent, error)

	GetV1ScheduledMaintenances(params *GetV1ScheduledMaintenancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetV1ScheduledMaintenancesOK, error)

	GetV1ScheduledMaintenancesScheduledMaintenanceID(params *GetV1ScheduledMaintenancesScheduledMaintenanceIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetV1ScheduledMaintenancesScheduledMaintenanceIDOK, error)

	PatchV1ScheduledMaintenancesScheduledMaintenanceID(params *PatchV1ScheduledMaintenancesScheduledMaintenanceIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PatchV1ScheduledMaintenancesScheduledMaintenanceIDOK, error)

	PostV1ScheduledMaintenances(params *PostV1ScheduledMaintenancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostV1ScheduledMaintenancesCreated, error)

	SetTransport(transport runtime.ClientTransport)
}

/*
DeleteV1ScheduledMaintenancesScheduledMaintenanceID deletes a scheduled maintenance event

Delete a scheduled maintenance event, preventing it from taking place.
*/
func (a *Client) DeleteV1ScheduledMaintenancesScheduledMaintenanceID(params *DeleteV1ScheduledMaintenancesScheduledMaintenanceIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteV1ScheduledMaintenancesScheduledMaintenanceIDNoContent, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewDeleteV1ScheduledMaintenancesScheduledMaintenanceIDParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "deleteV1ScheduledMaintenancesScheduledMaintenanceId",
		Method:             "DELETE",
		PathPattern:        "/v1/scheduled_maintenances/{scheduled_maintenance_id}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"https"},
		Params:             params,
		Reader:             &DeleteV1ScheduledMaintenancesScheduledMaintenanceIDReader{formats: a.formats},
		AuthInfo:           authInfo,
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*DeleteV1ScheduledMaintenancesScheduledMaintenanceIDNoContent)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for deleteV1ScheduledMaintenancesScheduledMaintenanceId: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
GetV1ScheduledMaintenances lists scheduled maintenance events

Lists all scheduled maintenance events
*/
func (a *Client) GetV1ScheduledMaintenances(params *GetV1ScheduledMaintenancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetV1ScheduledMaintenancesOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetV1ScheduledMaintenancesParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "getV1ScheduledMaintenances",
		Method:             "GET",
		PathPattern:        "/v1/scheduled_maintenances",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"https"},
		Params:             params,
		Reader:             &GetV1ScheduledMaintenancesReader{formats: a.formats},
		AuthInfo:           authInfo,
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*GetV1ScheduledMaintenancesOK)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for getV1ScheduledMaintenances: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
GetV1ScheduledMaintenancesScheduledMaintenanceID retrieves a scheduled maintenance event

Fetch the details of a scheduled maintenance event.
*/
func (a *Client) GetV1ScheduledMaintenancesScheduledMaintenanceID(params *GetV1ScheduledMaintenancesScheduledMaintenanceIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetV1ScheduledMaintenancesScheduledMaintenanceIDOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetV1ScheduledMaintenancesScheduledMaintenanceIDParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "getV1ScheduledMaintenancesScheduledMaintenanceId",
		Method:             "GET",
		PathPattern:        "/v1/scheduled_maintenances/{scheduled_maintenance_id}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"https"},
		Params:             params,
		Reader:             &GetV1ScheduledMaintenancesScheduledMaintenanceIDReader{formats: a.formats},
		AuthInfo:           authInfo,
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*GetV1ScheduledMaintenancesScheduledMaintenanceIDOK)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for getV1ScheduledMaintenancesScheduledMaintenanceId: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
PatchV1ScheduledMaintenancesScheduledMaintenanceID updates a scheduled maintenance event

Change the conditions of a scheduled maintenance event, including updating any status page announcements of changes.
*/
func (a *Client) PatchV1ScheduledMaintenancesScheduledMaintenanceID(params *PatchV1ScheduledMaintenancesScheduledMaintenanceIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PatchV1ScheduledMaintenancesScheduledMaintenanceIDOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewPatchV1ScheduledMaintenancesScheduledMaintenanceIDParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "patchV1ScheduledMaintenancesScheduledMaintenanceId",
		Method:             "PATCH",
		PathPattern:        "/v1/scheduled_maintenances/{scheduled_maintenance_id}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"https"},
		Params:             params,
		Reader:             &PatchV1ScheduledMaintenancesScheduledMaintenanceIDReader{formats: a.formats},
		AuthInfo:           authInfo,
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*PatchV1ScheduledMaintenancesScheduledMaintenanceIDOK)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for patchV1ScheduledMaintenancesScheduledMaintenanceId: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
PostV1ScheduledMaintenances creates a scheduled maintenance event

Create a new scheduled maintenance event
*/
func (a *Client) PostV1ScheduledMaintenances(params *PostV1ScheduledMaintenancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostV1ScheduledMaintenancesCreated, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewPostV1ScheduledMaintenancesParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "postV1ScheduledMaintenances",
		Method:             "POST",
		PathPattern:        "/v1/scheduled_maintenances",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"https"},
		Params:             params,
		Reader:             &PostV1ScheduledMaintenancesReader{formats: a.formats},
		AuthInfo:           authInfo,
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*PostV1ScheduledMaintenancesCreated)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for postV1ScheduledMaintenances: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
	a.transport = transport
}

repository: firehydrant/api-client-go

repo_name: firehydrant/api-client-go


text:
package admin

import (
	"gin-admin/dto"
	"gin-admin/middleware"
	"gin-admin/service"
	"github.com/gin-gonic/gin"
)

func GetRoleList(c *gin.Context)  {
	var q dto.QuerySysRole
	if err := c.ShouldBind(&q); err != nil{
		middleware.ResponseFail(c,201,err.Error())
		return
	}
	roles,total, err := service.GetRoleList(q)
	if err!=nil {
		middleware.ResponseFail(c,202,err.Error())
		return
	}else {
		if q.Page==""||q.PageSize==""{
			middleware.ResponseSucc(c, "获取角色列表",roles)
		}else{
			middleware.ResponseSucc(c, "获取角色列表",map[string]interface{}{
				"items":roles,
				"total":total,
			})
		}

	}
	return
}

func CreateRole(c *gin.Context)  {
	var role dto.SysRole
	if err := c.ShouldBindJSON(&role); err != nil{
		middleware.ResponseFail(c,201,err.Error())
		return
	}

	err := service.SaveRole(role)
	if err!=nil {
		middleware.ResponseFail(c,203,err.Error())
		return
	}else {
		middleware.ResponseSucc(c, "添加角色成功",true)
	}

	return
}
func UpdateRole(c *gin.Context)  {
	var role dto.SysRole
	if err := c.ShouldBindJSON(&role); err != nil{
		middleware.ResponseFail(c,201,err.Error())
		return
	}

		err := service.SaveRole(role)
		if err!=nil {
			middleware.ResponseFail(c,201,err.Error())
			return
		}else {
			middleware.ResponseSucc(c, "修改角色成功",true)
		}

	return
}

func DelRole(c *gin.Context)  {
	var Param dto.QuerySysRole
	err := c.ShouldBindJSON(&Param)
	if err!=nil {

		middleware.ResponseFail(c,201,err.Error())
		return
	}
	err1:= service.DelRole(Param.ID)
	if err1 != nil {
		middleware.ResponseFail(c,202,err1.Error())
	} else {
		middleware.ResponseSucc(c,"删除角色成功", true)
	}
	return
}

repository: whitexiong/gin-admin

repo_name: whitexiong/gin-admin


text:
package main

import (
	"io/ioutil"
	"path/filepath"
	"testing"

	"github.com/restic/restic/internal/test"
)

func TestRejectByPattern(t *testing.T) {
	var tests = []struct {
		filename string
		reject   bool
	}{
		{filename: "/home/user/foo.go", reject: true},
		{filename: "/home/user/foo.c", reject: false},
		{filename: "/home/user/foobar", reject: false},
		{filename: "/home/user/foobar/x", reject: true},
		{filename: "/home/user/README", reject: false},
		{filename: "/home/user/README.md", reject: true},
	}

	patterns := []string{"*.go", "README.md", "/home/user/foobar/*"}

	for _, tc := range tests {
		t.Run("", func(t *testing.T) {
			reject := rejectByPattern(patterns)
			res := reject(tc.filename, nil)
			if res != tc.reject {
				t.Fatalf("wrong result for filename %v: want %v, got %v",
					tc.filename, tc.reject, res)
			}
		})
	}
}

func TestIsExcludedByFile(t *testing.T) {
	const (
		tagFilename = "CACHEDIR.TAG"
		header      = "Signature: 8a477f597d28d172789f06886806bc55"
	)
	tests := []struct {
		name    string
		tagFile string
		content string
		want    bool
	}{
		{"NoTagfile", "", "", false},
		{"EmptyTagfile", tagFilename, "", true},
		{"UnnamedTagFile", "", header, false},
		{"WrongTagFile", "notatagfile", header, false},
		{"IncorrectSig", tagFilename, header[1:], false},
		{"ValidSig", tagFilename, header, true},
		{"ValidPlusStuff", tagFilename, header + "foo", true},
		{"ValidPlusNewlineAndStuff", tagFilename, header + "\nbar", true},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			tempDir, cleanup := test.TempDir(t)
			defer cleanup()

			foo := filepath.Join(tempDir, "foo")
			err := ioutil.WriteFile(foo, []byte("foo"), 0666)
			if err != nil {
				t.Fatalf("could not write file: %v", err)
			}
			if tc.tagFile != "" {
				tagFile := filepath.Join(tempDir, tc.tagFile)
				err = ioutil.WriteFile(tagFile, []byte(tc.content), 0666)
				if err != nil {
					t.Fatalf("could not write tagfile: %v", err)
				}
			}
			h := header
			if tc.content == "" {
				h = ""
			}
			if got := isExcludedByFile(foo, tagFilename, h, nil); tc.want != got {
				t.Fatalf("expected %v, got %v", tc.want, got)
			}
		})
	}
}

repository: michaeldorner/restic

repo_name: michaeldorner/restic


text:
@article{chen2017survey,
  title={A survey on dialogue systems: Recent advances and new frontiers},
  author={Chen, Hongshen and Liu, Xiaorui and Yin, Dawei and Tang, Jiliang},
  journal={Acm Sigkdd Explorations Newsletter},
  volume={19},
  number={2},
  pages={25--35},
  year={2017},
  publisher={ACM New York, NY, USA}
}

url: https://raw.githubusercontent.com/rbt-c/DL-NLP-Readings/82ca76e9184a3b00ac87129d99391477c85cfcd2/Bibtex/A Survey on Dialogue Systems.bib

repository: rbt-c/DL-NLP-Readings

repo_name: rbt-c/DL-NLP-Readings

filename: A Survey on Dialogue Systems.bib


text:
package perconaservermongodb

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"strconv"
	"strings"

	api "github.com/percona/percona-server-mongodb-operator/pkg/apis/psmdb/v1"
	"github.com/percona/percona-server-mongodb-operator/pkg/psmdb"
	"github.com/percona/percona-server-mongodb-operator/pkg/psmdb/mongo"
	"github.com/pkg/errors"
	mgo "go.mongodb.org/mongo-driver/mongo"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
)

func (r *ReconcilePerconaServerMongoDB) mongoClientWithRole(cr *api.PerconaServerMongoDB, rs api.ReplsetSpec,
	role UserRole) (*mgo.Client, error) {

	c, err := r.getInternalCredentials(cr, role)
	if err != nil {
		return nil, errors.Wrap(err, "failed to get credentials")
	}

	return r.mongoClient(cr, rs, c)
}

func (r *ReconcilePerconaServerMongoDB) mongoClient(cr *api.PerconaServerMongoDB, rs api.ReplsetSpec,
	c Credentials) (*mgo.Client, error) {

	pods, err := r.getRSPods(cr, rs.Name)
	if err != nil {
		return nil, errors.Wrapf(err, "get pods list for replset %s", rs.Name)
	}

	rsAddrs, err := psmdb.GetReplsetAddrs(r.client, cr, rs.Name, rs.Expose.Enabled, pods.Items)
	if err != nil {
		return nil, errors.Wrap(err, "get replset addr")
	}

	conf := &mongo.Config{
		ReplSetName: rs.Name,
		Hosts:       rsAddrs,
		Username:    c.Username,
		Password:    c.Password,
	}

	if !cr.Spec.UnsafeConf {
		tlsCfg, err := r.tlsConfig(cr)
		if err != nil {
			return nil, errors.Wrap(err, "failed to get TLS config")
		}

		conf.TLSConf = &tlsCfg
	}

	return mongo.Dial(conf)
}

func (r *ReconcilePerconaServerMongoDB) tlsConfig(cr *api.PerconaServerMongoDB) (tls.Config, error) {
	certSecret := &corev1.Secret{}
	err := r.client.Get(context.TODO(), types.NamespacedName{
		Name:      cr.Spec.Secrets.SSL,
		Namespace: cr.Namespace,
	}, certSecret)
	if err != nil {
		return tls.Config{}, errors.Wrap(err, "get ssl certSecret")
	}
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(certSecret.Data["ca.crt"])

	var clientCerts []tls.Certificate
	cert, err := tls.X509KeyPair(certSecret.Data["tls.crt"], certSecret.Data["tls.key"])
	if err != nil {
		return tls.Config{}, errors.Wrap(err, "load keypair")
	}
	clientCerts = append(clientCerts, cert)

	return tls.Config{
		InsecureSkipVerify: true,
		RootCAs:            pool,
		Certificates:       clientCerts,
	}, nil
}

func (r *ReconcilePerconaServerMongoDB) mongosClientWithRole(cr *api.PerconaServerMongoDB, role UserRole) (*mgo.Client, error) {
	c, err := r.getInternalCredentials(cr, role)
	if err != nil {
		return nil, errors.Wrap(err, "failed to get credentials")
	}

	return r.mongosClient(cr, c)
}

func (r *ReconcilePerconaServerMongoDB) mongosClient(cr *api.PerconaServerMongoDB, c Credentials) (*mgo.Client, error) {
	conf := mongo.Config{
		Hosts: []string{strings.Join([]string{cr.Name + "-mongos", cr.Namespace, cr.Spec.ClusterServiceDNSSuffix}, ".") +
			":" + strconv.Itoa(int(cr.Spec.Sharding.Mongos.Port))},
		Username: c.Username,
		Password: c.Password,
	}

	if !cr.Spec.UnsafeConf {
		tlsCfg, err := r.tlsConfig(cr)
		if err != nil {
			return nil, errors.Wrap(err, "failed to get TLS config")
		}

		conf.TLSConf = &tlsCfg
	}

	return mongo.Dial(&conf)
}


text:
# --- PvApi ---
if(NOT HAVE_PVAPI)
  if(X86_64)
    set(arch x64)
  else()
    set(arch x86)
  endif()
  find_path(PVAPI_INCLUDE "PvApi.h"
    PATHS "${PVAPI_ROOT}" ENV PVAPI_ROOT
    PATH_SUFFIXES "inc-pc")
  find_library(PVAPI_LIBRARY "PvAPI"
    PATHS "${PVAPI_ROOT}" ENV PVAPI_ROOT
    PATH_SUFFIXES "bin-pc/${arch}/${gcc}")
  if(PVAPI_INCLUDE AND PVAPI_LIBRARY)
    set(HAVE_PVAPI TRUE)
  endif()
endif()

if(HAVE_PVAPI)
  ocv_add_external_target(pvapi "${PVAPI_INCLUDE}" "${PVAPI_LIBRARY}" "HAVE_PVAPI")
endif()

repository: opencv/opencv

repo_name: opencv/opencv

extension: cmake


text:
// +build cxfx

package cxfx

import (
	"github.com/skycoin/cx/cx/ast"
	"unicode/utf8"

	"github.com/skycoin/gltext"

	"github.com/skycoin/cx/cx/packages/cxos"
)

var fonts map[string]*gltext.Font = make(map[string]*gltext.Font, 0)

func loadTrueType(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue, fixedPipeline bool) {
	if file := cxos.ValidFile(inputs[0].Get_i32(prgrm)); file != nil {
		if theFont, err := gltext.LoadTruetype(file,
			inputs[2].Get_i32(prgrm), rune(inputs[3].Get_i32(prgrm)), rune(inputs[4].Get_i32(prgrm)),
			gltext.Direction(inputs[5].Get_i32(prgrm)), fixedPipeline); err == nil {
			fonts[inputs[1].Get_str(prgrm)] = theFont
		}
	}
}

func opGltextLoadTrueType(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) {
	loadTrueType(prgrm, inputs, outputs, true)
}

func opGltextLoadTrueTypeCore(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) {
	loadTrueType(prgrm, inputs, outputs, false)
}

func opGltextPrintf(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) {
	if err := fonts[inputs[0].Get_str(prgrm)].Printf(inputs[1].Get_f32(prgrm), inputs[2].Get_f32(prgrm), inputs[3].Get_str(prgrm)); err != nil {
		panic(err)
	}
}

func opGltextMetrics(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) {
	width, height := fonts[inputs[0].Get_str(prgrm)].Metrics(inputs[1].Get_str(prgrm))

	outputs[0].Set_i32(prgrm, int32(width))
	outputs[1].Set_i32(prgrm, int32(height))
}

func opGltextTexture(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) {
	outputs[0].Set_i32(prgrm, int32(fonts[inputs[0].Get_str(prgrm)].Texture()))
}

func opGltextNextGlyph(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) { // refactor
	font := fonts[inputs[0].Get_str(prgrm)]
	str := inputs[1].Get_str(prgrm)
	var index int = int(inputs[2].Get_i32(prgrm))
	var runeValue rune = -1
	var width int = -1
	var x int = 0
	var y int = 0
	var w int = 0
	var h int = 0
	var advance int = 0
	if index < len(str) {
		runeValue, width = utf8.DecodeRuneInString(str[index:])
		g := font.Glyphs()[runeValue-font.Low()]
		x = g.X
		y = g.Y
		w = g.Width
		h = g.Height
		advance = g.Advance
	}

	outputs[0].Set_i32(prgrm, int32(runeValue-font.Low()))
	outputs[1].Set_i32(prgrm, int32(width))
	outputs[2].Set_i32(prgrm, int32(x))
	outputs[3].Set_i32(prgrm, int32(y))
	outputs[4].Set_i32(prgrm, int32(w))
	outputs[5].Set_i32(prgrm, int32(h))
	outputs[6].Set_i32(prgrm, int32(advance))
}

func opGltextGlyphBounds(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) {
	font := fonts[inputs[0].Get_str(prgrm)]
	var maxGlyphWidth, maxGlyphHeight int = font.GlyphBounds()
	outputs[0].Set_i32(prgrm, int32(maxGlyphWidth))
	outputs[1].Set_i32(prgrm, int32(maxGlyphHeight))
}

func opGltextGlyphMetrics(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) { // refactor
	width, height := fonts[inputs[0].Get_str(prgrm)].GlyphMetrics(uint32(inputs[1].Get_i32(prgrm)))

	outputs[0].Set_i32(prgrm, int32(width))
	outputs[1].Set_i32(prgrm, int32(height))
}

func opGltextGlyphInfo(prgrm *ast.CXProgram, inputs []ast.CXValue, outputs []ast.CXValue) { // refactor
	font := fonts[inputs[0].Get_str(prgrm)]
	glyph := inputs[1].Get_i32(prgrm)
	var x int = 0
	var y int = 0
	var w int = 0
	var h int = 0
	var advance int = 0
	g := font.Glyphs()[glyph]
	x = g.X
	y = g.Y
	w = g.Width
	h = g.Height
	advance = g.Advance

	outputs[0].Set_i32(prgrm, int32(x))
	outputs[1].Set_i32(prgrm, int32(y))
	outputs[2].Set_i32(prgrm, int32(w))
	outputs[3].Set_i32(prgrm, int32(h))
	outputs[4].Set_i32(prgrm, int32(advance))
}

repository: skycoin/cx

repo_name: skycoin/cx

branch_name: refs/heads/develop


text:
@TechReport{Caldwell2016,
author={Caldwell, Lucius K.
and Simonis, Juniper L.
and Contor, Craig R.
and Sheoships, Matthew},
institution={Cramer Fish Sciences},
title={Juvenile steelhead and chinook production and smolt survival. 2016 Annual Progress Report for the Umatilla Basin Natural Production Monitoring and Evaluation Project},
year={2016},
address={Gresham, OR},
note={Report},
pages={40},
language={English}
}