text:
require u-boot.inc

# This is needs to be validated among supported BSP's before we can
# make it default
DEFAULT_PREFERENCE = "-1"

LICENSE = "GPLv2+"
LIC_FILES_CHKSUM = "file://COPYING;md5=1707d6db1d42237583f50183a5651ecb"

PV = "v2013.01.01+git${SRCPV}"

COMPATIBLE_MACHINE = "(alt|gose|koelsch|lager|porter|silk)"

SRCREV = "b653737dfca271d2f3d96cf02c67cabef6112dab"
SRC_URI = "git://git.denx.de/u-boot-sh.git;branch=renesas/bsp/rcar-gen2-1.9.2;protocol=git"

S = "${WORKDIR}/git"

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

SRC_URI_append_porter = " \
	file://0001-uboot-Silk-board-support.patch \
	file://0004-uboot-porter-board-support.patch \
	file://0005-uboot-serial-sh-SCIF-internal-clock-support.patch \
	file://0006-uboot-Silk-disable-dcache-until-fixed.patch \
"
SRC_URI_append_silk = " \
	file://0001-uboot-Silk-board-support.patch \
	file://0004-uboot-porter-board-support.patch \
	file://0005-uboot-serial-sh-SCIF-internal-clock-support.patch \
	file://0006-uboot-Silk-disable-dcache-until-fixed.patch \
"

repository: jonathanmaw/meta-renesas

repo_name: jonathanmaw/meta-renesas


text:
// Tencent is pleased to support the open source community by making TNN available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.

#include "graph/attr_value.h"
#include "npu_base_layer_convert.h"
#include "npu_conv_layer_convert_impl.h"
#include "npu_utils.h"

namespace TNN_NS {

class NpuDeconvLayer : public NpuConvImplLayer {
public:
    NpuDeconvLayer(LayerType ignore) : NpuConvImplLayer(LAYER_DECONVOLUTION){};
    virtual ~NpuDeconvLayer() {}

protected:
    virtual Status Convert() {
        Status ret = ObtainParam();
        if (ret != TNN_OK) {
            return ret;
        }
        auto resource = dynamic_cast<ConvLayerResource *>(resource_);
        if (!resource) {
            return Status(TNNERR_MODEL_ERR, "Error: DeConvLayerResource is empty");
        }

        if (!(NpuUtils::VersionCompare(npu_version_, "100.320.xxx.xxx", VCT_BIGEQUAL) &&
              ((NpuUtils::VersionCompare(npu_version_, "100.320.010.023", VCT_BIGEQUAL) &&
                NpuUtils::VersionCompare(npu_version_, "100.320.010.999", VCT_SMALLER)) ||
               (NpuUtils::VersionCompare(npu_version_, "100.320.011.019", VCT_BIGEQUAL) &&
                NpuUtils::VersionCompare(npu_version_, "100.320.011.999", VCT_SMALLER)) ||
               (NpuUtils::VersionCompare(npu_version_, "100.320.012.011", VCT_BIGEQUAL) &&
                NpuUtils::VersionCompare(npu_version_, "100.320.012.999", VCT_SMALLER))))) {
            if (resource->bias_handle.GetDataCount() > 0) {
                LOGE("Current IR deconv does not support bias (npu version: %s)\n", npu_version_.c_str());
                return Status(TNNERR_LAYER_ERR, "Error: Current IR deconv does not support bias");
            }
        }

        const int input_channel = input_ops_[0]->GetShape()[1];

        // filter
        int filter_channel = (resource->filter_handle.GetDataCount() / (kernel_h_ * kernel_w_ * input_channel));
        ge::Shape filter_shape({input_channel, filter_channel, kernel_h_, kernel_w_});
        auto filter_const = std::make_shared<ge::op::Const>(layer_name_ + "filter");
        NpuUtils::CreateAttrValue(filter_const, filter_shape, resource->filter_handle);
        weight_ops_.push_back(filter_const);

        // bias
        int bias_count  = resource->bias_handle.GetDataCount();
        auto bias_const = std::make_shared<ge::op::Const>(layer_name_ + "_bias");
        if (bias_count != 0) {
            // bias
            ge::Shape bias_shape({1, bias_count, 1, 1});
            NpuUtils::CreateAttrValue(bias_const, bias_shape, resource->bias_handle);
            weight_ops_.push_back(bias_const);
        }

        std::string deconv_op_name = outputs_name_[0];
        if (activation_type_ != ActivationType_None) {
            deconv_op_name = layer_name_ + "_deconv_op";
        }
        auto deconv_op = std::make_shared<hiai::op::ConvTranspose>(deconv_op_name);
        deconv_op->set_input_filter(*filter_const);
        if (bias_count != 0) {
            deconv_op->set_input_bias(*bias_const);
        }
        deconv_op->set_input_x(*input_ops_[0]->GetOperator());
        deconv_op->set_attr_groups(group_);
        if (0 == pad_type_ || 3 == pad_type_) {
            deconv_op->set_attr_pad_mode("SAME");
            deconv_op->set_attr_pads(ge::AttrValue::LIST_INT({0, 0, 0, 0}));
        } else if (1 == pad_type_) {
            deconv_op->set_attr_pad_mode("VALID");
            deconv_op->set_attr_pads(ge::AttrValue::LIST_INT({0, 0, 0, 0}));
        } else {
            deconv_op->set_attr_pad_mode("SPECIFIC");
            deconv_op->set_attr_pads(ge::AttrValue::LIST_INT({pad_h_begin_, pad_h_end_, pad_w_begin_, pad_w_end_}));
        }
        deconv_op->set_attr_strides(ge::AttrValue::LIST_INT({stride_h_, stride_w_}));
        deconv_op->set_attr_dilations(ge::AttrValue::LIST_INT({dilation_h_, dilation_w_}));

        if (activation_type_ == ActivationType_None) {
            ADD_OUTPUT_OP(deconv_op)
        } else {
            weight_ops_.push_back(deconv_op);

            if (activation_type_ == ActivationType_ReLU) {
                auto activation_op = std::make_shared<hiai::op::Activation>(outputs_name_[0]);
                activation_op->set_input_x(*deconv_op);
                activation_op->set_attr_mode(1);
                ADD_OUTPUT_OP(activation_op)
            } else if (activation_type_ == ActivationType_ReLU6) {
                auto activation_op = std::make_shared<hiai::op::Activation>(outputs_name_[0]);
                activation_op->set_input_x(*deconv_op);
                activation_op->set_attr_mode(14);
                ADD_OUTPUT_OP(activation_op)
            } else if (activation_type_ == ActivationType_SIGMOID_MUL) {
                auto activation_op = std::make_shared<hiai::op::Activation>(layer_name_ + "_sigmoid");
                activation_op->set_input_x(*deconv_op);
                activation_op->set_attr_mode(0);
                weight_ops_.push_back(activation_op);

                auto mul_op = std::make_shared<hiai::op::Mul>(outputs_name_[0]);
                mul_op->set_input_x1(*deconv_op);
                mul_op->set_input_x2(*activation_op);
                ADD_OUTPUT_OP(mul_op)
            } else {
                LOGE("the deconvolution activation type (%d) is not support in HUAWEI_NPU yet\n", activation_type_);
                return Status(TNNERR_PARAM_ERR, "the deconvolution activation type is not support in HUAWEI_NPU yet");
            }
        }
    }
};
REGISTER_NPU_LAYER(Deconv, LAYER_DECONVOLUTION)

}  // namespace TNN_NS

repository: shaundai-tencent/TNN

license_type: permissive

repo_name: shaundai-tencent/TNN

branch_name: refs/heads/master

gha_license_id: NOASSERTION

extension: cc


text:
package Solution

func Solution(arr []int) []int {
	max := -1
	for i := len(arr) - 1; i >= 0; i-- {
		t := arr[i]
		arr[i] = max
		if t > max {
			max = t
		}
	}
	return arr
}

repository: hemingyuan/awesome-golang-leetcode

repo_name: hemingyuan/awesome-golang-leetcode

gha_language: Go

extension: go


text:
# base recipe: meta/recipes-connectivity/libpcap/libpcap_1.8.1.bb
# base branch: yocto-2.4
# base commit: fd8e632832eb9e0712b2869a3625821aef9cb7e4

SUMMARY = "Interface for user-level network packet capture"
DESCRIPTION = "Libpcap provides a portable framework for low-level network \
monitoring.  Libpcap can provide network statistics collection, \
security monitoring and network debugging."
HOMEPAGE = "http://www.tcpdump.org/"
BUGTRACKER = "http://sourceforge.net/tracker/?group_id=53067&atid=469577"
SECTION = "libs/network"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://LICENSE;md5=5eb289217c160e2920d2e35bddc36453 \
                    file://pcap.h;beginline=1;endline=32;md5=39af3510e011f34b8872f120b1dc31d2"
DEPENDS = "flex-native bison-native"

INC_PR = "r5"

BINCONFIG = "${bindir}/pcap-config"

inherit autotools binconfig-disabled pkgconfig bluetooth debian-package
require recipes-debian/sources/libpcap.inc

EXTRA_OECONF = "--with-pcap=linux"
EXTRA_AUTORECONF += "--exclude=aclocal"

PACKAGECONFIG ??= "${@bb.utils.contains('DISTRO_FEATURES', 'bluetooth', '${BLUEZ}', '', d)} \
                   ${@bb.utils.filter('DISTRO_FEATURES', 'ipv6', d)} \
"
PACKAGECONFIG[bluez4] = "--enable-bluetooth,--disable-bluetooth,bluez4"
# Add a dummy PACKAGECONFIG for bluez5 since it is not supported by libpcap.
PACKAGECONFIG[bluez5] = ",,"
PACKAGECONFIG[dbus] = "--enable-dbus,--disable-dbus,dbus"
PACKAGECONFIG[ipv6] = "--enable-ipv6,--disable-ipv6,"
PACKAGECONFIG[libnl] = "--with-libnl,--without-libnl,libnl"

CPPFLAGS_prepend = "-I${S} "
CFLAGS_prepend = "-I${S} "
CXXFLAGS_prepend = "-I${S} "

do_configure_prepend () {
    sed -i -e's,^V_RPATH_OPT=.*$,V_RPATH_OPT=,' ${S}/pcap-config.in
}

BBCLASSEXTEND = "native"

SRC_URI += " \
    file://libpcap-pkgconfig-support.patch \
    file://0001-Fix-compiler_state_t.ai-usage-when-INET6-is-not-defi.patch \
    file://0002-Add-missing-compiler_state_t-parameter.patch \
    file://fix-grammar-deps.patch \
    file://0010-workaround-for-build-failure.patch \
    file://fix-lds-path.diff \
    file://add-fPIC.diff \
"

#
# make install doesn't cover the shared lib
# make install-shared is just broken (no symlinks)
#

do_configure_prepend () {
    #remove hardcoded references to /usr/include
    sed 's|\([ "^'\''I]\+\)/usr/include/|\1${STAGING_INCDIR}/|g' -i ${S}/configure.ac
}

do_install_prepend () {
    install -d ${D}${libdir}
    install -d ${D}${bindir}
    oe_runmake install-shared DESTDIR=${D}
    oe_libinstall -a -so libpcap ${D}${libdir}
    sed "s|@VERSION@|${PV}|" -i ${B}/libpcap.pc
    install -D -m 0644 libpcap.pc ${D}${libdir}/pkgconfig/libpcap.pc
}

license: MIT

repository: mozoko/meta-debian-extended

repo_name: mozoko/meta-debian-extended

branch_name: refs/heads/warrior

gha_license_id: MIT

extension: bb


text:
PV = "0.0+cvs${SRCDATE}"
SECTION = "x11/libs"
PRIORITY = "optional"
DEPENDS = "virtual/libx11 libsm"
PROVIDES = "xt"
DESCRIPTION = "X Toolkit Intrinsics"
LICENSE =  "X-MIT"
PR = "r1"
SRC_URI = "${FREEDESKTOP_CVS}/xlibs;module=Xt"
S = "${WORKDIR}/Xt"

inherit autotools pkgconfig

do_compile() {
	(
		unset CC LD CXX CCLD
		oe_runmake -C util 'CC=${BUILD_CC}' 'LD=${BUILD_LD}' 'CFLAGS=' 'LDFLAGS=' 'CXXFLAGS=' 'CPPFLAGS=' makestrs
	)
	oe_runmake
}

do_stage () {
	autotools_stage_all
}


text:
DESCRIPTION = "Additional packages beyond console packages shared by TI SDKs"
LICENSE = "MIT"
PR = "r16"

inherit packagegroup

RDEPENDS_${PN} = "\
    dbus \
    expat \
    glib-2.0 \
    libxml2 \
    libpcre \
    iptables \
    iperf \
    arago-gpl-notice \
    arago-feed-config \
    nfs-utils-client \
    "

repository: varigit/meta-arago-var

repo_name: varigit/meta-arago-var


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

package ast

import (
	"fmt"
	"strings"
)

// TypeAnnotation

type TypeAnnotation struct {
	IsResource bool
	Type       Type
	StartPos   Position
}

func (e *TypeAnnotation) String() string {
	if e.IsResource {
		return fmt.Sprintf("@%s", e.Type)
	}
	return fmt.Sprint(e.Type)
}

func (e *TypeAnnotation) StartPosition() Position {
	return e.StartPos
}

func (e *TypeAnnotation) EndPosition() Position {
	return e.Type.EndPosition()
}

type Type interface {
	HasPosition
	fmt.Stringer
	isType()
}

// NominalType represents a named type

type NominalType struct {
	Identifier        Identifier
	NestedIdentifiers []Identifier
}

func (*NominalType) isType() {}

func (t *NominalType) String() string {
	var sb strings.Builder
	sb.WriteString(t.Identifier.String())
	for _, identifier := range t.NestedIdentifiers {
		sb.WriteRune('.')
		sb.WriteString(identifier.String())
	}
	return sb.String()
}

func (t *NominalType) StartPosition() Position {
	return t.Identifier.StartPosition()
}

func (t *NominalType) EndPosition() Position {
	nestedCount := len(t.NestedIdentifiers)
	if nestedCount == 0 {
		return t.Identifier.EndPosition()
	}
	lastIdentifier := t.NestedIdentifiers[nestedCount-1]
	return lastIdentifier.EndPosition()
}

// OptionalType represents am optional variant of another type

type OptionalType struct {
	Type   Type
	EndPos Position
}

func (*OptionalType) isType() {}

func (t *OptionalType) String() string {
	return fmt.Sprintf("%s?", t.Type)
}

func (t *OptionalType) StartPosition() Position {
	return t.Type.StartPosition()
}

func (t *OptionalType) EndPosition() Position {
	return t.EndPos
}

// VariableSizedType is a variable sized array type

type VariableSizedType struct {
	Type Type
	Range
}

func (*VariableSizedType) isType() {}

func (t *VariableSizedType) String() string {
	return fmt.Sprintf("[%s]", t.Type)
}

// ConstantSizedType is a constant sized array type

type ConstantSizedType struct {
	Type Type
	Size *IntegerExpression
	Range
}

func (*ConstantSizedType) isType() {}

func (t *ConstantSizedType) String() string {
	return fmt.Sprintf("[%s; %s]", t.Type, t.Size)
}

// DictionaryType

type DictionaryType struct {
	KeyType   Type
	ValueType Type
	Range
}

func (*DictionaryType) isType() {}

func (t *DictionaryType) String() string {
	return fmt.Sprintf("{%s: %s}", t.KeyType, t.ValueType)
}

// FunctionType

type FunctionType struct {
	ParameterTypeAnnotations []*TypeAnnotation
	ReturnTypeAnnotation     *TypeAnnotation
	Range
}

func (*FunctionType) isType() {}

func (t *FunctionType) String() string {
	var parameters strings.Builder
	for i, parameterTypeAnnotation := range t.ParameterTypeAnnotations {
		if i > 0 {
			parameters.WriteString(", ")
		}
		parameters.WriteString(parameterTypeAnnotation.String())
	}

	return fmt.Sprintf("((%s): %s)", parameters.String(), t.ReturnTypeAnnotation.String())
}

// ReferenceType

type ReferenceType struct {
	Authorized bool
	Type       Type
	StartPos   Position
}

func (*ReferenceType) isType() {}

func (t *ReferenceType) String() string {
	var builder strings.Builder
	if t.Authorized {
		builder.WriteString("auth ")
	}
	builder.WriteRune('&')
	builder.WriteString(t.Type.String())
	return builder.String()
}

func (t *ReferenceType) StartPosition() Position {
	return t.StartPos
}

func (t *ReferenceType) EndPosition() Position {
	return t.Type.EndPosition()
}

// RestrictedType

type RestrictedType struct {
	Type         Type
	Restrictions []*NominalType
	Range
}

func (*RestrictedType) isType() {}

func (t *RestrictedType) String() string {
	var builder strings.Builder
	if t.Type != nil {
		builder.WriteString(t.Type.String())
	}
	builder.WriteRune('{')
	for i, restriction := range t.Restrictions {
		if i > 0 {
			builder.WriteString(", ")
		}
		builder.WriteString(restriction.String())
	}
	builder.WriteRune('}')
	return builder.String()
}

// InstantiationType represents an instantiation of a generic (nominal) type

type InstantiationType struct {
	Type                  Type
	TypeArguments         []*TypeAnnotation
	TypeArgumentsStartPos Position
	EndPos                Position
}

func (*InstantiationType) isType() {}

func (t *InstantiationType) String() string {
	var sb strings.Builder
	sb.WriteString(t.Type.String())
	sb.WriteRune('<')
	for i, typeArgument := range t.TypeArguments {
		if i > 0 {
			sb.WriteString(", ")
		}
		sb.WriteString(typeArgument.String())
	}
	sb.WriteRune('>')
	return sb.String()
}

func (t *InstantiationType) StartPosition() Position {
	return t.Type.StartPosition()
}

func (t *InstantiationType) EndPosition() Position {
	return t.EndPos
}


text:
package acme

import (
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"
	"time"
)

// EncodeDNS01KeyAuthorization encodes a key authorization and provides a value to be put in the TXT record for the _acme-challenge DNS entry.
func EncodeDNS01KeyAuthorization(keyAuth string) string {
	h := sha256.Sum256([]byte(keyAuth))
	return base64.RawURLEncoding.EncodeToString(h[:])
}

// Helper function to determine whether a challenge is "finished" by it's status.
func checkUpdatedChallengeStatus(challenge Challenge) (bool, error) {
	switch challenge.Status {
	case "pending":
		// Challenge objects are created in the "pending" state.
		// TODO: https://github.com/letsencrypt/boulder/issues/3346
		// return true, errors.New("acme: unexpected 'pending' challenge state")
		return false, nil

	case "processing":
		// They transition to the "processing" state when the client responds to the
		//   challenge and the server begins attempting to validate that the client has completed the challenge.
		return false, nil

	case "valid":
		// If validation is successful, the challenge moves to the "valid" state
		return true, nil

	case "invalid":
		// if there is an error, the challenge moves to the "invalid" state.
		if challenge.Error.Type != "" {
			return true, challenge.Error
		}
		return true, errors.New("acme: challenge is invalid, no error provided")

	default:
		return true, fmt.Errorf("acme: unknown challenge status: %s", challenge.Status)
	}
}

// UpdateChallenge responds to a challenge to indicate to the server to complete the challenge.
func (c Client) UpdateChallenge(account Account, challenge Challenge) (Challenge, error) {
	resp, err := c.post(challenge.URL, account.URL, account.PrivateKey, struct{}{}, &challenge, http.StatusOK)
	if err != nil {
		return challenge, err
	}

	if loc := resp.Header.Get("Location"); loc != "" {
		challenge.URL = loc
	}
	challenge.AuthorizationURL = fetchLink(resp, "up")

	if finished, err := checkUpdatedChallengeStatus(challenge); finished {
		return challenge, err
	}

	pollInterval, pollTimeout := c.getPollingDurations()
	end := time.Now().Add(pollTimeout)
	for {
		if time.Now().After(end) {
			return challenge, errors.New("acme: challenge update timeout")
		}
		time.Sleep(pollInterval)

		resp, err := c.post(challenge.URL, account.URL, account.PrivateKey, "", &challenge, http.StatusOK)
		if err != nil {
			// i don't think it's worth exiting the loop on this error
			// it could just be connectivity issue that's resolved before the timeout duration
			continue
		}

		if loc := resp.Header.Get("Location"); loc != "" {
			challenge.URL = loc
		}
		challenge.AuthorizationURL = fetchLink(resp, "up")

		if finished, err := checkUpdatedChallengeStatus(challenge); finished {
			return challenge, err
		}
	}
}

// FetchChallenge fetches an existing challenge from the given url.
func (c Client) FetchChallenge(account Account, challengeURL string) (Challenge, error) {
	challenge := Challenge{}
	resp, err := c.post(challengeURL, account.URL, account.PrivateKey, "", &challenge, http.StatusOK)
	if err != nil {
		return challenge, err
	}

	challenge.URL = resp.Header.Get("Location")
	challenge.AuthorizationURL = fetchLink(resp, "up")

	return challenge, nil
}

repository: eggsampler/acme

repo_name: eggsampler/acme


text:
package run

import (
	"syscall"
	"testing"
	"time"

	apps_v1 "k8s.io/api/apps/v1"
	v1 "k8s.io/api/core/v1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/bpineau/kube-deployments-notifier/config"
	"github.com/bpineau/kube-deployments-notifier/pkg/controllers"
	"github.com/bpineau/kube-deployments-notifier/pkg/controllers/deployment"
	"github.com/bpineau/kube-deployments-notifier/pkg/notifiers/count"
)

var (
	obj1 = &apps_v1.Deployment{ObjectMeta: meta_v1.ObjectMeta{
		Name:      "test",
		Labels:    config.Labels,
		Namespace: v1.NamespaceDefault},
	}
)

func TestRun(t *testing.T) {
	conf := config.FakeConfig(obj1)
	runFromConf(t, conf)
}

func TestRunFailingHealthcheck(t *testing.T) {
	conf := config.FakeConfig(obj1)
	conf.Endpoint = ""
	conf.HealthPort = -1
	runFromConf(t, conf)
}

func runFromConf(t *testing.T, conf *config.KdnConfig) {
	conts = []controllers.Controller{
		&deployment.Controller{},
	}
	notif := new(count.Notifier)
	go Run(conf, notif)

	ch := make(chan int, 1)
	defer close(ch)

	go func() {
		for notif.Count() == 0 {
			time.Sleep(time.Second)
		}
		ch <- notif.Count()
	}()

	select {
	case res := <-ch:
		if res != 1 {
			t.Errorf("Failed to convert an event to a notification")
		}
	case <-time.After(10 * time.Second):
		t.Error("Timeout waiting for a event to pop up as a notification")
	}

	syscall.Kill(syscall.Getpid(), syscall.SIGTERM) //nolint:errcheck
	time.Sleep(300 * time.Millisecond)              // controllers wait for 200ms before stopping
}

repository: bpineau/kube-deployments-notifier

repo_name: bpineau/kube-deployments-notifier


text:
@Article{pmid11302950,
  Author="Sandborn, W. J. ",
  Title="{{R}ational dosing of azathioprine and 6-mercaptopurine}",
  Journal="Gut",
  Year="2001",
  Volume="48",
  Number="5",
  Pages="591--592",
  Month="May"
}

repository: larmcr/px

repo_name: larmcr/px

extension: bib


text:
//          Copyright Edvard Severin Pettersen 2017.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE.md or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include <proxc/config.hpp>

#include <proxc/channel.hpp>
#include <proxc/runtime/context.hpp>
#include <proxc/alt/choice_base.hpp>
#include <proxc/detail/delegate.hpp>

#include <boost/assert.hpp>

PROXC_NAMESPACE_BEGIN
namespace alt {

template<typename T>
class ChoiceRecv : public ChoiceBase
{
public:
    using ItemT = typename std::remove_cv< typename std::decay< T >::type >::type;
    using RxT   = channel::Rx< ItemT >;
    using EndT  = channel::detail::ChanEnd< ItemT >;
    using FnT   = proxc::detail::delegate< void( ItemT ) >;

private:
    RxT &    rx_;
    ItemT    item_;
    EndT     end_;
    FnT      fn_;

public:
    ChoiceRecv( Alt *              alt,
                runtime::Context * ctx,
                RxT &              rx,
                FnT                fn )
        : ChoiceBase{ alt }
        , rx_{ rx }
        , item_{}
        , end_{ ctx, item_, this }
        , fn_{ std::move( fn ) }
    {}

    ~ChoiceRecv() {}

    void enter() noexcept
    {
        rx_.alt_enter( end_ );
    }

    void leave() noexcept
    {
        rx_.alt_leave();
    }

    bool is_ready() const noexcept
    {
        return rx_.alt_ready();
    }

    Result try_complete() noexcept
    {
        auto res = rx_.alt_recv();
        switch ( res ) {
        case channel::AltResult::Ok:       return Result::Ok;
        case channel::AltResult::TryLater: return Result::TryLater;
        default:                           return Result::Failed;
        }
    }

    void run_func() noexcept
    {
        if ( fn_ ) {
            fn_( std::move( item_ ) );
        }
    }
};

} // namespace alt
PROXC_NAMESPACE_END

repository: edvardsp/libproxcplusplus

repo_name: edvardsp/libproxcplusplus

extension: hpp


text:
package platform

// Generated file, please do not change!!!

import (
	"encoding/json"
	"errors"
	"time"
)

type Review struct {
	// Unique identifier of the Review.
	ID string `json:"id"`
	// Current version of the Review.
	Version int `json:"version"`
	// Date and time (UTC) the Review was initially created.
	CreatedAt time.Time `json:"createdAt"`
	// Date and time (UTC) the Review was last updated.
	LastModifiedAt time.Time `json:"lastModifiedAt"`
	// Present on resources created after 1 February 2019 except for [events not tracked](/client-logging#events-tracked).
	LastModifiedBy *LastModifiedBy `json:"lastModifiedBy,omitempty"`
	// Present on resources created after 1 February 2019 except for [events not tracked](/client-logging#events-tracked).
	CreatedBy *CreatedBy `json:"createdBy,omitempty"`
	// User-defined unique identifier of the Review.
	Key *string `json:"key,omitempty"`
	// Must be unique among Reviews. For example, if this value is set to Customer `id` + Product `id`, only one Review per Customer and per Product is allowed.
	UniquenessValue *string `json:"uniquenessValue,omitempty"`
	// Language in which the content of the Review is written.
	Locale *string `json:"locale,omitempty"`
	// Name of the author.
	AuthorName *string `json:"authorName,omitempty"`
	// Title of the Review.
	Title *string `json:"title,omitempty"`
	// Content of the Review.
	Text *string `json:"text,omitempty"`
	// Identifies the target of the Review. Can be a [Product](ctp:api:type:Product) or a [Channel](ctp:api:type:Channel), specified as [ProductReference](ctp:api:type:ProductReference) or [ChannelReference](ctp:api:type:ChannelReference), respectively.
	Target interface{} `json:"target,omitempty"`
	// Indicates if this Review is taken into account in the ratings statistics of the target.
	// A Review is per default used in the statistics, unless the Review is in a state that does not have the [role](ctp:api:type:StateRoleEnum) `ReviewIncludedInStatistics`.
	// If the role of a [State](ctp:api:type:State) is modified after the calculation of this field, the calculation is not updated.
	IncludedInStatistics bool `json:"includedInStatistics"`
	// Rating of the Product or Channel.
	Rating *int `json:"rating,omitempty"`
	// State of the Review. Used for approval processes, see [Review approval process](/../tutorials/review-ratings#review-approval-process) for details.
	State *StateReference `json:"state,omitempty"`
	// Customer who created the Review.
	Customer *CustomerReference `json:"customer,omitempty"`
	// Custom Fields of the Review.
	Custom *CustomFields `json:"custom,omitempty"`
}

/**
*	When creating a new Review, at least one of `title`, `text` or `rating` should be set.
*
 */
type ReviewDraft struct {
	// User-defined unique identifier for the Review.
	Key *string `json:"key,omitempty"`
	// If set, this value must be unique among Reviews.
	// For example, if you want to have only one Review per Customer and per Product, you can set the value to Customer `id` + Product `id`.
	UniquenessValue *string `json:"uniquenessValue,omitempty"`
	// Language in which the content of the Review is written.
	Locale *string `json:"locale,omitempty"`
	// Name of the author.
	AuthorName *string `json:"authorName,omitempty"`
	// Title of the Review.
	Title *string `json:"title,omitempty"`
	// Content of the Review.
	Text *string `json:"text,omitempty"`
	// Identifies the target of the Review. Can be a [Product](ctp:api:type:Product) or a [Channel](ctp:api:type:Channel), specified as [ProductResourceIdentifier](ctp:api:type:ProductResourceIdentifier) or [ChannelResourceIdentifier](ctp:api:type:ChannelResourceIdentifier), respectively.
	Target interface{} `json:"target,omitempty"`
	// State of the Review. Used for approval processes, see [Review approval process](/../tutorials/review-ratings#review-approval-process) for details.
	State *StateResourceIdentifier `json:"state,omitempty"`
	// Rating of the targeted Product or Channel.
	// This rating can represent the number of stars, a percentage, or a like (+1)/dislike (-1).
	// A rating is used in the ratings statistics of the targeted object, unless the Review is in a State that does not have the role `ReviewIncludedInStatistics`.
	Rating *int `json:"rating,omitempty"`
	// Customer who created the Review.
	Customer *CustomerResourceIdentifier `json:"customer,omitempty"`
	// Custom Fields for the Review.
	Custom *CustomFieldsDraft `json:"custom,omitempty"`
}

type ReviewPagedQueryResponse struct {
	// Number of [results requested](/../api/general-concepts#limit).
	Limit int `json:"limit"`
	// Actual number of results returned.
	Count int `json:"count"`
	// Total number of results matching the query.
	// This number is an estimation that is not [strongly consistent](/../api/general-concepts#strong-consistency).
	// This field is returned by default.
	// For improved performance, calculating this field can be deactivated by using the query parameter `withTotal=false`.
	// When the results are filtered with a [Query Predicate](/../api/predicates/query), `total` is subject to a [limit](/../api/limits#queries).
	Total *int `json:"total,omitempty"`
	// Number of [elements skipped](/../api/general-concepts#offset).
	Offset int `json:"offset"`
	// [Reviews](ctp:api:type:Review) matching the query.
	Results []Review `json:"results"`
}

type ReviewRatingStatistics struct {
	// Average rating of one target
	// This number is rounded with 5 decimals.
	AverageRating float64 `json:"averageRating"`
	// Highest rating of one target
	HighestRating float64 `json:"highestRating"`
	// Lowest rating of one target
	LowestRating float64 `json:"lowestRating"`
	// Number of ratings taken into account
	Count int `json:"count"`
	// Full distribution of the ratings.
	// The keys are the different ratings and the values are the count of reviews having this rating.
	// Only the used ratings appear in this object.
	RatingsDistribution interface{} `json:"ratingsDistribution"`
}

/**
*	[Reference](ctp:api:type:Reference) to a [Review](ctp:api:type:Review).
*
 */
type ReviewReference struct {
	// Unique identifier of the referenced [Review](ctp:api:type:Review).
	ID string `json:"id"`
	// Contains the representation of the expanded Review. Only present in responses to requests with [Reference Expansion](/../api/general-concepts#reference-expansion) for Reviews.
	Obj *Review `json:"obj,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewReference) MarshalJSON() ([]byte, error) {
	type Alias ReviewReference
	return json.Marshal(struct {
		Action string `json:"typeId"`
		*Alias
	}{Action: "review", Alias: (*Alias)(&obj)})
}

/**
*	[ResourceIdentifier](ctp:api:type:ResourceIdentifier) to a [Review](ctp:api:type:Review).
*
 */
type ReviewResourceIdentifier struct {
	// Unique identifier of the referenced [Review](ctp:api:type:Review). Either `id` or `key` is required.
	ID *string `json:"id,omitempty"`
	// User-defined unique identifier of the referenced [Review](ctp:api:type:Review). Either `id` or `key` is required.
	Key *string `json:"key,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewResourceIdentifier) MarshalJSON() ([]byte, error) {
	type Alias ReviewResourceIdentifier
	return json.Marshal(struct {
		Action string `json:"typeId"`
		*Alias
	}{Action: "review", Alias: (*Alias)(&obj)})
}

type ReviewUpdate struct {
	// The expected version of the review on which the changes should be applied. If the expected version does not match the actual version, a 409 Conflict will be returned.
	Version int `json:"version"`
	// The list of update actions to be performed on the review.
	Actions []ReviewUpdateAction `json:"actions"`
}

// UnmarshalJSON override to deserialize correct attribute types based
// on the discriminator value
func (obj *ReviewUpdate) UnmarshalJSON(data []byte) error {
	type Alias ReviewUpdate
	if err := json.Unmarshal(data, (*Alias)(obj)); err != nil {
		return err
	}
	for i := range obj.Actions {
		var err error
		obj.Actions[i], err = mapDiscriminatorReviewUpdateAction(obj.Actions[i])
		if err != nil {
			return err
		}
	}

	return nil
}

type ReviewUpdateAction interface{}

func mapDiscriminatorReviewUpdateAction(input interface{}) (ReviewUpdateAction, error) {
	var discriminator string
	if data, ok := input.(map[string]interface{}); ok {
		discriminator, ok = data["action"].(string)
		if !ok {
			return nil, errors.New("error processing discriminator field 'action'")
		}
	} else {
		return nil, errors.New("invalid data")
	}

	switch discriminator {
	case "setAuthorName":
		obj := ReviewSetAuthorNameAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setCustomField":
		obj := ReviewSetCustomFieldAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setCustomType":
		obj := ReviewSetCustomTypeAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setCustomer":
		obj := ReviewSetCustomerAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setKey":
		obj := ReviewSetKeyAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setLocale":
		obj := ReviewSetLocaleAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setRating":
		obj := ReviewSetRatingAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setTarget":
		obj := ReviewSetTargetAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setText":
		obj := ReviewSetTextAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "setTitle":
		obj := ReviewSetTitleAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	case "transitionState":
		obj := ReviewTransitionStateAction{}
		if err := decodeStruct(input, &obj); err != nil {
			return nil, err
		}
		return obj, nil
	}
	return nil, nil
}

type ReviewSetAuthorNameAction struct {
	// Value to set. If empty, any existing value will be removed.
	AuthorName *string `json:"authorName,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetAuthorNameAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetAuthorNameAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setAuthorName", Alias: (*Alias)(&obj)})
}

type ReviewSetCustomFieldAction struct {
	// Name of the [Custom Field](/../api/projects/custom-fields).
	Name string `json:"name"`
	// If `value` is absent or `null`, this field will be removed if it exists.
	// Removing a field that does not exist returns an [InvalidOperation](ctp:api:type:InvalidOperationError) error.
	// If `value` is provided, it is set for the field defined by `name`.
	Value interface{} `json:"value,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetCustomFieldAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetCustomFieldAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setCustomField", Alias: (*Alias)(&obj)})
}

type ReviewSetCustomTypeAction struct {
	// Defines the [Type](ctp:api:type:Type) that extends the Review with [Custom Fields](/../api/projects/custom-fields).
	// If absent, any existing Type and Custom Fields are removed from the Review.
	Type *TypeResourceIdentifier `json:"type,omitempty"`
	// Sets the [Custom Fields](/../api/projects/custom-fields) fields for the Review.
	Fields *FieldContainer `json:"fields,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetCustomTypeAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetCustomTypeAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setCustomType", Alias: (*Alias)(&obj)})
}

type ReviewSetCustomerAction struct {
	// Value to set. If empty, any existing value will be removed.
	Customer *CustomerResourceIdentifier `json:"customer,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetCustomerAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetCustomerAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setCustomer", Alias: (*Alias)(&obj)})
}

type ReviewSetKeyAction struct {
	// Value to set. If empty, any existing value will be removed.
	Key *string `json:"key,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetKeyAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetKeyAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setKey", Alias: (*Alias)(&obj)})
}

type ReviewSetLocaleAction struct {
	// Value to set. If empty, any existing value will be removed.
	Locale *string `json:"locale,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetLocaleAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetLocaleAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setLocale", Alias: (*Alias)(&obj)})
}

/**
*	This update action produces the [ReviewRatingSet](ctp:api:type:ReviewRatingSetMessage) Message.
*
 */
type ReviewSetRatingAction struct {
	// Value to set. If empty, any existing value will be removed.
	Rating *int `json:"rating,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetRatingAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetRatingAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setRating", Alias: (*Alias)(&obj)})
}

type ReviewSetTargetAction struct {
	// Value to set, specified as [ProductResourceIdentifier](ctp:api:type:ProductResourceIdentifier) or [ChannelResourceIdentifier](ctp:api:type:ChannelResourceIdentifier), respectively. If empty, any existing value will be removed.
	Target interface{} `json:"target"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetTargetAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetTargetAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setTarget", Alias: (*Alias)(&obj)})
}

type ReviewSetTextAction struct {
	// Value to set. If empty, any existing value will be removed.
	Text *string `json:"text,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetTextAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetTextAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setText", Alias: (*Alias)(&obj)})
}

type ReviewSetTitleAction struct {
	// Value to set. If empty, any existing value will be removed.
	Title *string `json:"title,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewSetTitleAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewSetTitleAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "setTitle", Alias: (*Alias)(&obj)})
}

/**
*	Transition to a new State. This update action produces the [Review State Transition](ctp:api:type:ReviewStateTransitionMessage) Message.
*
 */
type ReviewTransitionStateAction struct {
	// Value to set. If there is no State yet, the new State must be an initial State. If the existing State has `transitions` set, there must be a direct transition to the new State. If `transitions` is not set, no validation is performed. If the new State does not have the [role](ctp:api:type:StateRoleEnum) `ReviewIncludedInStatistics`, the Review is not taken into account in the ratings statistics of the target.
	State StateResourceIdentifier `json:"state"`
	// Switch validations on or off.
	Force *bool `json:"force,omitempty"`
}

// MarshalJSON override to set the discriminator value or remove
// optional nil slices
func (obj ReviewTransitionStateAction) MarshalJSON() ([]byte, error) {
	type Alias ReviewTransitionStateAction
	return json.Marshal(struct {
		Action string `json:"action"`
		*Alias
	}{Action: "transitionState", Alias: (*Alias)(&obj)})
}

repository: labd/commercetools-go-sdk

repo_name: labd/commercetools-go-sdk

branch_name: refs/heads/main


text:
require ${BPN}.inc

inherit native

DEPENDS += " \
    libuv-native \
"

do_install() {
    install -d ${D}${bindir}
    install -m 755 ${B}/mruby/build/host-debug/bin/mrbc ${D}${bindir}/mrbc-zest
}

repository: schnitzeltony/meta-musicians

repo_name: schnitzeltony/meta-musicians

gha_language: BitBake


text:
package main

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

func main() {
	if len(os.Args) < 2 { //if there's no program to run, don't run :)
		return
	}
	//can't think of a way to chunk up a bf program -- read it all in!
	file, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println(err)
		return
	}
	interpret(file)
}

repository: dgarrick/gofu

repo_name: dgarrick/gofu


text:
// SPDX-FileCopyrightText: 2020 SAP SE
// SPDX-FileCopyrightText: 2021 SAP SE
// SPDX-FileCopyrightText: 2022 SAP SE
// SPDX-FileCopyrightText: 2023 SAP SE
//
// SPDX-License-Identifier: Apache-2.0

package ase

import (
	"context"
	"database/sql/driver"
	"errors"
	"fmt"
	"io"

	"github.com/SAP/go-dblib/namepool"
	"github.com/SAP/go-dblib/tds"
)

var (
	cursorPool = namepool.Pool("cursor%d")
)

// Cursor is used to interact with a cursor on the ASE server.
type Cursor struct {
	conn *Conn

	poolName *namepool.Name
	hasArgs  bool

	cursorID int32
	name     string
	// currently unused
	// tableName string

	currentRow int32
	totalRows  int32

	stmt *Stmt

	paramFmt *tds.ParamFmtPackage
	rowFmt   *tds.RowFmtPackage

	// When a CursorRows is created from a Cursor CursorRows.Close is
	// executed before the Cursor.Close.
	// Since CursorRows.Close needs to call Cursor.Close to correctly
	// deallocate a cursor when used through database/sql a flag is
	// required for direct use to prevent duplicated deallocation
	// requests.
	closed bool
}

// NewCursor creates a new cursor.
//
// NewCursor is a wrapper around NewCursorWithValues that converts
// arguments into driver.NamedValues.
func (c *Conn) NewCursor(ctx context.Context, query string, args ...interface{}) (*Cursor, error) {
	valueArgs := make([]driver.NamedValue, len(args))
	for i, arg := range args {
		valueArgs[i] = driver.NamedValue{
			Ordinal: i + 1,
			Value:   arg,
		}
	}

	return c.NewCursorWithValues(ctx, query, valueArgs)
}

// NewCursorWithValues creates a new cursor.
func (c *Conn) NewCursorWithValues(ctx context.Context, query string, args []driver.NamedValue) (*Cursor, error) {
	cursor := new(Cursor)
	cursor.conn = c

	if err := cursor.allocateOnServer(ctx, query, args); err != nil {
		return nil, fmt.Errorf("go-ase: error allocating cursor on server: %w", err)
	}

	return cursor, nil
}

// allocateOnServer allocates the cursor on the TDS server.
func (cursor *Cursor) allocateOnServer(ctx context.Context, query string, args []driver.NamedValue) error {
	cursor.poolName = cursorPool.Acquire()
	cursor.hasArgs = len(args) > 0

	if cursor.hasArgs {
		// cursor has argument, prepare statement
		stmt, err := cursor.conn.NewStmt(ctx, cursor.poolName.String(), query, true)
		if err != nil {
			return fmt.Errorf("error creating stmt: %w", err)
		}
		// The cursor needs a reference to the statement to close it.
		// The statement needs a reference to the cursor to mark it as
		// already closed if the server decides to close the cursor
		// immediately instead of waiting on being instructed to do so.
		cursor.stmt = stmt
		stmt.cursor = cursor
	}

	// If a cursor has arguments a statement with the query must be
	// prepared using the query. The name of the new statement is used
	// as the 'query' to reference the statement.
	cursorQuery := query
	if cursor.hasArgs {
		cursorQuery = cursor.poolName.String()
	}

	// Declare cursor.
	declarePkg, err := tds.NewCurDeclarePackage(cursor.poolName.String(), cursorQuery,
		tds.TDS_CUR_DSTAT_UNUSED,
		tds.TDS_CUR_DOPT_UNUSED,
	)
	if err != nil {
		return fmt.Errorf("could not create CurDeclarePackage: %w", err)
	}
	if cursor.hasArgs {
		declarePkg.Options |= tds.TDS_CUR_DOPT_DYNAMIC
	}

	if err := cursor.conn.Channel.SendPackage(ctx, declarePkg); err != nil {
		return fmt.Errorf("error sending CurDeclarePackage: %w", err)
	}

	_, err = cursor.conn.Channel.NextPackageUntil(ctx, true, func(pkg tds.Package) (bool, error) {
		switch typed := pkg.(type) {
		case *tds.DynamicPackage:
			if typed.Type&tds.TDS_DYN_ACK != tds.TDS_DYN_ACK {
				return true, fmt.Errorf("received DynamicPackage without type TDS_DYN_ACK: %s", typed)
			}

			return false, nil
		case *tds.CurInfoPackage:
			if typed.Command != tds.TDS_CUR_CMD_INFORM {
				return true, fmt.Errorf("received %T with command %s instead of TDS_CUR_CMD_INFORM",
					typed, typed.Command)
			}

			cursor.cursorID = typed.CursorID
			cursor.name = typed.Name
			cursor.currentRow = typed.RowNum
			cursor.totalRows = typed.TotalRows
			return false, nil
		case *tds.RowFmtPackage:
			cursor.rowFmt = typed
			return false, nil
		case *tds.ParamFmtPackage:
			cursor.paramFmt = typed
			return false, nil
		case *tds.DonePackage:
			ok, err := handleDonePackage(typed)
			if err != nil {
				return true, err
			}
			return ok, nil
		default:
			return true, fmt.Errorf("unhandled package type %T: %s", typed, typed)
		}
	})
	if err != nil && !errors.Is(err, io.EOF) {
		return fmt.Errorf("error handling response to cursor creation: %w", err)
	}

	// Set how many rows should be sent by the TDS server per fetch.
	setFetchCount := &tds.CurInfoPackage{
		CursorID:  0,
		Name:      cursor.poolName.String(),
		Command:   tds.TDS_CUR_CMD_SETCURROWS,
		Status:    tds.TDS_CUR_ISTAT_ROWCNT,
		RowNum:    -1,
		TotalRows: 0,
		RowCount:  int32(cursor.conn.Info.CursorCacheRows),
	}

	if err := cursor.conn.Channel.SendPackage(ctx, setFetchCount); err != nil {
		return fmt.Errorf("error queueing CurInfoPackage to set fetch row count: %w", err)
	}

	_, err = cursor.conn.Channel.NextPackageUntil(ctx, true, func(pkg tds.Package) (bool, error) {
		switch typed := pkg.(type) {
		case *tds.DynamicPackage:
			if typed.Type&tds.TDS_DYN_ACK != tds.TDS_DYN_ACK {
				return true, fmt.Errorf("received DynamicPackage without type TDS_DYN_ACK: %s", typed)
			}

			return false, nil
		case *tds.CurInfoPackage:
			if typed.Command != tds.TDS_CUR_CMD_INFORM {
				return true, fmt.Errorf("received %T with command %s instead of TDS_CUR_CMD_INFORM",
					typed, typed.Command)
			}

			cursor.cursorID = typed.CursorID
			cursor.name = typed.Name
			cursor.currentRow = typed.RowNum
			cursor.totalRows = typed.TotalRows
			return false, nil
		case *tds.RowFmtPackage:
			cursor.rowFmt = typed
			return false, nil
		case *tds.ParamFmtPackage:
			cursor.paramFmt = typed
			return false, nil
		case *tds.DonePackage:
			ok, err := handleDonePackage(typed)
			if err != nil {
				return true, err
			}
			return ok, nil
		default:
			return true, fmt.Errorf("unhandled package type %T: %s", typed, typed)
		}
	})
	if err != nil && !errors.Is(err, io.EOF) {
		return fmt.Errorf("error handling response to cursor creation: %w", err)
	}

	// Open cursor to read results.
	openPkg := &tds.CurOpenPackage{
		CursorID: cursor.cursorID,
		Name:     cursor.name,
	}

	if cursor.hasArgs {
		openPkg.Status = tds.TDS_CUR_OSTAT_HASARGS
	}

	if err := cursor.conn.Channel.QueuePackage(ctx, openPkg); err != nil {
		return fmt.Errorf("error queueing and sending CurOpenPackage: %w", err)
	}

	if cursor.hasArgs {
		if err := cursor.stmt.sendArgs(ctx, args); err != nil {
			return fmt.Errorf("error queueing arguments: %w", err)
		}
	}

	if err := cursor.conn.Channel.SendRemainingPackets(ctx); err != nil {
		return fmt.Errorf("error sending packages: %w", err)
	}

	_, err = cursor.conn.Channel.NextPackageUntil(ctx, true, func(pkg tds.Package) (bool, error) {
		switch typed := pkg.(type) {
		case *tds.CurInfoPackage:
			if typed.Command != tds.TDS_CUR_CMD_INFORM {
				return true, fmt.Errorf("received %T with command %s instead of TDS_CUR_CMD_INFORM",
					typed, typed.Command)
			}

			// TDS sends the rowcount before opening the cursor
			if typed.Status&tds.TDS_CUR_ISTAT_ROWCNT == tds.TDS_CUR_ISTAT_ROWCNT {
				return false, nil
			}

			if typed.Status&tds.TDS_CUR_ISTAT_OPEN != tds.TDS_CUR_ISTAT_OPEN {
				return true, fmt.Errorf("received %T without status TDS_CUR_ISTAT_OPEN", typed)
			}

			return false, nil
		case *tds.RowFmtPackage:
			cursor.rowFmt = typed
			return false, nil
		case *tds.ControlPackage:
			// TODO
			return false, nil
		case *tds.OrderByPackage, *tds.OrderBy2Package:
			return false, nil
		case *tds.DonePackage:
			ok, err := handleDonePackage(typed)
			if err != nil {
				return true, fmt.Errorf("go-ase: %w", err)
			}
			return ok, nil
		default:
			return true, fmt.Errorf("unhandled package type %T: %v", typed, typed)
		}
	})
	if err != nil && !errors.Is(err, io.EOF) {
		return fmt.Errorf("error handling response to cursor opening: %w", err)
	}

	return nil
}

// Close closes the cursor.
func (cursor *Cursor) Close(ctx context.Context) error {
	defer cursorPool.Release(cursor.poolName)

	// If the cursor was already closed - e.g. because its result set
	// was exhausted and the CursorRows closed the cursor already, it
	// doesn't need to be closed again.
	// The statement will also be closed automatically by the server
	// once the result set is exhausted.
	if cursor.closed {
		return nil
	}

	if cursor.hasArgs {
		// cursor has an associated prepared statement
		if err := cursor.stmt.Close(); err != nil {
			return fmt.Errorf("go-ase: error closing stmt: %w", err)
		}

		// Return early if the cursor itself was automatically closed
		// after deallocating the associated statement.
		if cursor.closed {
			return nil
		}
	}

	closePkg := &tds.CurClosePackage{
		CursorID: cursor.cursorID,
		Name:     cursor.name,
		Options:  tds.TDS_CUR_COPT_DEALLOC,
	}

	if err := cursor.conn.Channel.SendPackage(ctx, closePkg); err != nil {
		return fmt.Errorf("go-ase: error sending CurClosePackage: %w", err)
	}

	// The deallocation request has been sent, mark cursor as closed.
	cursor.closed = true

	// TDS sometimes first sends an empty TDS_DONE_COUNT and
	// a TDS_DONE_FINAL, before sending the closing/deallocating
	// TDS_CUR_CMD_INFORM - sometimes though it directly sends the
	// closing/deallocating TDS_CUR_CMD_INFORM.
	// To handle this rxCurDealloc is set to true in the first stream
	// to only read the second stream if the cursor deallocation was not
	// confirmed by TDS.
	rxCurDealloc, err := cursor.closeReadResponse(ctx)
	if err != nil && !errors.Is(err, io.EOF) {
		return fmt.Errorf("go-ase: cursor deletion finished with error: %w", err)
	}

	if rxCurDealloc {
		return nil
	}

	if _, err := cursor.closeReadResponse(ctx); err != nil && !errors.Is(err, io.EOF) {
		return fmt.Errorf("go-ase: cursor deletion finished with error: %w", err)
	}

	return nil
}

func (cursor *Cursor) closeReadResponse(ctx context.Context) (bool, error) {
	rxCurDealloc := false

	_, err := cursor.conn.Channel.NextPackageUntil(ctx, true, func(pkg tds.Package) (bool, error) {
		switch typed := pkg.(type) {
		case *tds.CurInfoPackage:
			if typed.Command != tds.TDS_CUR_CMD_INFORM {
				return true, fmt.Errorf("go-ase: received %T with command %s instead of TDS_CUR_CMD_INFORM",
					typed, typed.Command)
			}

			if typed.Status&tds.TDS_CUR_ISTAT_CLOSED != tds.TDS_CUR_ISTAT_CLOSED &&
				typed.Status&tds.TDS_CUR_ISTAT_DEALLOC != tds.TDS_CUR_ISTAT_DEALLOC {
				return true, fmt.Errorf("go-ase: received %T without status TDS_CUR_ISTAT_CLOSED or TDS_CUR_ISTAT_DEALLOC",
					typed)
			}

			if typed.Status&tds.TDS_CUR_ISTAT_DEALLOC == tds.TDS_CUR_ISTAT_DEALLOC {
				rxCurDealloc = true
			}

			return false, nil
		case *tds.DonePackage:
			// TDS sends an empty TDS_DONE_COUNT before TDS_DONE_FINAL
			if typed.Status == tds.TDS_DONE_COUNT {
				return false, nil
			}

			ok, err := handleDonePackage(typed)
			if err != nil {
				return true, err
			}
			return ok, nil
		default:
			return true, fmt.Errorf("go-ase: unhandled package type %T: %v", typed, typed)
		}
	})
	if err != nil && !errors.Is(err, io.EOF) {
		return rxCurDealloc, err
	}

	return rxCurDealloc, nil
}

// CursorID returns the ID assigned to the cursor by ASE.
func (cursor Cursor) CursorID() int {
	return int(cursor.cursorID)
}

// Fetch returns CursorRows to iterate over the rows selected by
// a cursor.
func (cursor *Cursor) Fetch(ctx context.Context) (*CursorRows, error) {
	return cursor.NewCursorRows()
}

repository: SAP/go-ase

repo_name: SAP/go-ase


text:
#include <cstdint>
#include <netp/http/url_parser.hpp>

namespace netp { namespace http {
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif

#ifndef ARRAY_SIZE
# define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#endif

#ifndef BIT_AT
# define BIT_AT(a, i)                                                \
  (!!((unsigned int) (a)[(unsigned int) (i) >> 3] &                  \
   (1 << ((unsigned int) (i) & 7))))
#endif

#ifndef ELEM_AT
# define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v))
#endif

    /* Macros for character classes; depends on strict-mode  */
#define CR                  '\r'
#define LF                  '\n'
#define LOWER(c)            (unsigned char)(c | 0x20)
#define IS_ALPHA(c)         (LOWER(c) >= 'a' && LOWER(c) <= 'z')
#define IS_NUM(c)           ((c) >= '0' && (c) <= '9')
#define IS_ALPHANUM(c)      (IS_ALPHA(c) || IS_NUM(c))
#define IS_HEX(c)           (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'))
#define IS_MARK(c)          ((c) == '-' || (c) == '_' || (c) == '.' || \
  (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
  (c) == ')')
#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \
  (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
  (c) == '$' || (c) == ',')

#define STRICT_TOKEN(c)     ((c == ' ') ? 0 : tokens[(unsigned char)c])

#if HTTP_PARSER_STRICT
#define TOKEN(c)            STRICT_TOKEN(c)
#define IS_URL_CHAR(c)      (BIT_AT(normal_url_char, (unsigned char)c))
#define IS_HOST_CHAR(c)     (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
#else
#define TOKEN(c)            tokens[(unsigned char)c]
#define IS_URL_CHAR(c)                                                         \
  (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80))
#define IS_HOST_CHAR(c)                                                        \
  (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
#endif

/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
 * faster
 */
#ifndef HTTP_PARSER_STRICT
# define HTTP_PARSER_STRICT 1
#endif

#if HTTP_PARSER_STRICT
# define T(v) 0
#else
# define T(v) v
#endif

    static const uint8_t normal_url_char[32] = {
        /*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
         0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
         /*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
         0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0,
         /*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
         0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
         /*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
         0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
         /*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
         0 | 2 | 4 | 0 | 16 | 32 | 64 | 128,
         /*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 0,
         /*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
         /* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
         1 | 2 | 4 | 8 | 16 | 32 | 64 | 0,
    };

#undef T

    enum state
    {
        s_dead = 1 /* important that this is > 0 */

        , s_start_req_or_res
        , s_res_or_resp_H
        , s_start_res
        , s_res_H
        , s_res_HT
        , s_res_HTT
        , s_res_HTTP
        , s_res_http_major
        , s_res_http_dot
        , s_res_http_minor
        , s_res_http_end
        , s_res_first_status_code
        , s_res_status_code
        , s_res_status_start
        , s_res_status
        , s_res_line_almost_done

        , s_start_req

        , s_req_method
        , s_req_spaces_before_url
        , s_req_schema
        , s_req_schema_slash
        , s_req_schema_slash_slash
        , s_req_server_start
        , s_req_server
        , s_req_server_with_at
        , s_req_path
        , s_req_query_string_start
        , s_req_query_string
        , s_req_fragment_start
        , s_req_fragment
        , s_req_http_start
        , s_req_http_H
        , s_req_http_HT
        , s_req_http_HTT
        , s_req_http_HTTP
        , s_req_http_I
        , s_req_http_IC
        , s_req_http_major
        , s_req_http_dot
        , s_req_http_minor
        , s_req_http_end
        , s_req_line_almost_done

        , s_header_field_start
        , s_header_field
        , s_header_value_discard_ws
        , s_header_value_discard_ws_almost_done
        , s_header_value_discard_lws
        , s_header_value_start
        , s_header_value
        , s_header_value_lws

        , s_header_almost_done

        , s_chunk_size_start
        , s_chunk_size
        , s_chunk_parameters
        , s_chunk_size_almost_done

        , s_headers_almost_done
        , s_headers_done

        /* Important: 's_headers_done' must be the last 'header' state. All
         * states beyond this must be 'body' states. It is used for overflow
         * checking. See the PARSING_HEADER() macro.
         */

        , s_chunk_data
        , s_chunk_data_almost_done
        , s_chunk_data_done

        , s_body_identity
        , s_body_identity_eof

        , s_message_done
    };

    enum http_host_state
    {
        s_http_host_dead = 1
        , s_http_userinfo_start
        , s_http_userinfo
        , s_http_host_start
        , s_http_host_v6_start
        , s_http_host
        , s_http_host_v6
        , s_http_host_v6_end
        , s_http_host_v6_zone_start
        , s_http_host_v6_zone
        , s_http_host_port_start
        , s_http_host_port
    };

    /* Our URL parser.
 *
 * This is designed to be shared by http_parser_execute() for URL validation,
 * hence it has a state transition + byte-for-byte interface. In addition, it
 * is meant to be embedded in http_parser_parse_url(), which does the dirty
 * work of turning state transitions URL components for its API.
 *
 * This function should only be invoked with non-space characters. It is
 * assumed that the caller cares about (and can detect) the transition between
 * URL and non-URL states by looking for these.
 */
    static enum state
        parse_url_char(enum state s, const char ch)
    {
        if (ch == ' ' || ch == '\r' || ch == '\n') {
            return s_dead;
        }

#if HTTP_PARSER_STRICT
        if (ch == '\t' || ch == '\f') {
            return s_dead;
        }
#endif

        switch (s) {
        case s_req_spaces_before_url:
            /* Proxied requests are followed by scheme of an absolute URI (alpha).
             * All methods except CONNECT are followed by '/' or '*'.
             */

            if (ch == '/' || ch == '*') {
                return s_req_path;
            }

            if (IS_ALPHA(ch)) {
                return s_req_schema;
            }

            break;

        case s_req_schema:
            if (IS_ALPHA(ch)) {
                return s;
            }

            if (ch == ':') {
                return s_req_schema_slash;
            }

            break;

        case s_req_schema_slash:
            if (ch == '/') {
                return s_req_schema_slash_slash;
            }

            break;

        case s_req_schema_slash_slash:
            if (ch == '/') {
                return s_req_server_start;
            }

            break;

        case s_req_server_with_at:
            if (ch == '@') {
                return s_dead;
            }

            /* fall through */
        case s_req_server_start:
        case s_req_server:
            if (ch == '/') {
                return s_req_path;
            }

            if (ch == '?') {
                return s_req_query_string_start;
            }

            if (ch == '@') {
                return s_req_server_with_at;
            }

            if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
                return s_req_server;
            }

            break;

        case s_req_path:
            if (IS_URL_CHAR(ch)) {
                return s;
            }

            switch (ch) {
            case '?':
                return s_req_query_string_start;

            case '#':
                return s_req_fragment_start;
            }

            break;

        case s_req_query_string_start:
        case s_req_query_string:
            if (IS_URL_CHAR(ch)) {
                return s_req_query_string;
            }

            switch (ch) {
            case '?':
                /* allow extra '?' in query string */
                return s_req_query_string;

            case '#':
                return s_req_fragment_start;
            }

            break;

        case s_req_fragment_start:
            if (IS_URL_CHAR(ch)) {
                return s_req_fragment;
            }

            switch (ch) {
            case '?':
                return s_req_fragment;

            case '#':
                return s;
            }

            break;

        case s_req_fragment:
            if (IS_URL_CHAR(ch)) {
                return s;
            }

            switch (ch) {
            case '?':
            case '#':
                return s;
            }

            break;

        default:
            break;
        }

        /* We should never fall out of the switch above unless there's an error */
        return s_dead;
    }

    static enum http_host_state
        http_parse_host_char(enum http_host_state s, const char ch) {
        switch (s) {
        case s_http_userinfo:
        case s_http_userinfo_start:
            if (ch == '@') {
                return s_http_host_start;
            }

            if (IS_USERINFO_CHAR(ch)) {
                return s_http_userinfo;
            }
            break;

        case s_http_host_start:
            if (ch == '[') {
                return s_http_host_v6_start;
            }

            if (IS_HOST_CHAR(ch)) {
                return s_http_host;
            }

            break;

        case s_http_host:
            if (IS_HOST_CHAR(ch)) {
                return s_http_host;
            }

            /* fall through */
        case s_http_host_v6_end:
            if (ch == ':') {
                return s_http_host_port_start;
            }

            break;

        case s_http_host_v6:
            if (ch == ']') {
                return s_http_host_v6_end;
            }

            /* fall through */
        case s_http_host_v6_start:
            if (IS_HEX(ch) || ch == ':' || ch == '.') {
                return s_http_host_v6;
            }

            if (s == s_http_host_v6 && ch == '%') {
                return s_http_host_v6_zone_start;
            }
            break;

        case s_http_host_v6_zone:
            if (ch == ']') {
                return s_http_host_v6_end;
            }

            /* fall through */
        case s_http_host_v6_zone_start:
            /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */
            if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' ||
                ch == '~') {
                return s_http_host_v6_zone;
            }
            break;

        case s_http_host_port:
        case s_http_host_port_start:
            if (IS_NUM(ch)) {
                return s_http_host_port;
            }

            break;

        default:
            break;
        }
        return s_http_host_dead;
    }

    static int
        http_parse_host(const char* buf, struct http_parser_url* u, int found_at) {
        enum http_host_state s;

        const char* p;
        size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;

        assert(u->field_set & (1 << UF_HOST));

        u->field_data[UF_HOST].len = 0;

        s = found_at ? s_http_userinfo_start : s_http_host_start;

        for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) {
            enum http_host_state new_s = http_parse_host_char(s, *p);

            if (new_s == s_http_host_dead) {
                return 1;
            }

            switch (new_s) {
            case s_http_host:
                if (s != s_http_host) {
                    u->field_data[UF_HOST].off = (uint16_t)(p - buf);
                }
                u->field_data[UF_HOST].len++;
                break;

            case s_http_host_v6:
                if (s != s_http_host_v6) {
                    u->field_data[UF_HOST].off = (uint16_t)(p - buf);
                }
                u->field_data[UF_HOST].len++;
                break;

            case s_http_host_v6_zone_start:
            case s_http_host_v6_zone:
                u->field_data[UF_HOST].len++;
                break;

            case s_http_host_port:
                if (s != s_http_host_port) {
                    u->field_data[UF_PORT].off = (uint16_t)(p - buf);
                    u->field_data[UF_PORT].len = 0;
                    u->field_set |= (1 << UF_PORT);
                }
                u->field_data[UF_PORT].len++;
                break;

            case s_http_userinfo:
                if (s != s_http_userinfo) {
                    u->field_data[UF_USERINFO].off = (uint16_t)(p - buf);
                    u->field_data[UF_USERINFO].len = 0;
                    u->field_set |= (1 << UF_USERINFO);
                }
                u->field_data[UF_USERINFO].len++;
                break;

            default:
                break;
            }
            s = new_s;
        }

        /* Make sure we don't end somewhere unexpected */
        switch (s) {
        case s_http_host_start:
        case s_http_host_v6_start:
        case s_http_host_v6:
        case s_http_host_v6_zone_start:
        case s_http_host_v6_zone:
        case s_http_host_port_start:
        case s_http_userinfo:
        case s_http_userinfo_start:
            return 1;
        default:
            break;
        }

        return 0;
    }

    void http_parser_url_init(struct http_parser_url* u) {
        std::memset(u, 0, sizeof(*u));
    }

    int
        http_parser_parse_url(const char* buf, size_t buflen, int is_connect,
            struct http_parser_url* u)
    {
        enum state s;
        const char* p;
        enum http_parser_url_fields uf, old_uf;
        int found_at = 0;

        if (buflen == 0) {
            return 1;
        }

        u->port = u->field_set = 0;
        s = is_connect ? s_req_server_start : s_req_spaces_before_url;
        old_uf = UF_MAX;

        for (p = buf; p < buf + buflen; p++) {
            s = parse_url_char(s, *p);

            /* Figure out the next field that we're operating on */
            switch (s) {
            case s_dead:
                return 1;

                /* Skip delimeters */
            case s_req_schema_slash:
            case s_req_schema_slash_slash:
            case s_req_server_start:
            case s_req_query_string_start:
            case s_req_fragment_start:
                continue;

            case s_req_schema:
                uf = UF_SCHEMA;
                break;

            case s_req_server_with_at:
                found_at = 1;

                /* fall through */
            case s_req_server:
                uf = UF_HOST;
                break;

            case s_req_path:
                uf = UF_PATH;
                break;

            case s_req_query_string:
                uf = UF_QUERY;
                break;

            case s_req_fragment:
                uf = UF_FRAGMENT;
                break;

            default:
                NETP_ASSERT(!"Unexpected state");
                return 1;
            }

            /* Nothing's changed; soldier on */
            if (uf == old_uf) {
                u->field_data[uf].len++;
                continue;
            }

            u->field_data[uf].off = (uint16_t)(p - buf);
            u->field_data[uf].len = 1;

            u->field_set |= (1 << uf);
            old_uf = uf;
        }

        /* host must be present if there is a schema */
        /* parsing http:///toto will fail */
        if ((u->field_set & (1 << UF_SCHEMA)) &&
            (u->field_set & (1 << UF_HOST)) == 0) {
            return 1;
        }

        if (u->field_set & (1 << UF_HOST)) {
            if (http_parse_host(buf, u, found_at) != 0) {
                return 1;
            }
        }

        /* CONNECT requests can only contain "hostname:port" */
        if (is_connect && u->field_set != ((1 << UF_HOST) | (1 << UF_PORT))) {
            return 1;
        }

        if (u->field_set & (1 << UF_PORT)) {
            uint16_t off;
            uint16_t len;
            const char* p;
            const char* end;
            unsigned long v;

            off = u->field_data[UF_PORT].off;
            len = u->field_data[UF_PORT].len;
            end = buf + off + len;

            /* NOTE: The characters are already validated and are in the [0-9] range */
            NETP_ASSERT((size_t)(off + len) <= buflen && "Port number overflow");
            v = 0;
            for (p = buf + off; p < end; p++) {
                v *= 10;
                v += *p - '0';

                /* Ports have a max value of 2^16 */
                if (v > 0xffff) {
                    return 1;
                }
            }

            u->port = (uint16_t)v;
        }

        return 0;
    }

}}

extension: cpp


text:
inherit noto-fonts
inherit noto-cjk
inherit noto-cjk-styles

SRC_URI = "${NOTO_SRC_URI_PREFIX}/NotoSerifCJKsc-hinted.zip"
SRC_URI[sha256sum] = "91fd5c3d9465458fa6cf5bda3ff5ae6f3bf0bfd62110bd05ce5db29284f8e3bd"

repository: ssfivy/meta-noto

repo_name: ssfivy/meta-noto


text:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

string zad4_1()
{
    string line;
    vector<string> content;

    fstream file("../dane/liczby.txt");

    // wczytywanie danych z pliku
    if (file.is_open())
    {
        while (getline(file, line))
            content.push_back(line);
    }
    file.close();

    // liczenie linii, ktore maja wiecej zer niz jedynek
    int howManyLines = 0, zeros = 0, ones = 0;

    for (int i = 0; i < content.size(); i++)
    {
        for (int j = 0; j < content[i].size(); j++)
        {
            if (content[i][j] == '0')
                zeros++;
            else
                ones++;
        }

        if (zeros > ones)
            howManyLines++;

        zeros = 0;
        ones = 0;
    }

    return "4.1. Liczba linii, w ktorych jest wiecej zer niz jedynek: " + to_string(howManyLines);
}

repository: shilangyu/zadania-maturalne

repo_name: shilangyu/zadania-maturalne


text:
SUMMARY = "NSS module which can read user information from files in an alternative location"
LICENSE = "LGPL-2.1-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=fb1949d8d807e528c1673da700aff41f"

# Use upstream used and maintained by Flatcar
SRC_URI = "git://github.com/kinvolk/nss-altfiles.git;protocol=https;branch=master"

PV = "2.23.0+git${SRCPV}"
SRCREV = "9078c543ba7d2bc5011737675b3dddb882673ce7"

S = "${WORKDIR}/git"

inherit autotools-brokensep

NSS_ALT_TYPES ?= "pwd,grp,spwd,sgrp"

EXTRA_OECONF = " \
    --datadir=${libdir} \
    --prefix=${libdir} \
    --with-types=${NSS_ALT_TYPES} \
"

repository: foundriesio/meta-lmp

repo_name: foundriesio/meta-lmp


text:
package local

import (
	"errors"
	"fmt"
	"math"
	"net"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"

	"common"
	"github.com/RouterScript/ProxyClient"
	"outbound/ss"
	"outbound/ss/obfs"
	"outbound/ss/protocol"
	"outbound/ss/ssr"
)

var (
	ERR_NOT_FILTERED = errors.New("server is not filtered out by firewall")
)

type BackendInfo struct {
	id                 string
	address            string
	protocolType       string
	username           string      // auth for http/https/socks
	password           string      // auth for http/https/socks
	insecureSkipVerify bool        // https only
	domain             string      // https only
	obfs               string      // shadowsocksr only
	obfsParam          string      // shadowsocksr only
	obfsData           interface{} // shadowsocksr only
	protocol           string      // shadowsocksr only
	protocolParam      string      // shadowsocksr only
	protocolData       interface{} // shadowsocksr only
	cipher             *ss.Cipher  // shadowsocks/shadowsocksr only
	tcpFastOpen        bool        // shadowsocks/shadowsocksr only
	timeout            int
	restrict           bool
	local              bool
	firewalled         bool
	ipv6               bool
	lastCheckTimePoint time.Time
	ips                []net.IP
}

func (bi *BackendInfo) testLatency(rawaddr []byte, addr string, wg *sync.WaitGroup) {
	defer func() {
		wg.Done()
	}()
	startTime := time.Now()
	remote, err := bi.connect(rawaddr, addr)
	if err == nil {
		if remote != nil {
			defer remote.Close()
		}

		bi.firewalled = false
	}
	bi.lastCheckTimePoint = time.Now()
	endTime := time.Now()
	if stat, ok := Statistics.Get(bi); ok {
		if err != nil {
			stat.IncreaseFailedCount()
			if stat.GetFailedCount() > 10 {
				stat.SetLatency(math.MaxInt64)
			}
		} else {
			stat.SetLatency(endTime.Sub(startTime).Nanoseconds())
			stat.ClearFailedCount()
		}
	}
}

func (bi *BackendInfo) pipe(local net.Conn, remote net.Conn, buffer *common.Buffer) (err error, inboundSideError bool) {
	sig := make(chan bool)
	result := make(chan error)
	stat, ok := Statistics.Get(bi)
	if !ok || stat == nil {
		return errors.New("invalid statistics"), false
	}

	go func() {
		result <- PipeInboundToOutbound(local,
			remote,
			time.Duration(config.Generals.InBoundTimeout)*time.Second,
			time.Duration(bi.timeout)*time.Second,
			stat,
			sig,
			&buffer)
	}()
	err = PipeOutboundToInbound(remote,
		local,
		time.Duration(bi.timeout)*time.Second,
		time.Duration(config.Generals.InBoundTimeout)*time.Second,
		stat,
		sig)
	if err == ERR_WRITE {
		inboundSideError = true
	}
	if err == ERR_READ || err == ERR_NOSIG || err == ERR_SIGFALSE {
		Statistics.StatisticMap[bi].IncreaseFailedCount()
		common.Errorf("piping outbound to inbound error: %v, at %v\n", err, bi)
		go func() {
			// clear the channel
			<-result
		}()
		return
	}

	if neterr, ok := err.(net.Error); ok {
		common.Error("piping outbound to inbound unknown error: ", neterr)
	}

	err = <-result
	if err == ERR_READ || err == ERR_WRITE || err == ERR_NOSIG || err == ERR_SIGFALSE {
		Statistics.StatisticMap[bi].IncreaseFailedCount()
		common.Errorf("piping inbound to outbound error: %v, at %v\n", err, bi)
		if err == ERR_READ {
			inboundSideError = true
		}
		return
	}

	if neterr, ok := err.(net.Error); ok {
		common.Error("piping inbound to outbound unknown error: ", neterr)
	}

	return nil, false
}

func (bi *BackendInfo) connectToProxy(u string, addr string) (remote net.Conn, err error) {
	dialer := net.Dial
	if bi.timeout != 0 {
		dialer = proxyclient.DialWithTimeout(time.Duration(bi.timeout) * time.Second)
	}
	p, err := proxyclient.NewProxyClientWithDial(u, dialer)

	if err != nil {
		common.Error("creating proxy client failed", u, err)
		return
	}

	remote, err = p("tcp", addr)
	if err != nil {
		common.Error("connecting to target failed.", u, addr, err)
	}
	return
}

func (bi *BackendInfo) connect(rawaddr []byte, addr string) (remote net.Conn, err error) {
	switch bi.protocolType {
	case "https", "socks5+tls":
		u := url.URL{
			Scheme:bi.protocolType,
			User:  url.UserPassword(bi.username, bi.password),
			Host:  bi.address,
		}
		v := u.Query()
		if bi.insecureSkipVerify {
			v.Set("tls-insecure-skip-verify", "true")
		}
		if len(bi.domain) > 0 {
			v.Set("tls-domain", bi.domain)
		}
		if len(v) > 0 {
			u.RawQuery = v.Encode()
		}
		return bi.connectToProxy(u.String(), addr)
	case "http", "socks4", "socks4a", "socks5":
		u := url.URL{
			Scheme:bi.protocolType,
			User:  url.UserPassword(bi.username, bi.password),
			Host:  bi.address,
		}
		return bi.connectToProxy(u.String(), addr)
	case "shadowsocks", "ss":
		if bi.firewalled == true && time.Now().Sub(bi.lastCheckTimePoint) < 1*time.Hour {
			err = ERR_NOT_FILTERED
			common.Warningf("server %s is not filtered out by firewall.\n", bi.address)
			return
		}

		var ssconn *ss.SSTCPConn
		priorityInterfaceAddress := config.Generals.PriorityInterfaceAddress
		if !config.Generals.PriorityInterfaceEnabled {
			priorityInterfaceAddress = ""
		}

		if ssconn, err = ss.Dial(bi.address, bi.cipher.Copy(), priorityInterfaceAddress); err != nil {
			return nil, err
		}

		if ssconn.Conn, err = ss.ProtectSocket(ssconn.Conn); err != nil {
			return nil, err
		}

		// should initialize obfs/protocol now
		rs := strings.Split(ssconn.RemoteAddr().String(), ":")
		port, _ := strconv.Atoi(rs[1])

		ssconn.IObfs = obfs.NewObfs(bi.obfs)
		obfsServerInfo := &ssr.ServerInfoForObfs{
			Host:       rs[0],
			Port:       uint16(port),
			TcpMss:     1460,
			Param:      bi.obfsParam,
		}
		ssconn.IObfs.SetServerInfo(obfsServerInfo)
		if bi.obfsData == nil {
			bi.obfsData = ssconn.IObfs.GetData()
		}
		ssconn.IObfs.SetData(bi.obfsData)

		ssconn.IProtocol = protocol.NewProtocol(bi.protocol)
		protocolServerInfo := &ssr.ServerInfoForObfs{
			Host:       rs[0],
			Port:       uint16(port),
			TcpMss:     1460,
			Param:      bi.protocolParam,
		}
		ssconn.IProtocol.SetServerInfo(protocolServerInfo)
		if bi.protocolData == nil {
			bi.protocolData = ssconn.IProtocol.GetData()
		}
		ssconn.IProtocol.SetData(bi.protocolData)

		if _, err = ssconn.Write(rawaddr); err != nil {
			ssconn.Close()
			return nil, err
		}
		remote = ssconn
	default:
		return nil, fmt.Errorf("Unknown backend protocol type: %s", bi.protocolType)
	}
	return
}

type BackendsInformation []*BackendInfo

func (slice BackendsInformation) Len() int {
	return len(slice)
}

func (slice BackendsInformation) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

type ByLastSecondBps struct{ BackendsInformation }

func (slice ByLastSecondBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetLastSecondBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetLastSecondBps()
}

type ByLastMinuteBps struct{ BackendsInformation }

func (slice ByLastMinuteBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetLastMinuteBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetLastMinuteBps()
}

type ByLastTenMinutesBps struct{ BackendsInformation }

func (slice ByLastTenMinutesBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetLastTenMinutesBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetLastTenMinutesBps()
}

type ByLastHourBps struct{ BackendsInformation }

func (slice ByLastHourBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetLastHourBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetLastHourBps()
}

type ByHighestLastSecondBps struct{ BackendsInformation }

func (slice ByHighestLastSecondBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetHighestLastSecondBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetHighestLastSecondBps()
}

type ByHighestLastMinuteBps struct{ BackendsInformation }

func (slice ByHighestLastMinuteBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetHighestLastMinuteBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetHighestLastMinuteBps()
}

type ByHighestLastTenMinutesBps struct{ BackendsInformation }

func (slice ByHighestLastTenMinutesBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetHighestLastTenMinutesBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetHighestLastTenMinutesBps()
}

type ByHighestLastHourBps struct{ BackendsInformation }

func (slice ByHighestLastHourBps) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetHighestLastHourBps() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetHighestLastHourBps()
}

type ByLatency struct{ BackendsInformation }

func (slice ByLatency) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	if Statistics.StatisticMap[slice.BackendsInformation[i]].GetLatency() == 0 {
		return false
	}
	if Statistics.StatisticMap[slice.BackendsInformation[j]].GetLatency() == 0 {
		return true
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetLatency() < Statistics.StatisticMap[slice.BackendsInformation[j]].GetLatency()
}

type ByFailedCount struct{ BackendsInformation }

func (slice ByFailedCount) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetFailedCount() < Statistics.StatisticMap[slice.BackendsInformation[j]].GetFailedCount()
}

type ByTotalUpload struct{ BackendsInformation }

func (slice ByTotalUpload) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetTotalUploaded() > Statistics.StatisticMap[slice.BackendsInformation[j]].GetTotalUploaded()
}

type ByTotalDownload struct{ BackendsInformation }

func (slice ByTotalDownload) Less(i, j int) bool {
	Statistics.RLock()
	defer Statistics.RUnlock()
	if bi, ok := Statistics.StatisticMap[slice.BackendsInformation[i]]; !ok || bi == nil {
		return false
	}
	if sj, ok := Statistics.StatisticMap[slice.BackendsInformation[j]]; !ok || sj == nil {
		return false
	}
	return Statistics.StatisticMap[slice.BackendsInformation[i]].GetTotalDownload() < Statistics.StatisticMap[slice.BackendsInformation[j]].GetTotalDownload()
}

type BackendsInformationWrapper struct {
	sync.RWMutex
	BackendsInformation
}

func NewBackendsInformationWrapper() *BackendsInformationWrapper {
	biw := &BackendsInformationWrapper{}
	biw.BackendsInformation = make(BackendsInformation, 0)
	return biw
}

func (biw *BackendsInformationWrapper) Append(bi *BackendInfo) {
	biw.Lock()
	defer biw.Unlock()
	biw.BackendsInformation = append(biw.BackendsInformation, bi)
}

func (biw *BackendsInformationWrapper) Remove(i int) {
	biw.Lock()
	defer biw.Unlock()
	biw.BackendsInformation = append(biw.BackendsInformation[:i], biw.BackendsInformation[i + 1:]...)
}

func (biw *BackendsInformationWrapper) Get(i int) *BackendInfo {
	biw.RLock()
	defer biw.RUnlock()
	if i >= len(biw.BackendsInformation) {
		return nil
	}
	return biw.BackendsInformation[i]
}

func (biw *BackendsInformationWrapper) Len() int {
	biw.RLock()
	defer biw.RUnlock()
	return len(biw.BackendsInformation)
}

repository: cutemanworking/avege

repo_name: cutemanworking/avege


text:
// BoundingBoxTree.cpp

#include "BoundingBoxTree.h"
#include "LineSegment.h"

using namespace _3DMath;

//-----------------------------------------------------------------------------------------------------------
//                                           BoundingBoxTree
//-----------------------------------------------------------------------------------------------------------

BoundingBoxTree::BoundingBoxTree( void )
{
	rootNode = nullptr;
}

/*virtual*/ BoundingBoxTree::~BoundingBoxTree( void )
{
	delete rootNode;
}

void BoundingBoxTree::GenerateNodes( const AxisAlignedBox& rootBox, int depth )
{
	if( rootNode )
		delete rootNode;

	rootNode = CreateNode( rootBox, depth );
}

BoundingBoxTree::Node* BoundingBoxTree::CreateNode( const AxisAlignedBox& boundingBox, int depth )
{
	Node* node = nullptr;

	if( depth == 1 )
		node = new LeafNode();
	else
	{
		BranchNode* branchNode = new BranchNode();

		node = branchNode;

		AxisAlignedBox boxA, boxB;
		boundingBox.SplitInTwo( boxA, boxB, &branchNode->plane );

		branchNode->backNode = CreateNode( boxA, depth - 1 );
		branchNode->frontNode = CreateNode( boxB, depth - 1 );
	}

	node->boundingBox = boundingBox;

	return node;
}

bool BoundingBoxTree::InsertTriangle( const Triangle& triangle )
{
	if( !rootNode )
		return false;

	return rootNode->InsertTriangle( triangle );
}

bool BoundingBoxTree::InsertTriangleList( const TriangleList& triangleList, const Vector* normalFilter /*= nullptr*/, double angleFilter /*= 0.0*/ )
{
	for( TriangleList::const_iterator iter = triangleList.begin(); iter != triangleList.cend(); iter++ )
	{
		const Triangle& triangle = *iter;

		if( normalFilter )
		{
			Vector normal;
			triangle.GetNormal( normal );

			double angle = normal.AngleBetween( *normalFilter );
			if( angle >= angleFilter )
				continue;
		}

		if( !InsertTriangle( triangle ) )
			return false;
	}

	return true;
}

bool BoundingBoxTree::FindIntersection( const LineSegment& lineSegment, const Triangle*& intersectedTriangle, Vector& intersectionPoint ) const
{
	if( !rootNode )
		return false;

	return rootNode->FindIntersection( lineSegment, intersectedTriangle, intersectionPoint );
}

bool BoundingBoxTree::FindNearestTriangle( const Vector& point, const Triangle*& nearestTriangle, double maxDistance ) const
{
	if( !rootNode )
		return false;

	return rootNode->FindNearestTriangle( point, nearestTriangle, maxDistance );
}

//-----------------------------------------------------------------------------------------------------------
//                                                   Node
//-----------------------------------------------------------------------------------------------------------

BoundingBoxTree::Node::Node( void )
{
}

/*virtual*/ BoundingBoxTree::Node::~Node( void )
{
}

//-----------------------------------------------------------------------------------------------------------
//                                                   BranchNode
//-----------------------------------------------------------------------------------------------------------

BoundingBoxTree::BranchNode::BranchNode( void )
{
	frontNode = nullptr;
	backNode = nullptr;
}

/*virtual*/ BoundingBoxTree::BranchNode::~BranchNode( void )
{
	delete frontNode;
	delete backNode;
}

/*virtual*/ bool BoundingBoxTree::BranchNode::InsertTriangle( const Triangle& triangle )
{
	if( !boundingBox.ContainsTriangle( triangle ) )
		return false;

	if( !backNode->InsertTriangle( triangle ) && !frontNode->InsertTriangle( triangle ) )
	{
		// At the expense of duplicating triangles in the tree, we might consider inserting
		// down multiple branches.  Forgoing the split, we may actually net fewer triangles
		// per leaf node, and therefore fewer checks.

		TriangleList frontList, backList;
		if( !plane.SplitTriangle( triangle, frontList, backList ) )
			return false;

		for( TriangleList::iterator iter = backList.begin(); iter != backList.end(); iter++ )
			if( !backNode->InsertTriangle( *iter ) )
				return false;

		for( TriangleList::iterator iter = frontList.begin(); iter != frontList.end(); iter++ )
			if( !frontNode->InsertTriangle( *iter ) )
				return false;
	}

	return true;
}

/*virtual*/ bool BoundingBoxTree::BranchNode::FindIntersection( const LineSegment& lineSegment, const Triangle*& intersectedTriangle, Vector& intersectionPoint ) const
{
	if( boundingBox.IntersectsWithLineSegment( lineSegment ) )
	{
		if( backNode->FindIntersection( lineSegment, intersectedTriangle, intersectionPoint ) )
			return true;

		if( frontNode->FindIntersection( lineSegment, intersectedTriangle, intersectionPoint ) )
			return true;
	}

	return false;
}

/*virtual*/ bool BoundingBoxTree::BranchNode::FindNearestTriangle( const Vector& point, const Triangle*& nearestTriangle, double maxDistance ) const
{
	if( boundingBox.ContainsPoint( point ) )
	{
		if( backNode->FindNearestTriangle( point, nearestTriangle, maxDistance ) )
			return true;

		if( frontNode->FindNearestTriangle( point, nearestTriangle, maxDistance ) )
			return true;
	}

	return false;
}

//-----------------------------------------------------------------------------------------------------------
//                                                    LeafNode
//-----------------------------------------------------------------------------------------------------------

BoundingBoxTree::LeafNode::LeafNode( void )
{
	triangleList = new TriangleList();
}

/*virtual*/ BoundingBoxTree::LeafNode::~LeafNode( void )
{
	delete triangleList;
}

/*virtual*/ bool BoundingBoxTree::LeafNode::InsertTriangle( const Triangle& triangle )
{
	if( boundingBox.ContainsTriangle( triangle ) )
	{
		triangleList->push_back( triangle );
		return true;
	}

	return false;
}

/*virtual*/ bool BoundingBoxTree::LeafNode::FindIntersection( const LineSegment& lineSegment, const Triangle*& intersectedTriangle, Vector& intersectionPoint ) const
{
	intersectedTriangle = nullptr;
	double smallestLambda = 2.0;

	for( TriangleList::const_iterator iter = triangleList->cbegin(); iter != triangleList->cend(); iter++ )
	{
		const Triangle& triangle = *iter;
		if( triangle.Intersect( lineSegment, intersectionPoint ) )
		{
			double lambda;
			if( lineSegment.LerpInverse( lambda, intersectionPoint ) )
			{
				if( lambda < smallestLambda )
				{
					smallestLambda = lambda;
					intersectedTriangle = ▵
				}
			}
		}
	}

	return( intersectedTriangle ? true : false );
}

/*virtual*/ bool BoundingBoxTree::LeafNode::FindNearestTriangle( const Vector& point, const Triangle*& nearestTriangle, double maxDistance ) const
{
	double smallestDistance = maxDistance;
	nearestTriangle = nullptr;

	for( TriangleList::const_iterator iter = triangleList->cbegin(); iter != triangleList->cend(); iter++ )
	{
		const Triangle& triangle = *iter;

		double distance = triangle.DistanceToPoint( point );
		if( distance <= smallestDistance )
		{
			smallestDistance = distance;
			nearestTriangle = ▵
		}
	}

	return( nearestTriangle ? true : false );
}

// BoundingBoxTree.cpp


text:
@article{demo,
    title={How to used latex},
    author={John Smith},
    journal={Journal of Latex},
    pages={1--50},
    volume={39},
    year={1977}
}

license: Unlicense

repository: Faur/Latex-Template

repo_name: Faur/Latex-Template

gha_language: TeX


text:
package tree

func kthSmallest(root *TreeNode, k int) int {
	var vals []int
	var preorder func(*TreeNode)
	preorder = func(node *TreeNode) {
		if node == nil {
			return
		}
		preorder(node.Left)
		vals = append(vals, node.Val)
		preorder(node.Right)
	}
	preorder(root)
	return vals[k-1]
}

func kthSmallest2(root *TreeNode, k int) int {
	var stack []*TreeNode
	var vals []int
	node := root
	for node != nil || len(stack) > 0 {
		for node != nil {
			stack = append(stack, node)
			node = node.Left
		}
		node = stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		vals = append(vals, node.Val)
		if len(vals) == k {
			return vals[k-1]
		}
		node = node.Right
	}
	return 0
}

path: /leetcode/tree/230 kthSmallest.go

filename: 230 kthSmallest.go


text:
SUMMARY = "CMake is an open-source, cross-platform family of tools designed to build, test and package software"
LICENSE = "BSD-3-Clause & Apache-2.0"
LIC_FILES_CHKSUM = " \
	file://LICENSE_BSD_3;md5=9134cb61aebbdd79dd826ccb9ae6afcd \
	file://LICENSE_Apache_20;md5=19cbd64715b51267a47bf3750cc6a8a5 \
"

DEPENDS = "ninja-native cmake-native python3-scikit-build-native"

PYPI_PACKAGE = "cmake"
PYPI_ARCHIVE_NAME_PREFIX = "pypi-"

inherit pypi python_setuptools_build_meta
SRC_URI[sha256sum] = "d03f0a76a2b96805044ad1178b92aeeb5f695caa6776a32522bb5c430a55b4e8"

SRC_URI += " \
	file://CMakeLists.txt \
	file://run-cmake-from-path.patch \
"

addtask do_patchbuild after do_patch before do_configure

do_patchbuild () {
	rm -f ${S}/CMakeLists.txt
	cp ${WORKDIR}/CMakeLists.txt ${S}/
}

do_install:append () {
	rm -rf ${D}${bindir}
}

RDEPENDS:${PN} = " \
	cmake \
	python3-scikit-build \
"

BBCLASSEXTEND = "native nativesdk"

repository: openbmc/openbmc

repo_name: openbmc/openbmc

gha_language: Python