text:
package deployer

import (
	"github.com/autom8ter/gcloud/clients"
	"github.com/autom8ter/objectify"
	"k8s.io/api/apps/v1"
	v13 "k8s.io/api/core/v1" //https://godoc.org/k8s.io/api/core/v1
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	apps "k8s.io/client-go/kubernetes/typed/apps/v1"
)

const DefaultNamespace = v13.NamespaceDefault

var util = objectify.Default()

//Client holds an authenticated kubernetes client set
type Deployer struct {
	api apps.DeploymentInterface
}

//NewDeployer returns a Deployer with a kubernetes client set based on whether in/out of cluster
func NewDeployer(incluster bool, namespace string) (*Deployer, error) {
	cli, err := clients.NewKubernetesClientSet(incluster)
	if err != nil {
		return nil, err
	}
	cli.AppsV1().Deployments(namespace)
	return &Deployer{
		api: cli.AppsV1().Deployments(namespace),
	}, nil
}

func (d *Deployer) Validate() error {
	return util.Validate(d)
}

func (d *Deployer) API() apps.DeploymentInterface {
	return d.api
}

func (d *Deployer) CreateDeployment(name string, replicas int, labels map[string]string, containers []*Container) (*v1.Deployment, error) {
	tainers := []v13.Container{}
	for _, c := range containers {
		tainers = append(tainers, c.toConatainer())
	}
	return d.API().Create(&v1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Spec: v1.DeploymentSpec{
			Replicas: int32Ptr(int32(replicas)),
			Selector: &metav1.LabelSelector{
				MatchLabels: labels,
			},
			Template: v13.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: labels,
				},
				Spec: v13.PodSpec{
					Volumes:        nil,
					InitContainers: nil,
					Containers:     tainers,
				},
			},
		},
	})
}

type ContainerOption func(c *Container)

type Container struct {
	Name          string
	Image         string
	Command       []string
	Args          []string
	Directory     string
	ContainerPort int
	HostPort      int
	Env           map[string]string
}

func NewContainer(opts ...ContainerOption) *Container {
	c := &Container{}
	for _, o := range opts {
		o(c)
	}
	return c
}

func (c *Container) toConatainer() v13.Container {
	vars := []v13.EnvVar{}
	for k, v := range c.Env {
		vars = append(vars, v13.EnvVar{
			Name:  k,
			Value: v,
		})
	}
	return v13.Container{
		Name:       c.Name,
		Image:      c.Image,
		Command:    c.Command,
		Args:       c.Args,
		WorkingDir: c.Directory,
		Ports: []v13.ContainerPort{
			{
				Name:          c.Name + "_port",
				HostPort:      int32(c.HostPort),
				ContainerPort: int32(c.ContainerPort),
				Protocol:      "http",
			},
		},
		Env: vars,
	}
}
func int32Ptr(i int32) *int32 { return &i }


text:
#
#
#

SRC_URI = "\
   file://file1 \
   file://file2 \
   "

PROVIDES = "addfiles-rootfs"

RPROVIDES_${PN} += "${PN}"

do_install() {

    rsync -a --exclude=.svn ${ADDFILES_SRC}/files/* ${D}

}

LICENSE = "GPLv2+"

LIC_FILES_CHKSUM = "file://${THISDIR}/license;md5=8cf8463b34caa8ac871a52d5dd7ad1ef"

license: MIT

repository: chaegle/meta-custom-startup

license_type: permissive

repo_name: chaegle/meta-custom-startup

branch_name: refs/heads/master

extension: bb


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace WebRTCme.Middleware
{
    public class GenericPopupOut
    {
        public bool Ok { get; set; }
        public string Entry { get; set; }
    }
}

repository: BlazorHub/WebRTCme

repo_name: BlazorHub/WebRTCme

gha_license_id: NOASSERTION

gha_language: C#

extension: cs


text:
#[===[.md:
# vcpkg_cmake_build

Build a cmake project.

```cmake
vcpkg_cmake_build(
    [TARGET <target>]
    [LOGFILE_BASE <base>]
    [DISABLE_PARALLEL]
    [ADD_BIN_TO_PATH]
)
```

`vcpkg_cmake_build` builds an already-configured cmake project.
You can use the alias [`vcpkg_cmake_install()`] function
if your CMake build system supports the `install` TARGET,
and this is something we recommend doing whenever possible.
Otherwise, you can use `TARGET` to set the target to build.
This function defaults to not passing a target to cmake.

`LOGFILE_BASE` is used to set the base of the logfile names;
by default, this is `build`, and thus the logfiles end up being something like
`build-x86-windows-dbg.log`; if you use `vcpkg_cmake_install`,
this is set to `install`, so you'll get log names like `install-x86-windows-dbg.log`.

For build systems that are buggy when run in parallel,
using `DISABLE_PARALLEL` will run the build with only one job.

Finally, `ADD_BIN_TO_PATH` adds the appropriate (either release or debug)
`bin/` directories to the path during the build,
such that executables run during the build will be able to access those DLLs.
#]===]
if(Z_VCPKG_CMAKE_BUILD_GUARD)
    return()
endif()
set(Z_VCPKG_CMAKE_BUILD_GUARD ON CACHE INTERNAL "guard variable")

function(vcpkg_cmake_build)
    cmake_parse_arguments(PARSE_ARGV 0 "arg" "DISABLE_PARALLEL;ADD_BIN_TO_PATH" "TARGET;LOGFILE_BASE" "")

    if(DEFINED arg_UNPARSED_ARGUMENTS)
        message(FATAL_ERROR "vcpkg_cmake_build was passed extra arguments: ${arg_UNPARSED_ARGUMENTS}")
    endif()
    if(NOT DEFINED arg_LOGFILE_BASE)
        set(arg_LOGFILE_BASE "build")
    endif()

    set(build_args)
    set(target_args)
    set(parallel_args)
    set(no_parallel_args)

    if(Z_VCPKG_CMAKE_GENERATOR STREQUAL "Ninja")
        set(build_args "-v") # verbose output
        set(parallel_args "-j${VCPKG_CONCURRENCY}")
        set(no_parallel_args "-j1")
    elseif(Z_VCPKG_CMAKE_GENERATOR MATCHES "^Visual Studio")
        set(build_args
            "/p:VCPkgLocalAppDataDisabled=true"
            "/p:UseIntelMKL=No"
        )
        set(parallel_args "/m")
    elseif(Z_VCPKG_CMAKE_GENERATOR STREQUAL "NMake Makefiles")
        # No options are currently added for nmake builds
    else()
        message(FATAL_ERROR "Unrecognized GENERATOR setting from vcpkg_configure_cmake(). Valid generators are: Ninja, Visual Studio, and NMake Makefiles")
    endif()

    if(DEFINED arg_TARGET)
        set(target_args "--target" "${arg_TARGET}")
    endif()

    foreach(buildtype IN ITEMS debug release)
        if(NOT DEFINED VCPKG_BUILD_TYPE OR VCPKG_BUILD_TYPE STREQUAL buildtype)
            if(buildtype STREQUAL "debug")
                set(short_buildtype "dbg")
                set(cmake_config "Debug")
            else()
                set(short_buildtype "rel")
                set(cmake_config "Release")
            endif()

            message(STATUS "Building ${TARGET_TRIPLET}-${short_buildtype}")

            if(arg_ADD_BIN_TO_PATH)
                set(env_path_backup "$ENV{PATH}")
                if(buildtype STREQUAL "debug")
                    vcpkg_add_to_path(PREPEND "${CURRENT_INSTALLED_DIR}/debug/bin")
                else()
                    vcpkg_add_to_path(PREPEND "${CURRENT_INSTALLED_DIR}/bin")
                endif()
            endif()

            if (arg_DISABLE_PARALLEL)
                vcpkg_execute_build_process(
                    COMMAND "${CMAKE_COMMAND}" --build . --config "${cmake_config}" ${target_args} -- ${build_args} ${no_parallel_args}
                    WORKING_DIRECTORY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-${short_buildtype}"
                    LOGNAME "${arg_LOGFILE_BASE}-${TARGET_TRIPLET}-${short_buildtype}"
                )
            else()
                vcpkg_execute_build_process(
                    COMMAND "${CMAKE_COMMAND}" --build . --config "${cmake_config}" ${target_args} -- ${build_args} ${parallel_args}
                    NO_PARALLEL_COMMAND "${CMAKE_COMMAND}" --build . --config "${cmake_config}" ${target_args} -- ${build_args} ${no_parallel_args}
                    WORKING_DIRECTORY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-${short_buildtype}"
                    LOGNAME "${arg_LOGFILE_BASE}-${TARGET_TRIPLET}-${short_buildtype}"
                )
            endif()

            if(arg_ADD_BIN_TO_PATH)
                set(ENV{PATH} "${env_path_backup}")
            endif()
        endif()
    endforeach()
endfunction()

extension: cmake


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

package interval

import (
	"bytes"
	"crypto/rand"
	"testing"

	_ "github.com/cockroachdb/cockroach/util/log" // for flags
)

func TestRangeListSingleRangeAndClear(t *testing.T) {
	testRangeGroupSingleRangeAndClear(t, NewRangeList())
}

func TestRangeTreeSingleRangeAndClear(t *testing.T) {
	testRangeGroupSingleRangeAndClear(t, NewRangeTree())
}

func testRangeGroupSingleRangeAndClear(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x02}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added 1 range to range group, wanted len = 1; got len = %d", l)
	}

	rg.Clear()
	if l := rg.Len(); l != 0 {
		t.Errorf("cleared range group, wanted len = 0; got len = %d", l)
	}
}

func TestRangeListTwoRangesBefore(t *testing.T) {
	testRangeGroupTwoRangesBefore(t, NewRangeList())
}

func TestRangeTreeTwoRangesBefore(t *testing.T) {
	testRangeGroupTwoRangesBefore(t, NewRangeTree())
}

func testRangeGroupTwoRangesBefore(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x03}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x02}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 2 {
		t.Errorf("added 2 disjoint ranges to range group, wanted len = 2; got len = %d", l)
	}
}

func TestRangeListTwoRangesAfter(t *testing.T) {
	testRangeGroupTwoRangesAfter(t, NewRangeList())
}

func TestRangeTreeTwoRangesAfter(t *testing.T) {
	testRangeGroupTwoRangesAfter(t, NewRangeTree())
}

func testRangeGroupTwoRangesAfter(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x02}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x03}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 2 {
		t.Errorf("added 2 disjoint ranges to range group, wanted len = 2; got len = %d", l)
	}
}

func TestRangeListTwoRangesMergeForward(t *testing.T) {
	testRangeGroupTwoRangesMergeForward(t, NewRangeList())
}

func TestRangeTreeTwoRangesMergeForward(t *testing.T) {
	testRangeGroupTwoRangesMergeForward(t, NewRangeTree())
}

func testRangeGroupTwoRangesMergeForward(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x03}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x03}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added 2 overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListTwoRangesMergeBackwards(t *testing.T) {
	testRangeGroupTwoRangesMergeBackwards(t, NewRangeList())
}

func TestRangeTreeTwoRangesMergeBackwards(t *testing.T) {
	testRangeGroupTwoRangesMergeBackwards(t, NewRangeTree())
}

func testRangeGroupTwoRangesMergeBackwards(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x03}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x03}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added 2 overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListTwoRangesWithin(t *testing.T) {
	testRangeGroupTwoRangesWithin(t, NewRangeList())
}

func TestRangeTreeTwoRangesWithin(t *testing.T) {
	testRangeGroupTwoRangesWithin(t, NewRangeTree())
}

func testRangeGroupTwoRangesWithin(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x02}, End: []byte{0x03}}); added {
		t.Errorf("added fully contained range to range group, wanted false added flag; got true")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added 2 overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListTwoRangesSurround(t *testing.T) {
	testRangeGroupTwoRangesSurround(t, NewRangeList())
}

func TestRangeTreeTwoRangesSurround(t *testing.T) {
	testRangeGroupTwoRangesSurround(t, NewRangeTree())
}

func testRangeGroupTwoRangesSurround(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x02}, End: []byte{0x03}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added 2 overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListThreeRangesMergeInOrder(t *testing.T) {
	testRangeGroupThreeRangesMergeInOrder(t, NewRangeList())
}

func TestRangeTreeThreeRangesMergeInOrder(t *testing.T) {
	testRangeGroupThreeRangesMergeInOrder(t, NewRangeTree())
}

func testRangeGroupThreeRangesMergeInOrder(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x03}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x03}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x04}, End: []byte{0x06}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added three overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListThreeRangesMergeOutOfOrder(t *testing.T) {
	testRangeGroupThreeRangesMergeOutOfOrder(t, NewRangeList())
}

func TestRangeTreeThreeRangesMergeOutOfOrder(t *testing.T) {
	testRangeGroupThreeRangesMergeOutOfOrder(t, NewRangeTree())
}

func testRangeGroupThreeRangesMergeOutOfOrder(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x03}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x04}, End: []byte{0x06}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x03}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added three overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListThreeRangesMergeReverseOrder(t *testing.T) {
	testRangeGroupThreeRangesMergeReverseOrder(t, NewRangeList())
}

func TestRangeTreeThreeRangesMergeReverseOrder(t *testing.T) {
	testRangeGroupThreeRangesMergeReverseOrder(t, NewRangeTree())
}

func testRangeGroupThreeRangesMergeReverseOrder(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x04}, End: []byte{0x06}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x03}, End: []byte{0x04}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x03}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added three overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListThreeRangesSuperset(t *testing.T) {
	testRangeGroupThreeRangesSuperset(t, NewRangeList())
}

func TestRangeTreeThreeRangesSuperset(t *testing.T) {
	testRangeGroupThreeRangesSuperset(t, NewRangeTree())
}

func testRangeGroupThreeRangesSuperset(t *testing.T, rg RangeGroup) {
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x02}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x04}, End: []byte{0x06}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}
	if added := rg.Add(Range{Start: []byte{0x01}, End: []byte{0x06}}); !added {
		t.Errorf("added new range to range group, wanted true added flag; got false")
	}

	if l := rg.Len(); l != 1 {
		t.Errorf("added three overlapping ranges to range group, wanted len = 1; got len = %d", l)
	}
}

func TestRangeListAndRangeGroupIdentical(t *testing.T) {
	const trials = 5
	for tr := 0; tr < trials; tr++ {
		rl := NewRangeList()
		rt := NewRangeTree()

		const iters = 20
		for i := 0; i < iters; i++ {
			r := getRandomRange(t, 3)
			listAdded := rl.Add(r)
			treeAdded := rt.Add(r)
			if listAdded != treeAdded {
				t.Errorf("expected adding %s to RangeList and RangeTree to produce the same result; got %t from RangeList and %t from RangeTree", r, listAdded, treeAdded)
			}

			listLen := rl.Len()
			treeLen := rt.Len()
			if listLen != treeLen {
				t.Errorf("expected RangeList and RangeTree to have the same length; got %d from RangeList and %d from RangeTree", listLen, treeLen)
			}
		}
	}
}

func getRandomRange(t *testing.T, n int) Range {
	s1 := getRandomByteSlice(t, n)
	s2 := getRandomByteSlice(t, n)
	cmp := bytes.Compare(s1, s2)
	for cmp == 0 {
		s2 = getRandomByteSlice(t, n)
		cmp = bytes.Compare(s1, s2)
	}
	if cmp < 0 {
		return Range{Start: s1, End: s2}
	}
	return Range{Start: s2, End: s1}
}

func getRandomByteSlice(t *testing.T, n int) []byte {
	s := make([]byte, n)
	_, err := rand.Read(s)
	if err != nil {
		t.Fatalf("could not create random byte slice: %v", err)
	}
	return s
}

func BenchmarkRangeList(b *testing.B) {
	benchmarkRangeGroup(b, NewRangeList())
}

func BenchmarkRangeTree(b *testing.B) {
	benchmarkRangeGroup(b, NewRangeTree())
}

func benchmarkRangeGroup(b *testing.B, rg RangeGroup) {
	for i := 0; i < b.N; i++ {
		rg.Add(Range{Start: []byte{0x01}, End: []byte{0x02}})
		rg.Add(Range{Start: []byte{0x04}, End: []byte{0x06}})
		rg.Add(Range{Start: []byte{0x00}, End: []byte{0x02}})
		rg.Add(Range{Start: []byte{0x01}, End: []byte{0x06}})
		rg.Add(Range{Start: []byte{0x05}, End: []byte{0x15}})
		rg.Add(Range{Start: []byte{0x25}, End: []byte{0x30}})
		rg.Clear()
	}
}

repository: SteamShon/cockroach

repo_name: SteamShon/cockroach

extension: go


text:
package function

import (
	"fmt"
	"time"
)

//Request represents a single function invocation.
type Request struct {
	ReqId      string
	Fun        *Function
	Params     map[string]interface{}
	Arrival    time.Time
	ExecReport ExecutionReport
	RequestQoS
	CanDoOffloading bool
	Async           bool
}

type RequestQoS struct {
	Class    ServiceClass
	MaxRespT float64
}

type ExecutionReport struct {
	Result         string
	ResponseTime   float64
	IsWarmStart    bool
	InitTime       float64
	OffloadLatency float64
	Duration       float64
	SchedAction    string
}

type Response struct {
	Success bool
	ExecutionReport
}

type AsyncResponse struct {
	ReqId string
}

func (r *Request) String() string {
	return fmt.Sprintf("Rq-%s", r.Fun.Name, r.ReqId)
}

type ServiceClass int64

const (
	LOW               ServiceClass = 0
	HIGH_PERFORMANCE               = 1
	HIGH_AVAILABILITY              = 2
)

repository: grussorusso/serverledge

repo_name: grussorusso/serverledge

branch_name: refs/heads/main


text:
package usecase

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

	"github.com/a-zara-n/Matchlock/src/domain/value"

	"github.com/a-zara-n/Matchlock/src/config"
	"github.com/a-zara-n/Matchlock/src/domain/repository"

	"github.com/a-zara-n/Matchlock/src/domain/aggregate"
)

//ManagerUsecase is Manage various centers in the software
type ManagerUsecase interface {
	InternalCommunication()
}

type managerUsecase struct {
	channel        config.Channel
	MemoryRequest  repository.RequestRepositry
	MemoryResponse repository.ResponseRepositry
	MemoryHistory  repository.HistoryRepository
	flag           *value.Forward
}

//NewManagerUsecase はManagerUsecaseを返します
func NewManagerUsecase(channel config.Channel, repuestrepo repository.RequestRepositry, responserepo repository.ResponseRepositry, history repository.HistoryRepository, forward *value.Forward) ManagerUsecase {

	return &managerUsecase{channel, repuestrepo, responserepo, history, forward}
}
func (m *managerUsecase) InternalCommunication() {
	for {
		select {
		case req := <-m.channel.Proxy.Request:
			log.Println("リクエストを受信しました")
			httpmessage := aggregate.NewHTTPMessage()
			httpmessage.SetRequest(req)
			httpmessage.SetEditedRequest(req)
			log.Println("リクエストを保存を開始します")
			go m.MemoryRequest.Insert(httpmessage.Get(), false, httpmessage.Request)
			go m.MemoryHistory.Insert(httpmessage.Get(), false)
			if m.flag.Get() {
				log.Println("forwardがONです")
				m.channel.Server.Request <- httpmessage.Request
				httpmessage.EditRequest.SetHTTPRequestByString(<-m.channel.Server.Response)
			}
			log.Println("クライアントを準備しています")
			client := &http.Client{Timeout: time.Duration(10) * time.Second}
			req.RequestURI = httpmessage.EditRequest.Info.URL.RequestURI()
			resp, _ := client.Do(httpmessage.EditRequest.GetHTTPRequestByRequest())

			httpmessage.SetResponse(resp)

			m.channel.Proxy.Response <- resp

			//保存methodを追加
			go m.MemoryResponse.Insert(httpmessage.Get(), httpmessage.Response)
			if m.flag.Get() && httpmessage.IsEdited() {
				go m.MemoryHistory.Update(httpmessage.Get(), true)
				go m.MemoryRequest.Insert(httpmessage.Get(), true, httpmessage.EditRequest)
			}
		}
	}
}


text:
#ifndef SMENTFILE_H_
#define SMENTFILE_H_

#include <vector3.hpp>
#include <zip.h>
#include <vector>
#include <map>
#include <streambuf>
#include <string>
#include <cstring>
#include <iostream>

struct EntityFiles {
	std::vector<EntityFiles> dockedEntities;
	std::map<vector3i, int64_t> regions;
	int64_t headerIdx;
	int64_t logicIdx;
	int64_t metaIdx;
};

enum class fext {
	SMD,
	SMD2,
	SMD3,
	SMBPH,
	SMBPL,
	SMBPM,
	NONE
};

vector3i region(const std::string& path) {
	vector3i v;
	std::size_t i = path.rfind('.') - 1;
	const char * ptr = path.c_str() + 1;
	i = path.rfind('.', i);
	if(i == std::string::npos)
		return vector3i({0,0,0});
	v.z = std::atoi(ptr + i);
	i = path.rfind('.', --i);
	if(i == std::string::npos)
		return vector3i({0,0,0});
	v.y = std::atoi(ptr + i);
	i = path.rfind('.', --i);
	if(i == std::string::npos)
		return vector3i({0,0,0});
	v.x = std::atoi(ptr + i);
	return v;
}

fext ext(const std::string& path) {
	std::size_t i = path.rfind('.') + 1;
	const void* ptr = path.c_str() + i;
	switch(path.length() - i) {
		case 3:
			return (std::memcmp(ptr, "smd", 3) == 0)?fext::SMD:fext::NONE;
		case 4:
			if(std::memcmp(ptr, "smd", 3) == 0)
				switch(path[path.size()-1]) {
					case 2: return fext::SMD2;
					case 3: return fext::SMD3;
					default: return fext::NONE;
				}
			return fext::NONE;
		case 5:
			if(std::memcmp(ptr, "smbp", 4) == 0)
				switch(path[path.size()-1]) {
					case 'h': return fext::SMBPH;
					case 'l': return fext::SMBPL;
					case 'm': return fext::SMBPM;
					default: return fext::NONE;
				}
		default: return fext::NONE;
	}
	return fext::NONE;
}

void decompose(const std::string& path) {
	std::size_t start = 0, cur;
	while((cur = path.find('/', start)) != std::string::npos) {
		std::clog << '\t' << path.substr(start, cur - start) << '\n';
		start = ++cur;
	}
}

class zip_streambuf : public std::streambuf {
	static constexpr std::size_t pbacksz = 32;
	static constexpr std::size_t buffsz = 512;
	static_assert(buffsz>pbacksz, "buffer size must be greater than or equal to"
	                              " put back size");
public:
	explicit zip_streambuf(zip_file_t* fptr) :
	fptr(fptr),
	buffer(buffsz + pbacksz) {
		char* end = buffer.data() + buffer.size();
		setg(end, end, end);
	}

	zip_streambuf(const zip_streambuf&) = delete;
	zip_streambuf& operator=(const zip_streambuf&) = delete;
protected:
	typedef std::streambuf::pos_type pos_type;
	typedef std::streambuf::off_type off_type;
	typedef std::ios_base::openmode openmode;

	virtual std::streambuf::int_type underflow() {
		if(gptr() < egptr())
			return traits_type::to_int_type(*gptr());
		char *base = buffer.data();
		char *start = base;
		if(eback() == base) {
			std::memmove(base, egptr() - pbacksz, pbacksz);
			start += pbacksz;
		}
		std::size_t n = zip_fread(fptr, start, buffer.size() - (start - base));
		if(n <= 0)
			return traits_type::eof();
		setg(base, start, start + n);
		return traits_type::to_int_type(*gptr());
	}

private:

	zip_file_t* fptr;
	std::vector<char> buffer;
};

class SmentFileReader {
public:

	SmentFileReader() :
	archive(nullptr) {}

	SmentFileReader(const char* path) {
		open(path);
	}

	SmentFileReader(const std::string& path) {
		open(path);
	}

	bool open(const std::string& path) {
		return open(path.c_str());
	}

	bool open(const char* path) {
		int errorp;
		archive = zip_open(path, ZIP_RDONLY, &errorp);
		if(!archive) {
			switch(errorp) {
				case ZIP_ER_EXISTS: // shouldn't happen, ZIP_EXCL unset
				case ZIP_ER_INCONS: // inconsistencies in archive
				case ZIP_ER_INVAL: // null path argument
				case ZIP_ER_MEMORY: // couldn't allocate memory
				case ZIP_ER_NOENT: // zip archive not found
				case ZIP_ER_NOZIP: // not a zip archive
				case ZIP_ER_OPEN: // couldn't open file
				case ZIP_ER_READ: // read error, c.f. errno
				case ZIP_ER_SEEK: // opened file doesn't allow seeks
				default:
					break;
			}
		} else {
			int64_t entries = zip_get_num_entries(archive, 0);
			struct zip_stat st;
			for(int64_t i = 0 ; i < entries
				&& zip_stat_index(archive, i, 0, &st) == 0; ++i)
				if(st.valid & ZIP_STAT_NAME) {
					std::clog << st.name << '\n';
					decompose(st.name);
				}
		}
		return archive != nullptr;
	}

	void close() {
		zip_close(archive);
		archive = nullptr;
	}

	~SmentFileReader() {
		close();
	}

private:
	zip_t* archive;
	//int flags;
};

#endif

repository: Septaris/C-StarMadeFileParser

repo_name: Septaris/C-StarMadeFileParser

extension: hpp


text:
cmake_minimum_required(VERSION 3.6)

# if (ARM_TOOLCHAIN_PATH)
#     set(arm_toolchain_path "${ARM_TOOLCHAIN_PATH}/bin")
# elseif (EXISTS $ENV{ARM_TOOLCHAIN})
#     file(TO_CMAKE_PATH $ENV{ARM_TOOLCHAIN} arm_toolchain_path_converted)
#     set(arm_toolchain_path "${arm_toolchain_path_converted}/bin")
# endif()

# message(STATUS "ARM toolchain path: ${arm_toolchain_path}")

# if (arm_toolchain_path)
#     message(STATUS "ARM toolchain path: ${arm_toolchain_path}")
# endif()

# if (arm_toolchain_path)
#     set(binary_paths "${arm_toolchain_path}")
# else ()
#     set(binary_path "/bin" "/usr/bin")
# endif ()

find_program(arm_eabi_c_compiler
    NAMES
        "arm-none-eabi-gcc"
)

find_program(arm_eabi_cxx_compiler
    NAMES
        "arm-none-eabi-g++"
)

find_program(arm_eabi_objcpy
    NAMES
        "arm-none-eabi-objcopy"
)

find_program(arm_eabi_objdump
    NAMES
        "arm-none-eabi-objdump"
)

find_program(arm_eabi_size
    NAMES
        "arm-none-eabi-size"
)

find_program(arm_eabi_gcc_ar
    NAMES
        "arm-none-eabi-gcc-ar"
)

find_program(arm_eabi_ranlib
    NAMES
        "arm-none-eabi-ranlib"
)

message (STATUS "ARM ASM compiler: ${arm_eabi_c_compiler}")
message (STATUS "ARM C compiler:   ${arm_eabi_c_compiler}")
message (STATUS "ARM CXX compiler: ${arm_eabi_cxx_compiler}")
message (STATUS "ARM CXX objcopy:  ${arm_eabi_objcpy}")
message (STATUS "ARM CXX objdump:  ${arm_eabi_objdump}")
message (STATUS "ARM GCC ar:       ${arm_eabi_gcc_ar}")
message (STATUS "ARM ranlib:       ${arm_eabi_ranlib}")

set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY")

set(CMAKE_ASM_COMPILER          ${arm_eabi_c_compiler})
set(CMAKE_C_COMPILER            ${arm_eabi_c_compiler})
set(CMAKE_CXX_COMPILER          ${arm_eabi_cxx_compiler})
set(CMAKE_OBJCOPY               ${arm_eabi_objcpy} CACHE STRING "Path to objcopy executable")
set(CMAKE_OBJDUMP               ${arm_eabi_objdump} CACHE STRING "Path to objdump executable")
set(CMAKE_CXX_LINK_EXECUTABLE   ${arm_eabi_cxx_compiler})
set(CMAKE_C_LINK_EXECUTABLE     ${arm_eabi_c_compiler})
set(CMAKE_AR                    ${arm_eabi_gcc_ar})
set(CMAKE_C_COMPILER_AR         ${arm_eabi_gcc_ar})
set(CMAKE_RANLIB                ${arm_eabi_ranlib})
set(CMAKE_C_COMPILER_RANLIB     ${arm_eabi_ranlib})

#set(CMAKE_C_COMPILER_FORCED TRUE)
#set(CMAKE_CXX_COMPILER_FORCED TRUE)

find_package(PackageHandleStandardArgs)
find_package_handle_standard_args(ArmToolchain DEFAULT_MSG
    arm_eabi_c_compiler
    arm_eabi_cxx_compiler
    arm_eabi_objcpy
    arm_eabi_objdump
    arm_eabi_gcc_ar
    arm_eabi_ranlib
)

repository: matgla/EmbeddedCMakes

repo_name: matgla/EmbeddedCMakes


text:
/*
 * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
 *
 * 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.
 *
 * @author		Aeneas Rekkas <aeneas+oss@aeneas.io>
 * @copyright 	2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
 * @license 	Apache-2.0
 */

package role

import (
	"encoding/json"
	"net/http"

	"github.com/julienschmidt/httprouter"
	"github.com/ory/herodot"
	"github.com/ory/pagination"
	"github.com/pkg/errors"
)

// swagger:model roleMembers
type membersRequest struct {
	Members []string `json:"members"`
}

func NewHandler(manager Manager, writer herodot.Writer) *Handler {
	return &Handler{
		H:       writer,
		Manager: manager,
	}
}

type Handler struct {
	Manager Manager
	H       herodot.Writer
}

const (
	handlerBasePath = "/roles"
)

func (h *Handler) SetRoutes(r *httprouter.Router) {
	r.POST(handlerBasePath, h.CreateRole)
	r.GET(handlerBasePath, h.ListRoles)
	r.GET(handlerBasePath+"/:id", h.GetRole)
	r.DELETE(handlerBasePath+"/:id", h.DeleteRole)
	r.POST(handlerBasePath+"/:id/members", h.AddRoleMembers)
	r.DELETE(handlerBasePath+"/:id/members", h.DeleteRoleMembers)
	r.PUT(handlerBasePath+"/:id", h.UpdateRole)
}

// swagger:route GET /roles role listRoles
//
// List all roles
//
// A Role represents a group of users that share the same role and thus permissions. A role could be an administrator, a moderator, a regular
// user or some other sort of role.
//
// This endpoint allows you to retrieve all roles that are stored in the system.
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: http, https
//
//     Responses:
//       200: listRolesResponse
//       401: genericError
//       403: genericError
//       500: genericError
func (h *Handler) ListRoles(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	limit, offset := pagination.Parse(r, 100, 0, 500)
	if member := r.URL.Query().Get("member"); member != "" {
		h.FindGroupNames(w, r, member, limit, offset)
		return
	} else {
		h.listAllRoles(w, r, limit, offset)
		return
	}
}

func (h *Handler) listAllRoles(w http.ResponseWriter, r *http.Request, limit, offset int) {
	groups, err := h.Manager.ListRoles(limit, offset)
	if err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	h.H.Write(w, r, groups)
}

func (h *Handler) FindGroupNames(w http.ResponseWriter, r *http.Request, member string, limit, offset int) {
	groups, err := h.Manager.FindRolesByMember(member, limit, offset)
	if err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	h.H.Write(w, r, groups)
}

// swagger:route POST /roles role createRole
//
// Create a role
//
// A Role represents a group of users that share the same role and thus permissions. A role could be an administrator, a moderator, a regular
// user or some other sort of role.
//
// This endpoint allows you to create a new role. You may define members as well but you don't have to.
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: http, https
//
//     Responses:
//       201: role
//       401: genericError
//       403: genericError
//       500: genericError
func (h *Handler) CreateRole(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	var g Role

	if err := json.NewDecoder(r.Body).Decode(&g); err != nil {
		h.H.WriteError(w, r, errors.WithStack(err))
		return
	}

	if err := h.Manager.CreateRole(&g); err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	h.H.WriteCreated(w, r, handlerBasePath+"/"+g.ID, &g)
}

// swagger:route GET /roles/{id} role getRole
//
// Get a role by its ID
//
// A Role represents a group of users that share the same role and thus permissions. A role could be an administrator, a moderator, a regular
// user or some other sort of role.
//
// This endpoint allows you to retrieve an existing role. You have to know the role's ID.
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: http, https
//
//     Responses:
//       201: role
//       401: genericError
//       403: genericError
//       500: genericError
func (h *Handler) GetRole(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var id = ps.ByName("id")

	g, err := h.Manager.GetRole(id)
	if err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	h.H.Write(w, r, g)
}

// swagger:route DELETE /roles/{id} role deleteRole
//
// Get a role by its ID
//
// A Role represents a group of users that share the same role and thus permissions. A role could be an administrator, a moderator, a regular
// user or some other sort of role.
//
// This endpoint allows you to delete an existing role. You have to know the role's ID.
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: http, https
//
//     Responses:
//       204: emptyResponse
//       401: genericError
//       403: genericError
//       500: genericError
func (h *Handler) DeleteRole(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var id = ps.ByName("id")

	if err := h.Manager.DeleteRole(id); err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

// swagger:route POST /roles/{id}/members role addMembersToRole
//
// Add members to a role
//
// A Role represents a group of users that share the same role and thus permissions. A role could be an administrator, a moderator, a regular
// user or some other sort of role.
//
// This endpoint allows you to add members (users, applications, ...) to a specific role. You have to know the role's ID.
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: http, https
//
//     Responses:
//       204: emptyResponse
//       401: genericError
//       403: genericError
//       500: genericError
func (h *Handler) AddRoleMembers(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var id = ps.ByName("id")

	var m membersRequest
	if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
		h.H.WriteError(w, r, errors.WithStack(err))
		return
	}

	if err := h.Manager.AddRoleMembers(id, m.Members); err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

// swagger:route DELETE /roles/{id}/members role removeMembersFromRole
//
// Remove members from a role
//
// A Role represents a group of users that share the same role and thus permissions. A role could be an administrator, a moderator, a regular
// user or some other sort of role.
//
// This endpoint allows you to remove members (users, applications, ...) from a specific role. You have to know the role's ID.
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: http, https
//
//     Responses:
//       204: emptyResponse
//       401: genericError
//       403: genericError
//       500: genericError
func (h *Handler) DeleteRoleMembers(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var id = ps.ByName("id")

	var m membersRequest
	if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
		h.H.WriteError(w, r, errors.WithStack(err))
		return
	}

	if err := h.Manager.RemoveRoleMembers(id, m.Members); err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

// swagger:route PUT /roles/{id} role setRole
//
// A Role represents a group of users that share the same role and thus permissions. A role could be an administrator, a moderator, a regular
// user or some other sort of role.
//
// This endpoint allows you to overwrite a role. You have to know the role's ID.
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: http, https
//
//     Responses:
//       204: emptyResponse
//       401: genericError
//       403: genericError
//       500: genericError
func (h *Handler) UpdateRole(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var id = ps.ByName("id")

	var m membersRequest
	if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
		h.H.WriteError(w, r, errors.WithStack(err))
		return
	}

	if err := h.Manager.UpdateRole(Role{
		ID:      id,
		Members: m.Members,
	}); err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

repository: tacurran/keto

repo_name: tacurran/keto

gha_language: Go


text:
package mqtt

import (
	"fmt"
	"github.com/aiicy/aiicy-go/logger"
	"math"
	"sync"
	"time"

	"github.com/aiicy/aiicy-go/utils"
)

type stream struct {
	cli     *Client
	conn    Connection
	future  *Future
	tracker *Tracker
	tomb    utils.Tomb
	once    sync.Once
	mu      sync.Mutex
}

func (c *Client) connect() (*stream, error) {
	// dialing
	dialer := NewDialer(c.ops.TLSConfig, c.ops.Timeout)
	conn, err := dialer.Dial(c.ops.Address)
	if err != nil {
		return nil, err
	}

	// send connect
	connect := NewConnect()
	connect.ClientID = c.ops.ClientID
	connect.KeepAlive = uint16(math.Ceil(c.ops.KeepAlive.Seconds()))
	connect.CleanSession = c.ops.CleanSession
	connect.Username = c.ops.Username
	connect.Password = c.ops.Password
	// connect.Will = c.ops.WillMessage
	err = conn.Send(connect, false)
	if err != nil {
		conn.Close()
		return nil, err
	}

	s := &stream{
		cli:     c,
		conn:    conn,
		future:  NewFuture(),
		tracker: NewTracker(c.ops.KeepAlive),
	}
	s.tomb.Go(s.receiving)

	if len(c.ops.Subscriptions) > 0 {
		err = c.Subscribe(c.ops.Subscriptions)
		if err != nil {
			return nil, err
		}
	}
	if c.ops.KeepAlive > 0 {
		s.tomb.Go(s.pinging)
	}
	err = s.future.Wait(c.ops.Timeout)
	if err != nil {
		s.close()
		return nil, err
	}
	return s, nil
}

func (s *stream) send(pkt Packet, async bool) error {
	s.tracker.Reset()

	s.mu.Lock()
	err := s.conn.Send(pkt, async)
	s.mu.Unlock()
	if err != nil {
		s.die("failed to send packet", err)
		return err
	}

	if ent := s.cli.log.Check(logger.DebugLevel, "client sent a packet"); ent != nil {
		ent.Write(logger.String("pkt", fmt.Sprintf("%v", pkt)))
	}

	return nil
}

func (s *stream) sending(curr Packet) Packet {
	s.cli.log.Info("client starts to send packets")
	defer s.cli.log.Info("client has stopped sending packets")

	var err error
	if curr != nil {
		err = s.send(curr, true)
		if err != nil {
			return curr
		}
	}
	for {
		select {
		case pkt := <-s.cli.cache:
			err = s.send(pkt, true)
			if err != nil {
				return pkt
			}
		case <-s.cli.tomb.Dying():
			return nil
		case <-s.tomb.Dying():
			return nil
		}
	}
}

func (s *stream) receiving() error {
	s.cli.log.Info("client starts to receive packets")
	defer s.cli.log.Info("client has stopped receiving packets")

	var connacked bool
	for {
		pkt, err := s.conn.Receive()
		if err != nil {
			s.die("failed to receive packet", err)
			return err
		}

		if ent := s.cli.log.Check(logger.DebugLevel, "client received a packet"); ent != nil {
			ent.Write(logger.String("pkt", fmt.Sprintf("%v", pkt)))
		}

		if !connacked {
			connacked = true
			err = s.cli.onConnack(pkt)
			if err != nil {
				s.die("failed to handle connack", err)
				return err
			}
			s.future.Complete(nil)
			continue
		}

		switch p := pkt.(type) {
		case *Publish:
			qos := p.Message.QOS
			uerr := s.cli.onPublish(p)
			if uerr != nil {
				s.cli.log.Warn("failed to handle publish packet in user code", logger.Error(uerr))
			} else if !s.cli.ops.DisableAutoAck && qos == 1 {
				ack := NewPuback()
				ack.ID = p.ID
				err = s.send(ack, true)
			}
		case *Puback:
			err = s.cli.onPuback(p)
		case *Suback:
			err = s.cli.onSuback(p)
		case *Pingresp:
			s.tracker.Pong()
		case *Connack:
			err = ErrClientAlreadyConnecting
		default:
			err = fmt.Errorf("packet (%v) not supported", p)
		}

		if err != nil {
			s.die("failed to handle packet", err)
			return err
		}
	}
}

func (s *stream) pinging() error {
	s.cli.log.Info("client starts to send pings")
	defer s.cli.log.Info("client has stopped sending pings")

	var err error
	var window time.Duration
	for {
		window = s.tracker.Window()
		if window < 0 {
			// check if a pong has already been sent
			if s.tracker.Pending() {
				s.die(ErrClientMissingPong.Error(), ErrClientMissingPong)
				return ErrClientMissingPong
			}

			s.tracker.Ping()
			err = s.send(NewPingreq(), false)
			if err != nil {
				return err
			}

			s.cli.log.Debug("client sent a ping")
		}

		select {
		case <-time.After(window):
			continue
		case <-s.cli.tomb.Dying():
			return nil
		case <-s.tomb.Dying():
			return nil
		}
	}
}

func (s *stream) die(msg string, err error) {
	s.once.Do(func() {
		s.future.Cancel(nil)
		s.tomb.Kill(err)
		if err == nil {
			s.send(NewDisconnect(), false)
		}
		s.cli.onError(msg, err)
	})
}

// ! called in the same goroutine with sending
func (s *stream) close() error {
	s.die("", nil)
	s.conn.Close()
	return s.tomb.Wait()
}

repository: Aiicy/aiicy-go

repo_name: Aiicy/aiicy-go


text:
package state

import "encoding/json"

type Metadata struct {
	Name  string // Unique name to associate with a state
	Type  string // The type of state "package", "file", etc.
	State string // The desired state "installed", "rendered", etc.
	Requirements []string `json:"require"`// List of dependent states.
}

func (md *Metadata) Equal(metadata *Metadata) bool {
	return metadata.Name == md.Name && metadata.Type == md.Type && metadata.State == md.State
}

func MetadataFromJSON(data json.RawMessage) (Metadata, error) {
	metadata := Metadata{}
	raw := make(map[string]json.RawMessage)
	err := json.Unmarshal(data, &raw)
	if err != nil {
		return metadata, err
	}
	for key, value := range raw {
		if key == "metadata" {
			err := json.Unmarshal(value, &metadata)
			if err != nil {
				return metadata, err
			}
		}
	}
	return metadata, nil
}

repository: vektorlab/otter

repo_name: vektorlab/otter


text:
require transmission.inc

SRC_URI_append = " file://webupload.patch;striplevel=0"

PR = "r5"

SRC_URI[archive.md5sum] = "0b0428f4a6237a64dc8b7d378ace3f06"
SRC_URI[archive.sha256sum] = "3bc5bf49ed02a3d93b4b9b71c7814960e972c1bde4e9fb83b2cd500c83ae4a9a"


text:
/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 - 2020 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * 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
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include <memory>
#include <string>
#include <utility>

#include "modsecurity/actions/action.h"
#include "modsecurity/transaction.h"
#include "src/actions/action_with_run_time_string.h"
#include "src/variables/variable_with_runtime_string.h"
#include "src/rule_with_operator.h"
#include "src/actions/action_with_execution.h"

#ifndef SRC_ACTIONS_SET_VAR_H_
#define SRC_ACTIONS_SET_VAR_H_

namespace modsecurity {
namespace actions {

enum SetVarOperation {
    /* Set variable to something */
    setOperation,
    /* read variable, sum predicate and set */
    sumAndSetOperation,
    /* read variable, substract predicate and set */
    substractAndSetOperation,
    /* set variable to 1 */
    setToOneOperation,
    /* unset operation */
    unsetOperation,
};

class SetVar : public ActionWithRunTimeString, public ActionWithExecution {
 public:
    SetVar(SetVarOperation operation,
        std::unique_ptr<modsecurity::variables::Variable> variable,
        std::unique_ptr<RunTimeString> predicate)
        : ActionWithRunTimeString(std::move(predicate)),
        m_operation(operation),
        m_variable(std::move(variable)),
        Action("setvar")
    { }

    SetVar(SetVarOperation operation,
        std::unique_ptr<modsecurity::variables::Variable> variable)
        : ActionWithRunTimeString(),
        Action("setvar"),
        m_operation(operation),
        m_variable(std::move(variable))
    { }

    SetVar(const SetVar &var)
        : ActionWithRunTimeString(var),
        Action(var),
        m_operation(var.m_operation),
        m_variable(var.m_variable) {
        variables::RuleVariable *rv = dynamic_cast<variables::RuleVariable *>(
            m_variable.get());
        if (rv != nullptr) {
            auto nrv = rv->clone();
            rv = dynamic_cast<variables::RuleVariable *>(nrv);
            rv->populate(nullptr);
            m_variable = std::unique_ptr<variables::Variable>(nrv);
        }
    }

    bool execute(Transaction *transaction) const noexcept override;

    void populate(RuleWithActions *rule) override {
        ActionWithRunTimeString::populate(rule);
        variables::RuleVariable *rulev =
            dynamic_cast<variables::RuleVariable *>(
                m_variable.get());

        if (rulev != nullptr) {
            rulev->populate(rule);
        }
        variables::VariableWithRunTimeString *rulev2 =
            dynamic_cast<variables::VariableWithRunTimeString *>(
                m_variable.get());

        if (rulev2 != nullptr) {
            rulev2->populate(rule);
        }
    }

    ActionWithRunTimeString *clone() override {
        return new SetVar(*this);
    }

 private:
    SetVarOperation m_operation;
    std::shared_ptr<modsecurity::variables::Variable> m_variable;
};

}  // namespace actions
}  // namespace modsecurity

#endif  // SRC_ACTIONS_SET_VAR_H_

repository: zimmerle/ModSecurity

repo_name: zimmerle/ModSecurity

gha_language: C

extension: h


text:
package cmdy

import (
	"strings"
	"testing"
	"time"

	"github.com/ArtProcessors/cmdy/internal/assert"
)

const expectedUsage = `
  -b    Morbi ac elementum massa. Sed bibendum vel magna eget sagittis. Integer elit ac
        efficitur sodales, nibh felis pulvinar neque, eu pellentesque odio risus sed
        risus. Nulla ac sem ex. Suspendisse in orci pellentesque, posuere massa nec
        (default: true)
  -dv=<duration> (formats: '1h2s', '-3.4ms', units: h, m, s, ms, us, ns)
        Morbi ac elementum massa. Sed bibendum vel magna eget sagittis. (default: 1s)
  -iv=<int>
        Morbi ac elementum massa. Sed bibendum vel magna eget sagittis. (default: 2)
  -pants
        Morbi ac elementum massa. Sed bibendum vel magna eget sagittis. Integer
        tristique, elit ac efficitur sodales, nibh felis (default: true)
  -str=<string>
        Morbi ac elementum massa. Sed bibendum vel magna eget sagittis. (default: "yep")
`

func TestFlagUsage(t *testing.T) {
	tt := assert.WrapTB(t)

	var pants bool
	var str string
	var iv int
	var dv time.Duration

	fs := NewFlagSet()
	fs.BoolVar(&pants, "pants", true, ""+
		"Morbi ac elementum massa. Sed bibendum vel magna eget sagittis. "+
		"Integer tristique, elit ac efficitur sodales, nibh felis")

	fs.StringVar(&str, "str", "yep", ""+
		"Morbi ac elementum massa. Sed bibendum vel magna eget sagittis.")

	fs.IntVar(&iv, "iv", 2, ""+
		"Morbi ac elementum massa. Sed bibendum vel magna eget sagittis.")

	fs.DurationVar(&dv, "dv", 1*time.Second, ""+
		"Morbi ac elementum massa. Sed bibendum vel magna eget sagittis.")

	fs.BoolVar(&pants, "b", true, ""+
		"Morbi ac elementum massa. Sed bibendum vel magna eget sagittis. "+
		"Integer elit ac efficitur sodales, nibh felis "+
		"pulvinar neque, eu pellentesque odio risus sed risus. Nulla "+
		"ac sem ex. Suspendisse in orci pellentesque, posuere massa nec")

	// FIXME: brittle test, but adequate for now.
	tt.MustEqual(expectedUsage, "\n"+fs.Usage())
}

func TestFlagDoubleDash(t *testing.T) {
	tt := assert.WrapTB(t)

	FlagDoubleDash = true
	defer func() {
		FlagDoubleDash = false
	}()

	var a, b, a2, b2 bool
	var s, u, s2, u2 string

	fs := NewFlagSet()
	fs.BoolVar(&a, "a", true, "")
	fs.BoolVar(&b, "b", false, "")
	fs.BoolVar(&a2, "a2", false, "")
	fs.BoolVar(&b2, "b2", true, "")

	fs.StringVar(&s, "s", "", "")
	fs.StringVar(&u, "u", "foo", "")
	fs.StringVar(&s2, "s2", "", "")
	fs.StringVar(&u2, "u2", "foo", "")

	usage := fs.Usage()
	tt.MustAssert(strings.Contains(usage, " -a "))
	tt.MustAssert(strings.Contains(usage, " --a2\n"))
	tt.MustAssert(strings.Contains(usage, " -b "))
	tt.MustAssert(strings.Contains(usage, " --b2\n"))
	tt.MustAssert(strings.Contains(usage, " -s=<string>\n"))
	tt.MustAssert(strings.Contains(usage, " --s2=<string>\n"))
	tt.MustAssert(strings.Contains(usage, " -u=<string>\n"))
	tt.MustAssert(strings.Contains(usage, " --u2=<string>\n"))
}

func TestFlagUsageCollapsing(t *testing.T) {
	// Flags without descriptions should not be followed by a blank line
	tt := assert.WrapTB(t)

	var foo, bar int
	fs := NewFlagSet()
	fs.IntVar(&foo, "foo", 0, "")
	fs.IntVar(&bar, "bar", 0, "")

	expected := "" +
		"  -bar=<int>\n" +
		"  -foo=<int>\n"

	tt.MustEqual(expected, fs.Usage())
}

type (
	hintOnlyVar string
	kindOnlyVar string
	hintBothVar string
	hintNoneVar string
)

func (h hintOnlyVar) String() string            { return string(h) }
func (h hintOnlyVar) Hint() (kind, hint string) { return "", "hint" }
func (h *hintOnlyVar) Set(s string) error       { *h = hintOnlyVar(s); return nil }

func (h kindOnlyVar) String() string            { return string(h) }
func (h kindOnlyVar) Hint() (kind, hint string) { return "kind", "" }
func (h *kindOnlyVar) Set(s string) error       { *h = kindOnlyVar(s); return nil }

func (h hintBothVar) String() string            { return string(h) }
func (h hintBothVar) Hint() (kind, hint string) { return "kind", "hint" }
func (h *hintBothVar) Set(s string) error       { *h = hintBothVar(s); return nil }

func (h hintNoneVar) String() string            { return string(h) }
func (h hintNoneVar) Hint() (kind, hint string) { return "", "" }
func (h *hintNoneVar) Set(s string) error       { *h = hintNoneVar(s); return nil }

const expectedHintableUsage = `
  -hintboth=<kind> (hint)
        hint both
  -hintnone
        hint none
  -hintonly (hint)
        hint only
  -kindonly=<kind>
        kind only
`

func TestFlagVarHintable(t *testing.T) {
	tt := assert.WrapTB(t)

	var hintOnly hintOnlyVar
	var kindOnly kindOnlyVar
	var hintBoth hintBothVar
	var hintNone hintNoneVar

	fs := NewFlagSet()
	fs.Var(&hintOnly, "hintonly", "hint only")
	fs.Var(&kindOnly, "kindonly", "kind only")
	fs.Var(&hintBoth, "hintboth", "hint both")
	fs.Var(&hintNone, "hintnone", "hint none")

	// FIXME: brittle test, but adequate for now.
	tt.MustEqual(expectedHintableUsage, "\n"+fs.Usage())
}

repository: ArtProcessors/cmdy

repo_name: ArtProcessors/cmdy

gha_license_id: MIT


text:
package types

import (
	"fmt"

	sdk "github.com/cosmos/cosmos-sdk/types"
)

// PoolIDFromCoins returns a poolID from a coins object
func PoolIDFromCoins(coins sdk.Coins) string {
	return PoolID(coins[0].Denom, coins[1].Denom)
}

// PoolID returns an alphabetically sorted pool name from two denoms.
// The name is commutative for any all pairs A,B: f(A,B) == f(B,A).
func PoolID(denomA string, denomB string) string {
	if denomB < denomA {
		return fmt.Sprintf("%s/%s", denomB, denomA)
	}

	return fmt.Sprintf("%s/%s", denomA, denomB)
}

// PoolRecord represents the state of a liquidity pool
// and is used to store the state of a denominated pool
type PoolRecord struct {
	// primary key
	PoolID      string
	ReservesA   sdk.Coin `json:"reserves_a" yaml:"reserves_a"`
	ReservesB   sdk.Coin `json:"reserves_b" yaml:"reserves_b"`
	TotalShares sdk.Int  `json:"total_shares" yaml:"total_shares"`
}

// Reserves returns the total reserves for a pool
func (p PoolRecord) Reserves() sdk.Coins {
	return sdk.NewCoins(p.ReservesA, p.ReservesB)
}

// NewPoolRecord takes a pointer to a denominated pool and returns a
// pool record for storage in state.
func NewPoolRecord(pool *DenominatedPool) PoolRecord {
	reserves := pool.Reserves()
	poolID := PoolIDFromCoins(reserves)

	return PoolRecord{
		PoolID:      poolID,
		ReservesA:   reserves[0],
		ReservesB:   reserves[1],
		TotalShares: pool.TotalShares(),
	}
}

// PoolRecords is a slice of PoolRecord
type PoolRecords []PoolRecord

// ShareRecord stores the shares owned for a depositor and pool
type ShareRecord struct {
	// primary key
	Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"`
	// secondary / sort key
	PoolID      string  `json:"pool_id" yaml:"pool_id"`
	SharesOwned sdk.Int `json:"shares_owned" yaml:"shares_owned"`
}

// NewShareRecord takes a depositor, poolID, and shares and returns
// a new share record for storage in state.
func NewShareRecord(depositor sdk.AccAddress, poolID string, sharesOwned sdk.Int) ShareRecord {
	return ShareRecord{
		Depositor:   depositor,
		PoolID:      poolID,
		SharesOwned: sharesOwned,
	}
}

// ShareRecords is a slice of ShareRecord
type ShareRecords []ShareRecord

repository: billni/kava

repo_name: billni/kava


text:
package helpers

import (
	"fmt"
	"os"

	"github.com/solo-io/gloo/pkg/cliutil"
	"github.com/solo-io/go-utils/testutils"
)

func RegisterGlooDebugLogPrintHandlerAndClearLogs() {
	_ = os.Remove(cliutil.GetLogsPath())
	RegisterGlooDebugLogPrintHandler()
}

func RegisterGlooDebugLogPrintHandler() {
	testutils.RegisterPreFailHandler(PrintGlooDebugLogs)
}

func PrintGlooDebugLogs() {
	logs, _ := os.ReadFile(cliutil.GetLogsPath())
	fmt.Println("*** Gloo debug logs ***")
	fmt.Println(string(logs))
	fmt.Println("*** End Gloo debug logs ***")
}

repository: solo-io/gloo

repo_name: solo-io/gloo


text:
package serie

import (
	"github.com/datasweet/cast"
)

func Float32(v ...interface{}) Serie {
	s := New(float32(0), asFloat32, compareFloat32)
	if len(v) > 0 {
		s.Append(v...)
	}
	return s
}

func Float32N(v ...interface{}) Serie {
	s := New(NullFloat32{}, asNullFloat32, compareNullFloat32)
	if len(v) > 0 {
		s.Append(v...)
	}
	return s
}

func asFloat32(i interface{}) float32 {
	f, _ := cast.AsFloat32(i)
	return f
}

func compareFloat32(a, b float32) int {
	if a == b {
		return Eq
	}
	if a < b {
		return Lt
	}
	return Gt
}

type NullFloat32 struct {
	Float32 float32
	Valid   bool
}

func (f NullFloat32) Interface() interface{} {
	if f.Valid {
		return f.Float32
	}
	return nil
}

func asNullFloat32(i interface{}) NullFloat32 {
	var ni NullFloat32
	if i == nil {
		return ni
	}

	if v, ok := i.(NullFloat32); ok {
		return v
	}

	if v, ok := cast.AsFloat32(i); ok {
		ni.Float32 = v
		ni.Valid = true
	}
	return ni
}

func compareNullFloat32(a, b NullFloat32) int {
	if !b.Valid {
		if !a.Valid {
			return Eq
		}
		return Gt
	}
	if !a.Valid {
		return Lt
	}
	return compareFloat32(a.Float32, b.Float32)
}

repository: datasweet/datatable

repo_name: datasweet/datatable


text:
package main

import (
	"runtime"
	"flag"
	"fmt"
	"time"
	"log"
	"bytes"
	"github.com/valyala/fasthttp"
	"github.com/AubSs/fasthttplogger"
	"github.com/json-iterator/go"
  "github.com/aws/aws-sdk-go/aws"
  "github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

// Location : Meraki device observation location
type Location struct {
  Lat float64 `json:"lat,omitempty"`
  Lng float64 `json:"lng,omitempty"`
  Unc float64 `json:"unc,omitempty"`
  X []float64 `json:"x,omitempty"`
  Y []float64 `json:"y,omitempty"`
}
// ScanData : Scanning API top level data
type ScanData struct {
	Type    string     `json:"type"`
	Secret  string     `json:"secret"`
	Version string     `json:"version"`
	Data    ClientData `json:"data"`
}
// ClientData : Client data
type ClientData struct {
	ApMac        string        `json:"apMac"`
	ApFloors     []string      `json:"apFloors"`
	ApTags       []string      `json:"apTags"`
	Observations []Observation `json:"observations"`
	Tenant       string        `json:"tenant"`
}
// Observation ; Observation data
type Observation struct {
	Ssid         string       `json:"ssid"`
	Ipv4         string       `json:"ipv4"`
	Ipv6         string       `json:"ipv6"`
	SeenEpoch    float64      `json:"seenEpoch"`
	SeenTime     string       `json:"seenTime"`
	Rssi         int          `json:"rssi"`
	Manufacturer string       `json:"manufacturer"`
	Os           string       `json:"os"`
	Location     LocationData `json:"location"`
	ClientMac    string       `json:"clientMac"`
}
// LocationData : Location Data
type LocationData struct {
	Lat float64   `json:"lat"`
	X   []float64 `json:"x"`
	Lng float64   `json:"lng"`
	Unc float64   `json:"unc"`
	Y   []float64 `json:"y"`
}

type job struct {
  scanData []byte
}

var (
	loc *time.Location
	maxQueueSize = flag.Int("max_queue_size", 100, "The size of the job queue")
	maxWorkers = flag.Int("max_workers", 5, "The number of workers to start")
	port = flag.String("port", "8080", "The server port")
	bucket = flag.String("bucket", "cri.conatel.cloud", "The S3 Bucket where the data will be stored")
	location = flag.String("location", "UTC", "The time location")
	tls = flag.Bool("tls", false, "Should the server listen and serve tls")
	serverCrt = flag.String("server-tls", "server.crt", "Server TLS certificate")
	serverKey = flag.String("server-key", "server.key", "Server TLS key")
	validator = flag.String("validator", "da6a17c407bb11dfeec7392a5042be0a4cc034b6", "Meraki Sacnning API Validator")
	secret = flag.String("secret", "cjkww5rmn0001SE__2j7wztuy", "Meraki Sacnning API Secret")
)

func main() {
	// Parse flags
	flag.Parse()
	// Configure concurrent jobs
  runtime.GOMAXPROCS(runtime.NumCPU())
  fmt.Println("GOMAXPROCS =", runtime.NumCPU())
  fmt.Println("maxWorkers =", *maxWorkers)
  fmt.Println("maxQueueSize =", *maxQueueSize)
  fmt.Println("port =", *port)
	// Set the time location
	var err error
  loc, err = time.LoadLocation(*location)
  if err != nil {
    panic(err)
  }
	// Create job channel
  jobs := make(chan job, *maxQueueSize)
	// Create an AWS Session and an s3 service
  sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-east-1"),
  })
  if err != nil {
		fmt.Printf("Could not configure the AWS Go SDK: %v\n", err)
  }
	svc := s3.New(sess)
	// Create the worker handler
	processBody := createProcessBody(svc)
	// Create workers
  for index := 1; index <= *maxWorkers; index++ {
    fmt.Println("Starting worker #", index)
    go func(index int) {
      for job := range jobs {
        processBody(index, job)
      }
    }(index)
  }
	// Fasthttp configuration
	handler := requestHandler(jobs)
	if err := fasthttp.ListenAndServe("0.0.0.0:" + *port, fasthttplogger.Combined(handler)); err != nil {
		log.Fatalf("Error in ListenAndServe: %s", err)
	}
}

func requestHandler(jobs chan job) func (ctx *fasthttp.RequestCtx) {
	return func (ctx *fasthttp.RequestCtx) {
		path := string(ctx.URI().Path())
		method := string(ctx.Method())
		if method == "GET" {
			if path == "/loaderio-e482326fbb627da5b2ce44f66c07fee0/" {
				ctx.SetContentType("text/plain; charset=utf8")
				fmt.Fprintf(ctx, "loaderio-e482326fbb627da5b2ce44f66c07fee0")
				return
			}
			if path == "/" {
				getValidator(ctx)
				return
			}
			if path == "/healthz" {
				getHealthz(ctx)
				return
			}
		}
		if method == "POST" {
			if path == "/" {
				getData(ctx, jobs)
				return
			}
		}
		ctx.Response.SetStatusCode(404)
		ctx.SetContentType("text/plain; charset=utf8")
		fmt.Fprintf(ctx, "404 - Not Found")
	}
}

func createProcessBody(svc *s3.S3) func(id int, j job) {
	return func (id int, j job) {
		var scanData ScanData
		err := json.Unmarshal(j.scanData, &scanData)
		if err != nil {
			fmt.Println("Can't decode body")
			return
		}
		if *secret != scanData.Secret {
			fmt.Println("Invalid secret", scanData.Secret)
			return
		}
		start := time.Now()
		data := scanData.Data
		now := time.Now().In(loc).Format(time.RFC3339)
		key := now + "-" + data.ApMac + ".json"
		data.Tenant = "tata"
		dataBytes, err := json.Marshal(data)
		if err != nil {
			panic(err)
		}
		input := &s3.PutObjectInput{
			Body: bytes.NewReader(dataBytes),
			Bucket: aws.String(*bucket),
			Key: aws.String(key),
		}
		_, err = svc.PutObject(input)
		if err != nil {
			panic(err)
		}
		fmt.Println("Saved", key, "to S3 in", time.Since(start))
	}
}

func getValidator (ctx *fasthttp.RequestCtx) {
	ctx.SetContentType("text/plain; charset=utf8")
	fmt.Fprintf(ctx, *validator)
}

func getHealthz (ctx *fasthttp.RequestCtx) {
	ctx.Response.SetStatusCode(204)
}

func getData (ctx *fasthttp.RequestCtx, jobs chan job) {
	scanData := ctx.Request.Body()
	go func() {
    jobs <- job{scanData}
  }()
  // Render success
	ctx.Response.SetStatusCode(204)
}


text:
#include "CExoArrayListTemplatedCWorldJournalEntry.hpp"
#include "API/Functions.hpp"
#include "Platform/ASLR.hpp"

#include "CWorldJournalEntry.hpp"

namespace NWNXLib {

namespace API {

CExoArrayListTemplatedCWorldJournalEntry::~CExoArrayListTemplatedCWorldJournalEntry()
{
    CExoArrayListTemplatedCWorldJournalEntry__CExoArrayListTemplatedCWorldJournalEntryDtor(this);
}

void CExoArrayListTemplatedCWorldJournalEntry::Allocate(int32_t a0)
{
    return CExoArrayListTemplatedCWorldJournalEntry__Allocate(this, a0);
}

void CExoArrayListTemplatedCWorldJournalEntry::SetSize(int32_t a0)
{
    return CExoArrayListTemplatedCWorldJournalEntry__SetSize(this, a0);
}

void CExoArrayListTemplatedCWorldJournalEntry__CExoArrayListTemplatedCWorldJournalEntryDtor(CExoArrayListTemplatedCWorldJournalEntry* thisPtr)
{
    using FuncPtrType = void(__attribute__((cdecl)) *)(CExoArrayListTemplatedCWorldJournalEntry*, int);
    uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoArrayListTemplatedCWorldJournalEntry__CExoArrayListTemplatedCWorldJournalEntryDtor);
    FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
    func(thisPtr, 2);
}

void CExoArrayListTemplatedCWorldJournalEntry__Allocate(CExoArrayListTemplatedCWorldJournalEntry* thisPtr, int32_t a0)
{
    using FuncPtrType = void(__attribute__((cdecl)) *)(CExoArrayListTemplatedCWorldJournalEntry*, int32_t);
    uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoArrayListTemplatedCWorldJournalEntry__Allocate);
    FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
    return func(thisPtr, a0);
}

void CExoArrayListTemplatedCWorldJournalEntry__SetSize(CExoArrayListTemplatedCWorldJournalEntry* thisPtr, int32_t a0)
{
    using FuncPtrType = void(__attribute__((cdecl)) *)(CExoArrayListTemplatedCWorldJournalEntry*, int32_t);
    uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoArrayListTemplatedCWorldJournalEntry__SetSize);
    FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
    return func(thisPtr, a0);
}

}

}

repository: presscad/nwnee

repo_name: presscad/nwnee

extension: cpp


text:
package miapi

import (
	"../../utils/apierrors"
	"../../utils/constants"
	"../../utils/requests"
	"encoding/json"
	"fmt"
	"net/http"
)

type Site struct {
	ID string `json:"id"`
	Name string `json:"name"`
	CountryID string `json:"country_id"`
	SalesFreeMode string `json:"sales_free_mode"`
	MercadoPagoVersion string `json:"mercado_pago_version"`
	DefaultCurrencyId string `json:"default_currency_id"`
	InmediatePayment string `json:"inmediate_payment"`
	PaymentMethods []interface{} `json:"payment_methods"`
	Settings struct{
		IdentificationTypes []interface{} `json:"identification_types"`
		TaxpayerTypes []interface{}
	} `json:"settings"`
	Currencies []interface{} `json:"currencies"`
	Categories []interface{} `json:"categories"`

}

type Sites[] struct {
	ID string `json:"id"`
	Name string `json:"name"`
	CountryID string `json:"country_id"`
	SalesFreeMode string `json:"sales_free_mode"`
	MercadoPagoVersion string `json:"mercado_pago_version"`
	DefaultCurrencyId string `json:"default_currency_id"`
	InmediatePayment string `json:"inmediate_payment"`
	PaymentMethods []interface{} `json:"payment_methods"`
	Settings struct{
		IdentificationTypes []interface{} `json:"identification_types"`
		TaxpayerTypes []interface{}
	} `json:"settings"`
	Currencies []interface{} `json:"currencies"`
	Categories []interface{} `json:"categories"`

}

func (site *Site) Get() *apierrors.ApiError {
	if site.ID == "" {
		return &apierrors.ApiError{
			Message: "El site está vacío",
			Status:  http.StatusBadRequest,
		}
	}

	url := fmt.Sprintf("%s%s", constants.MockUrlSites, site.ID)
	data, err := requests.Get(url)

	if err != nil {
		return &apierrors.ApiError{
			Message: err.Error(),
			Status: http.StatusInternalServerError,
		}
	}

	if err := json.Unmarshal(data, &site);
		err != nil {
		return &apierrors.ApiError{
			Message: err.Error(),
			Status:  http.StatusInternalServerError,
		}
	}
	return nil

}

func GetAllSites(sites *Sites) *apierrors.ApiError {
	fmt.Println("About to get all sites from MELI...")
	res, err := requests.Get(constants.UrlSites)
	if err != nil {
		return &apierrors.ApiError{
			Message: err.Error(),
			Status:  http.StatusInternalServerError,
		}
	}

	if err != nil {
		return &apierrors.ApiError{
			Message: err.Error(),
			Status:  http.StatusInternalServerError,
		}
	}

	if err := json.Unmarshal(res, &sites);
		err != nil {
		return &apierrors.ApiError{
			Message: err.Error(),
			Status:  http.StatusInternalServerError,
		}
	}
	return nil
}

repository: ferralucho/go-sites-users-meli-api

repo_name: ferralucho/go-sites-users-meli-api


text:
package tests

import (
	"math"
	"reflect"
	"testing"
)

/**
 * [448] Find All Numbers Disappeared in an Array
 *
 * Given an array of integers where 1 <= a[i] <= n (n = size of array), some elements appear twice and others appear once.
 *
 * Find all the elements of [1, n] inclusive that do not appear in this array.
 *
 * Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
 *
 * Example:
 *
 * Input:
 * [4,3,2,7,8,2,3,1]
 *
 * Output:
 * [5,6]
 *
 *
 */

func TestFindAllNumbersDisappearedinanArray(t *testing.T) {
	var cases = []struct {
		input  []int
		output []int
	}{
		{
			input:  []int{4, 3, 2, 7, 8, 2, 3, 1},
			output: []int{5, 6},
		},
	}
	for _, c := range cases {
		x := findDisappearedNumbers(c.input)
		if !reflect.DeepEqual(x, c.output) {
			t.Fail()
		}
	}
}

// submission codes start here

func findDisappearedNumbers(nums []int) []int {
	res := make([]int, 0)
	for i := 0; i < len(nums); i++ {
		v := int(math.Abs(float64(nums[i]))) - 1
		if nums[v] > 0 {
			nums[v] = -nums[v]
		}
	}
	for i := 0; i < len(nums); i++ {
		if nums[i] > 0 {
			res = append(res, i+1)
		}
	}
	return res
}

// submission codes end


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

using System;
using System.Collections.Generic;
using System.Security;
using PlatformAgileFramework.ErrorAndException;
using PlatformAgileFramework.FileAndIO.FileAndDirectoryService;
using PlatformAgileFramework.Logging;
using PlatformAgileFramework.TypeHandling;
using PlatformAgileFramework.UserInterface;

// Exception shorthand.
using PAFSED = PlatformAgileFramework.FrameworkServices.Exceptions.PAFServiceExceptionData;
using IPAFSED = PlatformAgileFramework.FrameworkServices.Exceptions.IPAFServiceExceptionData;
using PlatformAgileFramework.FrameworkServices.Exceptions;
using PlatformAgileFramework.MultiProcessing.Tasking;

namespace PlatformAgileFramework.FrameworkServices
{
	/// <summary>
	/// This FrameworkService "manager" contains a singleton version of basic or "core"
	/// services that must be present even to start an application. These services
	/// have to do with loading files, interacting with the user during error
	/// conditions, etc. These services are often initialized with stand-in versions.
	/// As the application loads, the client may overload these services with more
	/// sophisticated versions to service the full application.
	/// </summary>
	/// <history>
	/// <author> DAP </author>
	/// <date> 21feb2012 </date>
	/// <contribution>
	/// Made necessary mods to use one base service manager for both remote
	/// and local services - code consolidation. Moved everything but dynamic
	/// deadlock detection/resolution out of Core according to KRM.
	/// </contribution>
	/// <author> KRM </author>
	/// <date> 27jan2012 </date>
	/// <contribution> Converted from 3.5 and cleaned up. </contribution>
	/// </history>
	/// <threadsafety>
	/// Synchronized.
	/// </threadsafety>
	/// <remarks>
	/// This service manager is both a Generic and non-Generic service manager.
	/// We had to build it this way to support legacy applications. But you don't
	/// have to build YOUR service manager this way! Better to require Generic
	/// services for type-safety.
	/// </remarks>
	// ReSharper disable PartialTypeWithSinglePart
	// Core part
	public sealed partial class PAFServices
		: PAFGeneralServiceManager<IPAFService>
	// ReSharper restore PartialTypeWithSinglePart
	{
		#region Class Fields
		//////////////////////////////////////////////////////////////////////////////////////
		//// These are our singleton versions of the low-level services that are always here
		//// (unless we get an exception in our constructor). These are internal static
		//// properties so they can be set from afar before the services are first accessed.
		//// These services are typically initially set as very simple versions of the services
		//// that do not have service dependencies, or have few.
		//////////////////////////////////////////////////////////////////////////////////////

		/// <summary>
		///	This is the UI service. This is the simple console and dialog window service.
		/// It is usually augmented with something more substantial once the app gets running.
		/// This service is usually a singleton (one instance per app domain) so they
		/// are static.
		/// </summary>
		// ReSharper disable once InconsistentNaming
		public static IPAFServiceDescription<IPAFUIService> s_SiPAFUIService
		{
			[SecurityCritical]
			get { return s_SiPAFUIServiceInternal; }
			[SecurityCritical]
			set { s_SiPAFUIServiceInternal = value; }
		}
		internal static IPAFServiceDescription<IPAFUIService> s_SiPAFUIServiceInternal
		{ get; set; }

		/// <summary>
		///	This is the logging service. It is dependent on the storage service usually.
		/// </summary>
		public static IPAFServiceDescription<IPAFLoggingService> s_SiPAFLoggingService
		{
			[SecurityCritical]
			get { return s_SiPAFLoggingServiceInternal; }
			[SecurityCritical]
			set { s_SiPAFLoggingServiceInternal = value; }
		}
		internal static IPAFServiceDescription<IPAFLoggingService> s_SiPAFLoggingServiceInternal
		{ get; set; }

		/// <summary>
		///	This is the storage service. This is fundamental file/directory access
		/// in simplest cases. This service can be pre-loaded with a basic implementation that
		/// is needed to even read configuration files to get the application parameterized,
		/// then replaced with something more specific. This needs to be loaded for emergency
		/// logger to log anything during SM initialization failure.
		/// </summary>
		public static IPAFServiceDescription<IPAFStorageService> SiPAFStorageService
		{
			get { return SiPAFStorageServiceInternal; }
			[SecurityCritical]
			set { SiPAFStorageServiceInternal = value; }
		}
		internal static IPAFServiceDescription<IPAFStorageService> SiPAFStorageServiceInternal { get; set; }

		///// <summary>
		///// Established by the bootstrapper method. Not synchronized.
		///// </summary>
		//public static ISymbolicDirectoryMappingDictionary DirectoryMappings { get; protected internal set; }

		//////////////////////////////////////////////////////////////////////////////////////
		/// <summary>
		/// Lock for multi-thread access. 1 indicates already initializing.
		/// </summary>
		/// <remarks>
		/// This is a lock variable and must never be touched by anyone except
		/// the initialization method. Not volatile since it is not accessed directly.
		/// </remarks>
		private static int s_1ForInitializing;
		/// <summary>
		/// Just tells our internals if initialization is complete.
		/// </summary>
		public static bool IsInitialized { get { return s_1ForInitializing != 1; } }
		/// <summary>
		/// Disposal key.
		/// </summary>
		private static Guid s_DisposalKey;
		/// <summary>
		/// Our singleton service set.
		/// </summary>
		private static PAFServices s_Services;
		#endregion Class Fields
		#region Constructors
		/// <summary>
		///	Initializes a new instance of the <see cref="PAFServiceManager"/> class.
		/// This is the standard one that the regular <see cref="Manager"/> property
		/// retrieves.
		/// </summary>
		/// <remarks>
		///	This is private to enforce the singleton condition.
		/// </remarks>
		[SecuritySafeCritical]
		private PAFServices()
			: base(null, null, GetStaticGuid())
		{
		}
		#endregion Constructors
		#region Singleton Members
		/// <summary>
		///	Gets the singleton instance after ensuring it is completely constructed.
		/// </summary>
		/// <value>The singleton instance.</value>
		/// <remarks>
		/// Lazy construction needed here, since the "AppDomain" creator
		/// may wish to set static fields before first access.
		/// </remarks>
		/// <security>
		/// Security safe so external app can access services without being trusted.
		/// </security>
		public static IPAFServiceManager<IPAFService> Manager
		{
			[SecuritySafeCritical]
			get
			{
				var manager =
				ThreadingUtils.LazyConstructionLock<PAFServices, object>
					(ref s_1ForInitializing, ref s_Services, null, InstantiateAndProvision);
				return manager;
			}
		}
		#endregion Singleton Members
		#region Methods
		/// <summary>
		/// Checks to see whether the disposal key has been loaded and generates
		/// a random guid if not.
		/// </summary>
		/// <returns>
		/// Preloaded or new random key.
		/// </returns>
		internal static Guid GetStaticGuid()
		{
			if (s_DisposalKey == Guid.Empty)
				s_DisposalKey = Guid.NewGuid();
			return s_DisposalKey;
		}
		/// <summary>
		/// This method is the "bootstrapper" for the service manager. It installs basic
		/// critical services from service objects that are either pre-loaded as statics
		/// or created by searching assemblies for implementations.
		/// </summary>
		/// <param name="o">An optional provisioning object.</param>
		/// <returns></returns>
		[SecurityCritical]
		internal static PAFServices InstantiateAndProvision(object o)
		{
			var manager = new PAFServices();
			// We must build initial services here, since the staging phases need basic
			// services.
			manager.BuildInitialServices();
			// By using the SM to supply services to itself, we allow iterative
			// load/initialize as service dependencies are negotiated.
			manager.StageDependentServices(manager, ServicePipelineStage.LOAD, true);
			manager.StageDependentServices(manager, ServicePipelineStage.INITIALIZE, true);

			// Set manager and flag to turn on service singleton for everybody.
			s_Services = manager;
			return manager;
		}

		/// <summary>
		/// <para>
		/// This is a helper method that builds the services from <see cref="PAFServiceManager.InitialServicesInternal"/>,
		/// one-by-one, in enumeration order and adds them to the service array without initializing
		/// them.
		/// </para>
		/// <para>
		/// The method will construct the initial set of services. It then checks to see if
		/// these services contain <see cref="IPAFLoggingService"/> or <see cref="IPAFUIService"/>
		/// or <see cref="IPAFStorageService"/>. If they do, <see cref="s_SiPAFLoggingService"/>
		/// and/or <see cref="s_SiPAFUIService"/> and/or <see cref="SiPAFStorageService"/>
		/// are replaced with these versions. If they don't and <see cref="s_SiPAFLoggingService"/>
		/// or <see cref="s_SiPAFLoggingService"/> or <see cref="SiPAFStorageService"/> are loaded,
		/// they are used instead. If no UI and/or Logger service has been provided from either
		/// input source, defaults are constructed.
		/// </para>
		/// </summary>
		/// <remarks>
		/// Currently, we cannot survive without a storage service being supplied, either in the
		/// <see cref="PAFGeneralServiceManager{IPAFService}.InitialServicesInternal"/> or in the static
		/// in this class.
		/// </remarks>
		/// <exceptions>
		/// <exception cref="PAFStandardException{IPAFSED}">
		/// <see cref="PAFServiceExceptionMessageTags.SERVICE_NOT_FOUND"/> is thrown if storage service not loaded. It is wrapped
		/// in a general exception.
		/// </exception>
		/// <exception cref="PAFStandardException{IPAFSED}">
		/// <see cref="PAFServiceExceptionMessageTags.SERVICE_CREATION_FAILED"/> is thrown as a wrapper if any exceptions
		/// occur in the method.
		/// </exception>
		/// </exceptions>
		private void BuildInitialServices()
		{
			var servicesBuilt = new List<IPAFServiceDescription>();
			try
			{
				////// We'll need one copy of the service object for any construction work we'll do.
				var iPAFServicePipelineObject
					= new PAFServicePipelineObject(this, ServicePipelineStage.CONSTRUCTION);
				if (InitialServicesInternal != null)
				{
					foreach (var svcDescription in InitialServicesInternal)
					{
						// Skip if we were pushed in already built.
						if (svcDescription.ServiceObject != null)
						{
							servicesBuilt.Add(svcDescription);
							continue;
						}
						var service = CreateServicePIV(
							iPAFServicePipelineObject, svcDescription);
						servicesBuilt.Add(service);
					}

					// Add the services that we may need for further work in this method.
					AddServicesHelper(servicesBuilt);
				}
				/////////////////////////////////////////////////////////////////////////////////////////////////////////
				//// If we do not have storage, logger or UI, put them in.
				/////////////////////////////////////////////////////////////////////////////////////////////////////////
				// SS
				if (GetAnyServiceDescription<IPAFStorageService>() == null)
				{
					// See if it is incoming on the static.
					if (SiPAFStorageServiceInternal == null)
					{
						// Can't withstand lack of a storage facility.
						var data
							= new PAFSED(new PAFServiceDescription<IPAFStorageService>(
								PAFTypeHolder.IHolder(typeof (IPAFStorageService))));
						throw new PAFStandardException<IPAFSED>(data, PAFServiceExceptionMessageTags.SERVICE_NOT_FOUND);
					}
					IPAFServiceDescription serviceDescription = SiPAFStorageServiceInternal;
					var servicePreload = SiPAFStorageServiceInternal.ServiceObject;

					// Not preloaded?
					if (servicePreload == null)
						serviceDescription =  CreateServicePIV(iPAFServicePipelineObject,
							SiPAFStorageServiceInternal);

					AddServiceHelper(serviceDescription);
				}

				// UI.
				if (GetAnyServiceDescription< IPAFUIService>() == null)
				{
					// See if it is incoming on the static.
					if (s_SiPAFUIServiceInternal == null)
					{
						// Can't withstand lack of a storage facility.
						var data
							= new PAFSED(new PAFServiceDescription<IPAFUIService>(
								PAFTypeHolder.IHolder(typeof(IPAFUIService))));
                        throw new PAFStandardException<IPAFSED>(data, PAFServiceExceptionMessageTags.SERVICE_NOT_FOUND);
					}
					IPAFServiceDescription serviceDescription = s_SiPAFUIServiceInternal;
					var servicePreload = s_SiPAFUIServiceInternal.ServiceObject;

					// Not preloaded?
					if (servicePreload == null)
						serviceDescription = CreateServicePIV(iPAFServicePipelineObject,
							s_SiPAFUIServiceInternal);

					AddServiceHelper(serviceDescription);
				}

				// Logger.
				if (GetAnyServiceDescription<IPAFLoggingService>() == null)
				{
					// See if it is incoming on the static.
					if (s_SiPAFLoggingServiceInternal == null)
					{
						//// Customer requirements specify a need for an "emergency" logger
						//// that does not have requirements on anything being configured yet.
						s_SiPAFLoggingServiceInternal
							= new PAFServiceDescription<IPAFLoggingService>(
							new PAFTypeHolder(typeof (IPAFLoggingService)),
							new PAFTypeHolder(typeof (EmergencyLoggingService)));
					}
					IPAFServiceDescription serviceDescription = s_SiPAFLoggingServiceInternal;
					var servicePreload = s_SiPAFLoggingServiceInternal.ServiceObject;

					// Not preloaded?
					if (servicePreload == null)
						serviceDescription = CreateServicePIV(iPAFServicePipelineObject,
							s_SiPAFLoggingServiceInternal);

					AddServiceHelper(serviceDescription);
				}
			}
			catch (Exception ex)
			{
				var data = new PAFSED(null);
                throw new PAFStandardException<IPAFSED>(data, PAFServiceExceptionMessageTags.SERVICE_CREATION_FAILED, ex);
			}
		}

		#endregion // Methods
	}
}

repository: Platform-Agile-Software/PAF-Community

repo_name: Platform-Agile-Software/PAF-Community


text:
package chunkymonkey

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"os"
	"rand"
	"regexp"
	"time"

	"chunkymonkey/command"
	. "chunkymonkey/entity"
	"chunkymonkey/gamerules"
	"chunkymonkey/player"
	"chunkymonkey/proto"
	"chunkymonkey/server_auth"
	"chunkymonkey/shardserver"
	. "chunkymonkey/types"
	"chunkymonkey/worldstore"
	"nbt"
)

// We regard usernames as valid if they don't contain "dangerous" characters.
// That is: characters that might be abused in filename components, etc.
var validPlayerUsername = regexp.MustCompile(`^[\-a-zA-Z0-9_]+$`)

type Game struct {
	chunkManager  *shardserver.LocalShardManager
	entityManager EntityManager
	worldStore    *worldstore.WorldStore

	// Mapping between entityId/name and player object
	players     map[EntityId]*player.Player
	playerNames map[string]*player.Player

	// Channels for events/actions
	workQueue        chan func(*Game)
	playerConnect    chan *player.Player
	playerDisconnect chan EntityId

	// Server information
	time                Ticks
	serverId            string
	UnderMaintenanceMsg string // if set, logins are disallowed.
}

func NewGame(worldPath string) (game *Game, err os.Error) {
	worldStore, err := worldstore.LoadWorldStore(worldPath)
	if err != nil {
		return nil, err
	}

	game = &Game{
		players:          make(map[EntityId]*player.Player),
		playerNames:      make(map[string]*player.Player),
		workQueue:        make(chan func(*Game), 256),
		playerConnect:    make(chan *player.Player),
		playerDisconnect: make(chan EntityId),
		time:             worldStore.Time,
		worldStore:       worldStore,
	}

	game.entityManager.Init()

	game.serverId = fmt.Sprintf("%016x", rand.NewSource(worldStore.Seed).Int63())
	//game.serverId = "-"

	game.chunkManager = shardserver.NewLocalShardManager(worldStore.ChunkStore, &game.entityManager)

	// TODO: Load the prefix from a config file
	gamerules.CommandFramework = command.NewCommandFramework("/")

	go game.mainLoop()
	return
}

// Fetch external events and respond appropriately
func (game *Game) mainLoop() {
	ticker := time.NewTicker(NanosecondsInSecond / TicksPerSecond)

	for {
		select {
		case f := <-game.workQueue:
			f(game)
		case <-ticker.C:
			game.onTick()
		case player := <-game.playerConnect:
			game.onPlayerConnect(player)
		case entityId := <-game.playerDisconnect:
			game.onPlayerDisconnect(entityId)
		}
	}
}

// A new player has connected to the server
func (game *Game) onPlayerConnect(newPlayer *player.Player) {
	game.players[newPlayer.GetEntityId()] = newPlayer
	game.playerNames[newPlayer.Name()] = newPlayer
}

// A player has disconnected from the server
func (game *Game) onPlayerDisconnect(entityId EntityId) {
	oldPlayer := game.players[entityId]
	game.players[entityId] = nil, false
	game.playerNames[oldPlayer.Name()] = nil, false
	game.entityManager.RemoveEntityById(entityId)

	playerData := oldPlayer.WriteNbt()

	if err := game.worldStore.WritePlayerData(oldPlayer.Name(), playerData); err != nil {
		log.Printf("Failed when writing player data: %s", err)
	}
}

func (game *Game) onTick() {
	game.time++
	if game.time%TicksPerSecond == 0 {
		game.sendTimeUpdate()
	}
}

// Negotiate a new player client login. This function runs in a new goroutine
// for each player connection and therefore should not attempt to alter the
// game structure without enqueue().
func (game *Game) login(conn net.Conn) {
	// TODO: This function should access game in a thread-safe way for reading
	var err, clientErr os.Error

	defer func() {
		if err != nil {
			log.Print(err.String())
			if clientErr == nil {
				clientErr = os.NewError("Server error.")
			}
			proto.WriteDisconnect(conn, clientErr.String())
			conn.Close()
		}
	}()

	var username string
	if username, err = proto.ServerReadHandshake(conn); err != nil {
		clientErr = os.NewError("Handshake error.")
		return
	}

	if !validPlayerUsername.MatchString(username) {
		err = os.NewError("Bad username")
		clientErr = err
		return
	}

	log.Print("Client ", conn.RemoteAddr(), " connected as ", username)

	if game.UnderMaintenanceMsg != "" {
		err = fmt.Errorf("Server under maintenance, kicking player: %q", username)
		clientErr = os.NewError(game.UnderMaintenanceMsg)
		return
	}

	// Load player permissions.
	permissions := gamerules.Permissions.UserPermissions(username)
	if !permissions.Has("login") {
		err = fmt.Errorf("Player %q does not have login permission", username)
		clientErr = os.NewError("You do not have access to this server.")
		return
	}

	if err = proto.ServerWriteHandshake(conn, game.serverId); err != nil {
		clientErr = os.NewError("Handshake error.")
		return
	}

	if game.serverId != "-" {
		var authenticated bool
		authserver := &server_auth.ServerAuth{"http://www.minecraft.net/game/checkserver.jsp"}
		authenticated, err = authserver.Authenticate(game.serverId, username)
		if !authenticated || err != nil {
			var reason string
			if err != nil {
				reason = "Authentication check failed: " + err.String()
			} else {
				reason = "Failed authentication"
			}
			err = fmt.Errorf("Client %v: %s", conn.RemoteAddr(), reason)
			clientErr = os.NewError(reason)
			return
		}
		log.Print("Client ", conn.RemoteAddr(), " passed minecraft.net authentication")
	}

	if _, err = proto.ServerReadLogin(conn); err != nil {
		clientErr = os.NewError("Login error.")
		return
	}

	entityId := game.entityManager.NewEntity()

	var playerData nbt.ITag
	if playerData, err = game.worldStore.PlayerData(username); err != nil {
		clientErr = os.NewError("Error reading user data. Please contact the server administrator.")
		return
	}

	player := player.NewPlayer(entityId, game.chunkManager, conn, username, game.worldStore.SpawnPosition, game.playerDisconnect, game)
	if playerData != nil {
		if err = player.ReadNbt(playerData); err != nil {
			// Don't let the player log in, as they will only have default inventory
			// etc., which could lose items from them. Better for an administrator to
			// sort this out.
			err = fmt.Errorf("Error parsing player data for %q: %v", username, err)
			clientErr = os.NewError("Error reading user data. Please contact the server administrator.")
			return
		}
	}

	game.playerConnect <- player
	player.Start()
}

func (game *Game) Serve(addr string) {
	listener, e := net.Listen("tcp", addr)
	if e != nil {
		log.Fatalf("Listen: %s", e.String())
	}
	log.Print("Listening on ", addr)

	for {
		conn, e2 := listener.Accept()
		if e2 != nil {
			log.Print("Accept: ", e2.String())
			break
		}

		go game.login(conn)
	}
}

// Utility functions

// Send a time/keepalive packet
func (game *Game) sendTimeUpdate() {
	buf := new(bytes.Buffer)
	proto.ServerWriteTimeUpdate(buf, game.time)

	// The "keep-alive" packet to client(s) sent here as well, as there
	// seems no particular reason to send time and keep-alive separately
	// for now.
	proto.WriteKeepAlive(buf)

	game.multicastPacket(buf.Bytes(), nil)
}

// Send a packet to every player connected to the server
func (game *Game) multicastPacket(packet []byte, except interface{}) {
	for _, player := range game.players {
		if player == except {
			continue
		}

		player.TransmitPacket(packet)
	}
}

// Safely enqueue some work to be executed at some point in the future
func (game *Game) enqueue(f func(*Game)) {
	game.workQueue <- f
}

// The following functions implement the IGame interface

func (game *Game) BroadcastMessage(msg string) {
	buf := new(bytes.Buffer)
	proto.WriteChatMessage(buf, msg)

	game.enqueue(func(_ *Game) {
		game.multicastPacket(buf.Bytes(), nil)
	})
}

func (game *Game) ItemTypeById(id int) (gamerules.ItemType, bool) {
	itemType, ok := gamerules.Items[ItemTypeId(id)]
	return *itemType, ok
}

func (game *Game) PlayerByEntityId(id EntityId) gamerules.IPlayerClient {
	result := make(chan gamerules.IPlayerClient)
	game.enqueue(func(_ *Game) {
		player, ok := game.players[id]
		if ok {
			result <- player.Client()
		} else {
			result <- nil
		}
		close(result)
	})
	return <-result
}

func (game *Game) PlayerByName(name string) gamerules.IPlayerClient {
	result := make(chan gamerules.IPlayerClient)
	game.enqueue(func(_ *Game) {
		player, ok := game.playerNames[name]
		if ok {
			result <- player.Client()
		} else {
			result <- nil
		}
		close(result)
	})
	return <-result
}

repository: nictuku/chunkymonkey

repo_name: nictuku/chunkymonkey


text:
/*
Copyright © 2018-2023 blacktop

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package dyld

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"github.com/apex/log"
	dscCmd "github.com/blacktop/ipsw/internal/commands/dsc"
	"github.com/blacktop/ipsw/internal/utils"
	"github.com/blacktop/ipsw/pkg/dyld"
	"github.com/fatih/color"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func init() {
	DyldCmd.AddCommand(SymAddrCmd)
	SymAddrCmd.Flags().BoolP("all", "a", false, "Find all symbol matches")
	SymAddrCmd.Flags().BoolP("binds", "b", false, "Also search LC_DYLD_INFO binds")
	SymAddrCmd.Flags().StringP("image", "i", "", "dylib image to search")
	SymAddrCmd.Flags().String("in", "", "Path to JSON file containing list of symbols to lookup")
	SymAddrCmd.Flags().String("out", "", "Path to output JSON file")
	// SymAddrCmd.Flags().StringP("cache", "c", "", "path to addr to sym cache file")
	SymAddrCmd.MarkZshCompPositionalArgumentFile(1, "dyld_shared_cache*")
}

// SymAddrCmd represents the symaddr command
var SymAddrCmd = &cobra.Command{
	Use:           "symaddr <dyld_shared_cache>",
	Aliases:       []string{"sym"},
	Short:         "Lookup or dump symbol(s)",
	SilenceUsage:  false,
	SilenceErrors: true,
	Args:          cobra.MinimumNArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {

		if viper.GetBool("verbose") {
			log.SetLevel(log.DebugLevel)
		}
		color.NoColor = !viper.GetBool("color")

		imageName, _ := cmd.Flags().GetString("image")
		symbolFile, _ := cmd.Flags().GetString("in")
		jsonFile, _ := cmd.Flags().GetString("out")
		allMatches, _ := cmd.Flags().GetBool("all")
		showBinds, _ := cmd.Flags().GetBool("binds")

		dscPath := filepath.Clean(args[0])

		fileInfo, err := os.Lstat(dscPath)
		if err != nil {
			return fmt.Errorf("file %s does not exist", dscPath)
		}

		// Check if file is a symlink
		if fileInfo.Mode()&os.ModeSymlink != 0 {
			symlinkPath, err := os.Readlink(dscPath)
			if err != nil {
				return errors.Wrapf(err, "failed to read symlink %s", dscPath)
			}
			// TODO: this seems like it would break
			linkParent := filepath.Dir(dscPath)
			linkRoot := filepath.Dir(linkParent)

			dscPath = filepath.Join(linkRoot, symlinkPath)
		}

		f, err := dyld.Open(dscPath)
		if err != nil {
			return err
		}
		defer f.Close()

		if len(symbolFile) > 0 {
			/******************************************
			 * Search for symbols in JSON lookup file *
			 ******************************************/
			var lookups []dscCmd.Symbol

			lookupData, err := os.ReadFile(filepath.Clean(symbolFile))
			if err != nil {
				return fmt.Errorf("failed to read symbol lookup JSON file %s: %v", symbolFile, err)
			}
			if err := json.Unmarshal(lookupData, &lookups); err != nil {
				return fmt.Errorf("failed to parse symbol lookup JSON file %s: %v", symbolFile, err)
			}

			syms, err := dscCmd.GetSymbols(f, lookups)
			if err != nil {
				return fmt.Errorf("failed to lookup symbols from lookup JSON file: %v", err)
			}

			var enc *json.Encoder
			if len(jsonFile) > 0 {
				jf, err := os.Create(jsonFile)
				if err != nil {
					return err
				}
				defer jf.Close()
				enc = json.NewEncoder(jf)
			} else {
				enc = json.NewEncoder(os.Stdout)
			}

			if err := enc.Encode(syms); err != nil {
				return err
			}

			return nil
		} else if len(args) > 1 {
			if len(imageName) > 0 {
				/**********************************
				 * Search for symbol inside dylib *
				 **********************************/
				i, err := f.Image(imageName)
				if err != nil {
					return fmt.Errorf("image not in %s: %v", dscPath, err)
				}

				if lsym, err := i.GetSymbol(args[1]); err == nil {
					fmt.Println(lsym.String(viper.GetBool("color")))
				}

				// if lsym, err := i.GetLocalSymbol(args[1]); err == nil {
				// 	fmt.Println(lsym)
				// }
				// if lsym, err := i.GetPublicSymbol(args[1]); err == nil {
				// 	fmt.Println(lsym)
				// }
				// if export, err := i.GetExport(args[1]); err == nil {
				// 	fmt.Println(export)
				// }

				return nil
			}
			/**********************************
			 * Search ALL dylibs for a symbol *
			 **********************************/
			symChan, err := f.GetExportedSymbols(context.Background(), args[1])
			if err != nil {
				if !errors.Is(err, dyld.ErrNoPrebuiltLoadersInCache) {
					return fmt.Errorf("failed to get exported symbols: %v", err)
				}
			} else {
				for {
					sym, ok := <-symChan
					if !ok {
						break
					}
					fmt.Println(sym.String(viper.GetBool("color")))
					if !allMatches {
						return nil
					}
				}
			}
			for _, image := range f.Images { // use brute force search
				utils.Indent(log.Debug, 2)("Searching " + image.Name)
				if sym, err := image.GetSymbol(args[1]); err == nil {
					if (sym.Address > 0 || allMatches) && (sym.Kind != dyld.BIND || showBinds) {
						fmt.Println(sym.String(viper.GetBool("color")))
						if !allMatches {
							return nil
						}
					}
				}
			}
			return nil
		} else if len(imageName) > 0 {
			/*************************
			* Dump all dylib symbols *
			**************************/
			i, err := f.Image(imageName)
			if err != nil {
				return fmt.Errorf("image not in %s: %v", dscPath, err)
			}

			log.Warn("parsing private symbols for image...")
			if err := i.ParseLocalSymbols(true); err != nil {
				if errors.Is(err, dyld.ErrNoLocals) {
					utils.Indent(log.Warn, 2)(err.Error())
				} else if err != nil {
					log.Errorf("failed parse private symbols for image %s: %v", i.Name, err)
				}
			}

			log.Warn("parsing public symbols for image...")
			if err := i.ParsePublicSymbols(true); err != nil {
				log.Errorf("failed to parse public symbols for image %s: %v", i.Name, err)
			}

			return nil
		}
		/******************
		* Dump ALL symbols*
		*******************/
		log.Warn("parsing public symbols...")
		if err = f.ParsePublicSymbols(true); err != nil {
			log.Errorf("failed to get all public symbols: %v", err)
		}

		log.Warn("parsing private symbols...")
		if err = f.ParseLocalSyms(true); err != nil {
			log.Errorf("failed to parse private symbols: %v", err)
		}

		return nil
	},
}

repository: blacktop/ipsw

repo_name: blacktop/ipsw


text:
SUMMARY = "i.MX M4 coprocessor images"
SECTION = "app"
LICENSE = "GPL-2.0"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/GPL-2.0;md5=801f80980d171dd6425610833a22dbe6"

SRC_URI = "file://coprocessor.elf \
"
S = "${WORKDIR}"

do_install () {
    # install elf format binary to /lib/firmware
    install -d ${D}/lib/firmware
    install -m 0644 ${S}/coprocessor.elf ${D}/lib/firmware/coprocessor.elf
}

FILES_${PN} = "/lib/firmware/coprocessor.elf"

repository: embedded-specialties/meta-esi

repo_name: embedded-specialties/meta-esi