text:
// This is a modified version of Modgraphviz created by the Go authors.
// Original Modgraphviz resides in the experimental repository.
// https://github.com/golang/exp/tree/master/cmd/modgraphviz

package modgv

import (
	"bytes"
	"fmt"
	"io"
	"strings"

	"github.com/lucasepe/modgv/text"
)

// Render translates “go mod graph” output taken from
// the 'in' reader into Graphviz's DOT language, writing
// to the 'out' writer.
func Render(in io.Reader, out io.Writer) error {
	graph, err := convert(in)
	if err != nil {
		return err
	}

	fmt.Fprintf(out, "digraph gomodgraph {\n")
	fmt.Fprintf(out, "\tpad=1;\n")
	fmt.Fprintf(out, "\trankdir=TB;\n")
	fmt.Fprintf(out, "\tranksep=\"1.2 equally\";\n")
	fmt.Fprintf(out, "\tsplines=ortho;\n")
	fmt.Fprintf(out, "\tnodesep=\"0.8\";\n")
	fmt.Fprintf(out, "\tnode [shape=plaintext style=\"filled,rounded\" penwidth=2 fontsize=12 fontname=\"monospace\"];\n")

	fmt.Fprintf(out, "\t%q [shape=underline style=\"\" fontsize=14 label=<%s>];\n", graph.root, graph.root)

	for _, n := range graph.mvsPicked {
		fmt.Fprintf(out, "\t%q [fillcolor=\"#0c5525\" label=<%s>];\n", n, textToHTML(n, "#fafafa"))
	}
	for _, n := range graph.mvsUnpicked {
		fmt.Fprintf(out, "\t%q [fillcolor=\"#a3a3a3\" label=<%s>];\n", n, textToHTML(n, "#0e0e0e"))
	}
	out.Write(edgesAsDOT(graph))

	fmt.Fprintf(out, "}\n")

	return nil
}

// edgesAsDOT returns the edges in DOT notation.
func edgesAsDOT(gr *graph) []byte {
	var buf bytes.Buffer
	for _, e := range gr.edges {
		fmt.Fprintf(&buf, "\t%q -> %q", e.from, e.to)
		if _, ok := text.Find(gr.mvsUnpicked, e.to); ok {
			fmt.Fprintf(&buf, "[style=dashed]")
		}
		fmt.Fprintf(&buf, ";\n")
	}
	return buf.Bytes()
}

// textToHTML converts the line with module@version
// in a colored HTML table
func textToHTML(line string, color string) string {
	var mod, ver string
	if i := strings.IndexByte(line, '@'); i >= 0 {
		mod, ver = line[:i], line[i+1:]
	}

	u := fmt.Sprintf(`href="https://pkg.go.dev/%s?tab=doc"`, mod)

	var sb strings.Builder
	sb.WriteString(`<table border="0" cellspacing="8" `)
	if mod != "" {
		sb.WriteString(u)
	}
	sb.WriteString(`>`)
	if len(mod) > 0 {
		sb.WriteString(`<tr><td><font color="`)
		sb.WriteString(color)
		sb.WriteString(`"><b>`)
		sb.WriteString(mod)
		sb.WriteString("
")
	}

	if len(ver) > 0 {
		sb.WriteString(`<tr><td><font color="`)
		sb.WriteString(color)
		sb.WriteString(`" point-size="10">`)
		sb.WriteString(ver)
		sb.WriteString("
")
	}
	sb.WriteString("
")

	return sb.String()
}

repository: jpalardy/modgv

repo_name: jpalardy/modgv


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

package firewall_policies

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

import (
	"fmt"
	"io"

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

	"github.com/crowdstrike/gofalcon/falcon/models"
)

// SetFirewallPoliciesPrecedenceReader is a Reader for the SetFirewallPoliciesPrecedence structure.
type SetFirewallPoliciesPrecedenceReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *SetFirewallPoliciesPrecedenceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {
	case 200:
		result := NewSetFirewallPoliciesPrecedenceOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil
	case 400:
		result := NewSetFirewallPoliciesPrecedenceBadRequest()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 403:
		result := NewSetFirewallPoliciesPrecedenceForbidden()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 429:
		result := NewSetFirewallPoliciesPrecedenceTooManyRequests()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 500:
		result := NewSetFirewallPoliciesPrecedenceInternalServerError()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	default:
		return nil, runtime.NewAPIError("[POST /policy/entities/firewall-precedence/v1] setFirewallPoliciesPrecedence", response, response.Code())
	}
}

// NewSetFirewallPoliciesPrecedenceOK creates a SetFirewallPoliciesPrecedenceOK with default headers values
func NewSetFirewallPoliciesPrecedenceOK() *SetFirewallPoliciesPrecedenceOK {
	return &SetFirewallPoliciesPrecedenceOK{}
}

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

OK
*/
type SetFirewallPoliciesPrecedenceOK struct {

	/* Trace-ID: submit to support if resolving an issue
	 */
	XCSTRACEID string

	/* Request limit per minute.
	 */
	XRateLimitLimit int64

	/* The number of requests remaining for the sliding one minute window.
	 */
	XRateLimitRemaining int64

	Payload *models.MsaQueryResponse
}

// IsSuccess returns true when this set firewall policies precedence o k response has a 2xx status code
func (o *SetFirewallPoliciesPrecedenceOK) IsSuccess() bool {
	return true
}

// IsRedirect returns true when this set firewall policies precedence o k response has a 3xx status code
func (o *SetFirewallPoliciesPrecedenceOK) IsRedirect() bool {
	return false
}

// IsClientError returns true when this set firewall policies precedence o k response has a 4xx status code
func (o *SetFirewallPoliciesPrecedenceOK) IsClientError() bool {
	return false
}

// IsServerError returns true when this set firewall policies precedence o k response has a 5xx status code
func (o *SetFirewallPoliciesPrecedenceOK) IsServerError() bool {
	return false
}

// IsCode returns true when this set firewall policies precedence o k response a status code equal to that given
func (o *SetFirewallPoliciesPrecedenceOK) IsCode(code int) bool {
	return code == 200
}

// Code gets the status code for the set firewall policies precedence o k response
func (o *SetFirewallPoliciesPrecedenceOK) Code() int {
	return 200
}

func (o *SetFirewallPoliciesPrecedenceOK) Error() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceOK  %+v", 200, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceOK) String() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceOK  %+v", 200, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceOK) GetPayload() *models.MsaQueryResponse {
	return o.Payload
}

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

	// hydrates response header X-CS-TRACEID
	hdrXCSTRACEID := response.GetHeader("X-CS-TRACEID")

	if hdrXCSTRACEID != "" {
		o.XCSTRACEID = hdrXCSTRACEID
	}

	// hydrates response header X-RateLimit-Limit
	hdrXRateLimitLimit := response.GetHeader("X-RateLimit-Limit")

	if hdrXRateLimitLimit != "" {
		valxRateLimitLimit, err := swag.ConvertInt64(hdrXRateLimitLimit)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Limit", "header", "int64", hdrXRateLimitLimit)
		}
		o.XRateLimitLimit = valxRateLimitLimit
	}

	// hydrates response header X-RateLimit-Remaining
	hdrXRateLimitRemaining := response.GetHeader("X-RateLimit-Remaining")

	if hdrXRateLimitRemaining != "" {
		valxRateLimitRemaining, err := swag.ConvertInt64(hdrXRateLimitRemaining)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Remaining", "header", "int64", hdrXRateLimitRemaining)
		}
		o.XRateLimitRemaining = valxRateLimitRemaining
	}

	o.Payload = new(models.MsaQueryResponse)

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

	return nil
}

// NewSetFirewallPoliciesPrecedenceBadRequest creates a SetFirewallPoliciesPrecedenceBadRequest with default headers values
func NewSetFirewallPoliciesPrecedenceBadRequest() *SetFirewallPoliciesPrecedenceBadRequest {
	return &SetFirewallPoliciesPrecedenceBadRequest{}
}

/*
SetFirewallPoliciesPrecedenceBadRequest describes a response with status code 400, with default header values.

Bad Request
*/
type SetFirewallPoliciesPrecedenceBadRequest struct {

	/* Trace-ID: submit to support if resolving an issue
	 */
	XCSTRACEID string

	/* Request limit per minute.
	 */
	XRateLimitLimit int64

	/* The number of requests remaining for the sliding one minute window.
	 */
	XRateLimitRemaining int64

	Payload *models.MsaQueryResponse
}

// IsSuccess returns true when this set firewall policies precedence bad request response has a 2xx status code
func (o *SetFirewallPoliciesPrecedenceBadRequest) IsSuccess() bool {
	return false
}

// IsRedirect returns true when this set firewall policies precedence bad request response has a 3xx status code
func (o *SetFirewallPoliciesPrecedenceBadRequest) IsRedirect() bool {
	return false
}

// IsClientError returns true when this set firewall policies precedence bad request response has a 4xx status code
func (o *SetFirewallPoliciesPrecedenceBadRequest) IsClientError() bool {
	return true
}

// IsServerError returns true when this set firewall policies precedence bad request response has a 5xx status code
func (o *SetFirewallPoliciesPrecedenceBadRequest) IsServerError() bool {
	return false
}

// IsCode returns true when this set firewall policies precedence bad request response a status code equal to that given
func (o *SetFirewallPoliciesPrecedenceBadRequest) IsCode(code int) bool {
	return code == 400
}

// Code gets the status code for the set firewall policies precedence bad request response
func (o *SetFirewallPoliciesPrecedenceBadRequest) Code() int {
	return 400
}

func (o *SetFirewallPoliciesPrecedenceBadRequest) Error() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceBadRequest  %+v", 400, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceBadRequest) String() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceBadRequest  %+v", 400, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceBadRequest) GetPayload() *models.MsaQueryResponse {
	return o.Payload
}

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

	// hydrates response header X-CS-TRACEID
	hdrXCSTRACEID := response.GetHeader("X-CS-TRACEID")

	if hdrXCSTRACEID != "" {
		o.XCSTRACEID = hdrXCSTRACEID
	}

	// hydrates response header X-RateLimit-Limit
	hdrXRateLimitLimit := response.GetHeader("X-RateLimit-Limit")

	if hdrXRateLimitLimit != "" {
		valxRateLimitLimit, err := swag.ConvertInt64(hdrXRateLimitLimit)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Limit", "header", "int64", hdrXRateLimitLimit)
		}
		o.XRateLimitLimit = valxRateLimitLimit
	}

	// hydrates response header X-RateLimit-Remaining
	hdrXRateLimitRemaining := response.GetHeader("X-RateLimit-Remaining")

	if hdrXRateLimitRemaining != "" {
		valxRateLimitRemaining, err := swag.ConvertInt64(hdrXRateLimitRemaining)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Remaining", "header", "int64", hdrXRateLimitRemaining)
		}
		o.XRateLimitRemaining = valxRateLimitRemaining
	}

	o.Payload = new(models.MsaQueryResponse)

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

	return nil
}

// NewSetFirewallPoliciesPrecedenceForbidden creates a SetFirewallPoliciesPrecedenceForbidden with default headers values
func NewSetFirewallPoliciesPrecedenceForbidden() *SetFirewallPoliciesPrecedenceForbidden {
	return &SetFirewallPoliciesPrecedenceForbidden{}
}

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

Forbidden
*/
type SetFirewallPoliciesPrecedenceForbidden struct {

	/* Trace-ID: submit to support if resolving an issue
	 */
	XCSTRACEID string

	/* Request limit per minute.
	 */
	XRateLimitLimit int64

	/* The number of requests remaining for the sliding one minute window.
	 */
	XRateLimitRemaining int64

	Payload *models.MsaErrorsOnly
}

// IsSuccess returns true when this set firewall policies precedence forbidden response has a 2xx status code
func (o *SetFirewallPoliciesPrecedenceForbidden) IsSuccess() bool {
	return false
}

// IsRedirect returns true when this set firewall policies precedence forbidden response has a 3xx status code
func (o *SetFirewallPoliciesPrecedenceForbidden) IsRedirect() bool {
	return false
}

// IsClientError returns true when this set firewall policies precedence forbidden response has a 4xx status code
func (o *SetFirewallPoliciesPrecedenceForbidden) IsClientError() bool {
	return true
}

// IsServerError returns true when this set firewall policies precedence forbidden response has a 5xx status code
func (o *SetFirewallPoliciesPrecedenceForbidden) IsServerError() bool {
	return false
}

// IsCode returns true when this set firewall policies precedence forbidden response a status code equal to that given
func (o *SetFirewallPoliciesPrecedenceForbidden) IsCode(code int) bool {
	return code == 403
}

// Code gets the status code for the set firewall policies precedence forbidden response
func (o *SetFirewallPoliciesPrecedenceForbidden) Code() int {
	return 403
}

func (o *SetFirewallPoliciesPrecedenceForbidden) Error() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceForbidden  %+v", 403, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceForbidden) String() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceForbidden  %+v", 403, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceForbidden) GetPayload() *models.MsaErrorsOnly {
	return o.Payload
}

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

	// hydrates response header X-CS-TRACEID
	hdrXCSTRACEID := response.GetHeader("X-CS-TRACEID")

	if hdrXCSTRACEID != "" {
		o.XCSTRACEID = hdrXCSTRACEID
	}

	// hydrates response header X-RateLimit-Limit
	hdrXRateLimitLimit := response.GetHeader("X-RateLimit-Limit")

	if hdrXRateLimitLimit != "" {
		valxRateLimitLimit, err := swag.ConvertInt64(hdrXRateLimitLimit)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Limit", "header", "int64", hdrXRateLimitLimit)
		}
		o.XRateLimitLimit = valxRateLimitLimit
	}

	// hydrates response header X-RateLimit-Remaining
	hdrXRateLimitRemaining := response.GetHeader("X-RateLimit-Remaining")

	if hdrXRateLimitRemaining != "" {
		valxRateLimitRemaining, err := swag.ConvertInt64(hdrXRateLimitRemaining)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Remaining", "header", "int64", hdrXRateLimitRemaining)
		}
		o.XRateLimitRemaining = valxRateLimitRemaining
	}

	o.Payload = new(models.MsaErrorsOnly)

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

	return nil
}

// NewSetFirewallPoliciesPrecedenceTooManyRequests creates a SetFirewallPoliciesPrecedenceTooManyRequests with default headers values
func NewSetFirewallPoliciesPrecedenceTooManyRequests() *SetFirewallPoliciesPrecedenceTooManyRequests {
	return &SetFirewallPoliciesPrecedenceTooManyRequests{}
}

/*
SetFirewallPoliciesPrecedenceTooManyRequests describes a response with status code 429, with default header values.

Too Many Requests
*/
type SetFirewallPoliciesPrecedenceTooManyRequests struct {

	/* Trace-ID: submit to support if resolving an issue
	 */
	XCSTRACEID string

	/* Request limit per minute.
	 */
	XRateLimitLimit int64

	/* The number of requests remaining for the sliding one minute window.
	 */
	XRateLimitRemaining int64

	/* Too many requests, retry after this time (as milliseconds since epoch)
	 */
	XRateLimitRetryAfter int64

	Payload *models.MsaReplyMetaOnly
}

// IsSuccess returns true when this set firewall policies precedence too many requests response has a 2xx status code
func (o *SetFirewallPoliciesPrecedenceTooManyRequests) IsSuccess() bool {
	return false
}

// IsRedirect returns true when this set firewall policies precedence too many requests response has a 3xx status code
func (o *SetFirewallPoliciesPrecedenceTooManyRequests) IsRedirect() bool {
	return false
}

// IsClientError returns true when this set firewall policies precedence too many requests response has a 4xx status code
func (o *SetFirewallPoliciesPrecedenceTooManyRequests) IsClientError() bool {
	return true
}

// IsServerError returns true when this set firewall policies precedence too many requests response has a 5xx status code
func (o *SetFirewallPoliciesPrecedenceTooManyRequests) IsServerError() bool {
	return false
}

// IsCode returns true when this set firewall policies precedence too many requests response a status code equal to that given
func (o *SetFirewallPoliciesPrecedenceTooManyRequests) IsCode(code int) bool {
	return code == 429
}

// Code gets the status code for the set firewall policies precedence too many requests response
func (o *SetFirewallPoliciesPrecedenceTooManyRequests) Code() int {
	return 429
}

func (o *SetFirewallPoliciesPrecedenceTooManyRequests) Error() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceTooManyRequests  %+v", 429, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceTooManyRequests) String() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceTooManyRequests  %+v", 429, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceTooManyRequests) GetPayload() *models.MsaReplyMetaOnly {
	return o.Payload
}

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

	// hydrates response header X-CS-TRACEID
	hdrXCSTRACEID := response.GetHeader("X-CS-TRACEID")

	if hdrXCSTRACEID != "" {
		o.XCSTRACEID = hdrXCSTRACEID
	}

	// hydrates response header X-RateLimit-Limit
	hdrXRateLimitLimit := response.GetHeader("X-RateLimit-Limit")

	if hdrXRateLimitLimit != "" {
		valxRateLimitLimit, err := swag.ConvertInt64(hdrXRateLimitLimit)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Limit", "header", "int64", hdrXRateLimitLimit)
		}
		o.XRateLimitLimit = valxRateLimitLimit
	}

	// hydrates response header X-RateLimit-Remaining
	hdrXRateLimitRemaining := response.GetHeader("X-RateLimit-Remaining")

	if hdrXRateLimitRemaining != "" {
		valxRateLimitRemaining, err := swag.ConvertInt64(hdrXRateLimitRemaining)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Remaining", "header", "int64", hdrXRateLimitRemaining)
		}
		o.XRateLimitRemaining = valxRateLimitRemaining
	}

	// hydrates response header X-RateLimit-RetryAfter
	hdrXRateLimitRetryAfter := response.GetHeader("X-RateLimit-RetryAfter")

	if hdrXRateLimitRetryAfter != "" {
		valxRateLimitRetryAfter, err := swag.ConvertInt64(hdrXRateLimitRetryAfter)
		if err != nil {
			return errors.InvalidType("X-RateLimit-RetryAfter", "header", "int64", hdrXRateLimitRetryAfter)
		}
		o.XRateLimitRetryAfter = valxRateLimitRetryAfter
	}

	o.Payload = new(models.MsaReplyMetaOnly)

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

	return nil
}

// NewSetFirewallPoliciesPrecedenceInternalServerError creates a SetFirewallPoliciesPrecedenceInternalServerError with default headers values
func NewSetFirewallPoliciesPrecedenceInternalServerError() *SetFirewallPoliciesPrecedenceInternalServerError {
	return &SetFirewallPoliciesPrecedenceInternalServerError{}
}

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

Internal Server Error
*/
type SetFirewallPoliciesPrecedenceInternalServerError struct {

	/* Trace-ID: submit to support if resolving an issue
	 */
	XCSTRACEID string

	/* Request limit per minute.
	 */
	XRateLimitLimit int64

	/* The number of requests remaining for the sliding one minute window.
	 */
	XRateLimitRemaining int64

	Payload *models.MsaQueryResponse
}

// IsSuccess returns true when this set firewall policies precedence internal server error response has a 2xx status code
func (o *SetFirewallPoliciesPrecedenceInternalServerError) IsSuccess() bool {
	return false
}

// IsRedirect returns true when this set firewall policies precedence internal server error response has a 3xx status code
func (o *SetFirewallPoliciesPrecedenceInternalServerError) IsRedirect() bool {
	return false
}

// IsClientError returns true when this set firewall policies precedence internal server error response has a 4xx status code
func (o *SetFirewallPoliciesPrecedenceInternalServerError) IsClientError() bool {
	return false
}

// IsServerError returns true when this set firewall policies precedence internal server error response has a 5xx status code
func (o *SetFirewallPoliciesPrecedenceInternalServerError) IsServerError() bool {
	return true
}

// IsCode returns true when this set firewall policies precedence internal server error response a status code equal to that given
func (o *SetFirewallPoliciesPrecedenceInternalServerError) IsCode(code int) bool {
	return code == 500
}

// Code gets the status code for the set firewall policies precedence internal server error response
func (o *SetFirewallPoliciesPrecedenceInternalServerError) Code() int {
	return 500
}

func (o *SetFirewallPoliciesPrecedenceInternalServerError) Error() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceInternalServerError  %+v", 500, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceInternalServerError) String() string {
	return fmt.Sprintf("[POST /policy/entities/firewall-precedence/v1][%d] setFirewallPoliciesPrecedenceInternalServerError  %+v", 500, o.Payload)
}

func (o *SetFirewallPoliciesPrecedenceInternalServerError) GetPayload() *models.MsaQueryResponse {
	return o.Payload
}

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

	// hydrates response header X-CS-TRACEID
	hdrXCSTRACEID := response.GetHeader("X-CS-TRACEID")

	if hdrXCSTRACEID != "" {
		o.XCSTRACEID = hdrXCSTRACEID
	}

	// hydrates response header X-RateLimit-Limit
	hdrXRateLimitLimit := response.GetHeader("X-RateLimit-Limit")

	if hdrXRateLimitLimit != "" {
		valxRateLimitLimit, err := swag.ConvertInt64(hdrXRateLimitLimit)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Limit", "header", "int64", hdrXRateLimitLimit)
		}
		o.XRateLimitLimit = valxRateLimitLimit
	}

	// hydrates response header X-RateLimit-Remaining
	hdrXRateLimitRemaining := response.GetHeader("X-RateLimit-Remaining")

	if hdrXRateLimitRemaining != "" {
		valxRateLimitRemaining, err := swag.ConvertInt64(hdrXRateLimitRemaining)
		if err != nil {
			return errors.InvalidType("X-RateLimit-Remaining", "header", "int64", hdrXRateLimitRemaining)
		}
		o.XRateLimitRemaining = valxRateLimitRemaining
	}

	o.Payload = new(models.MsaQueryResponse)

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

	return nil
}

license: MIT

repository: CrowdStrike/gofalcon

license_type: permissive

repo_name: CrowdStrike/gofalcon

branch_name: refs/heads/main

gha_license_id: MIT

gha_language: Go

extension: go


text:
package log

import (
	"encoding/json"
	"fmt"
	"reflect"
	"time"

	"github.com/sirupsen/logrus"
)

// FluentdFormatter is similar to logrus.JSONFormatter but with log level that are recongnized
// by kubernetes fluentd.
type FluentdFormatter struct {
	TimestampFormat string
}

// Format the log entry. Implements logrus.Formatter.
func (f *FluentdFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	data := make(logrus.Fields, len(entry.Data)+3)
	for k, v := range entry.Data {
		data[k] = Value(v)
	}
	prefixFieldClashes(data)

	timestampFormat := f.TimestampFormat
	if timestampFormat == "" {
		timestampFormat = time.RFC3339
	}

	data["time"] = entry.Time.Format(timestampFormat)
	data["message"] = entry.Message
	data["severity"] = entry.Level.String()

	serialized, err := json.Marshal(data)
	if err != nil {
		return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
	}
	return append(serialized, '\n'), nil
}

// Value handle field value depends on its type
func Value(i interface{}) interface{} {
	v := reflect.ValueOf(i)
	kind := v.Kind()
	if v, ok := i.(error); ok {
		return v.Error()
	}
	if kind == reflect.Ptr {
		if !v.Elem().IsValid() {
			return nil
		}
		return Value(v.Elem().Interface())
	}
	// handle basic type
	if kind < reflect.Array {
		return i
	}
	// handle string type
	if kind == reflect.String {
		return i
	}
	// handle type implement fmt.Stringer
	if s, ok := i.(fmt.Stringer); ok {
		return s.String()
	}
	if kind == reflect.Array || kind == reflect.Map || kind == reflect.Slice || kind == reflect.Struct {
		return fmt.Sprintf("%+v", i)
	}
	return i
}

func prefixFieldClashes(data logrus.Fields) {
	if t, ok := data["time"]; ok {
		data["fields.time"] = t
	}

	if m, ok := data["msg"]; ok {
		data["fields.msg"] = m
	}

	if l, ok := data["level"]; ok {
		data["fields.level"] = l
	}
}

repository: micanzhang/log

repo_name: micanzhang/log

branch_name: refs/heads/master


text:
package genwriter

import (
	"fmt"
	"io"

	"github.com/clipperhouse/gen/typewriter"
	"github.com/clipperhouse/inflect"
)

func init() {
	err := typewriter.Register(NewGenWriter())
	if err != nil {
		panic(err)
	}
}

type GenWriter struct {
	// Type is not comparable, use .String() as keys instead
	models    map[string]model
	validated map[string]bool
}

func NewGenWriter() *GenWriter {
	return &GenWriter{
		models:    make(map[string]model),
		validated: make(map[string]bool),
	}
}

// A convenience struct for passing data to templates.
type model struct {
	typewriter.Type
	methods     []string
	projections []Projection
}

func (m model) Plural() (result string) {
	result = inflect.Pluralize(m.Name)
	if result == m.Name {
		result += "s"
	}
	return
}

// genwriter prepares models for later use in the .Validate() method. It must be called prior.
func (g *GenWriter) ensureValidation(t typewriter.Type) error {
	if !g.validated[t.String()] {
		return fmt.Errorf("Type '%s' has not been previously validated. TypeWriter.Validate() must be called on all types before using them in subsequent methods.", t.String())
	}

	return nil
}

func (g *GenWriter) Name() string {
	return "gen"
}

func (g *GenWriter) Validate(t typewriter.Type) (bool, error) {
	standardMethods, projectionMethods, err := evaluateTags(t)
	if err != nil {
		return false, err
	}

	// filter methods applicable to type
	for _, s := range standardMethods {
		tmpl, ok := standardTemplates[s]

		if !ok {
			err = fmt.Errorf("unknown method %v on type %s", s, t.String())
			return false, err
		}

		if !tmpl.ApplicableTo(t) {
			standardMethods = remove(standardMethods, s)
		}
	}

	projectionTag, found, err := t.Tags.ByName("projections")

	if err != nil {
		return false, err
	}

	m := model{
		Type:    t,
		methods: standardMethods,
	}

	if found {
		for _, s := range projectionTag.Items {
			projectionType, err := t.Package.Eval(s)

			if err != nil {
				return false, fmt.Errorf("unable to identify type %s, projected on %s (%s)", s, t.Name, err)
			}

			for _, pm := range projectionMethods {
				tmpl, ok := projectionTemplates[pm]

				if !ok {
					return false, fmt.Errorf("unknown projection method %v", pm)
				}

				if tmpl.ApplicableTo(projectionType) {
					m.projections = append(m.projections, Projection{
						Method: pm,
						Type:   s,
						Parent: &m,
					})
				}
			}
		}
	}

	g.validated[t.String()] = true

	// only add to models if we are going to do something with it
	if len(m.methods) > 0 || len(m.projections) > 0 {
		g.models[t.String()] = m
	}

	return true, nil
}

func (g *GenWriter) WriteHeader(w io.Writer, t typewriter.Type) {
	err := g.ensureValidation(t)

	if err != nil {
		panic(err)
	}

	m, exists := g.models[t.String()]

	if !exists {
		return
	}

	s := `// See http://clipperhouse.github.io/gen for documentation

`
	w.Write([]byte(s))

	if includeSortSupport(m.methods) {
		s := `// Sort implementation is a modification of http://golang.org/pkg/sort/#Sort
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found at http://golang.org/LICENSE.

`
		w.Write([]byte(s))
	}

	return
}

func (g *GenWriter) Imports(t typewriter.Type) (result []typewriter.ImportSpec) {
	err := g.ensureValidation(t)

	if err != nil {
		panic(err)
	}

	m, exists := g.models[t.String()]

	if !exists {
		return
	}

	imports := make(map[string]bool)

	methodRequiresErrors := map[string]bool{
		"First":   true,
		"Single":  true,
		"Max":     true,
		"Min":     true,
		"MaxBy":   true,
		"MinBy":   true,
		"Average": true,
	}

	methodRequiresSort := map[string]bool{
		"Sort": true,
	}

	for _, s := range m.methods {
		if methodRequiresErrors[s] {
			imports["errors"] = true
		}
		if methodRequiresSort[s] {
			imports["sort"] = true
		}
	}

	for _, p := range m.projections {
		if methodRequiresErrors[p.Method] {
			imports["errors"] = true
		}
		if methodRequiresSort[p.Method] {
			imports["sort"] = true
		}
	}

	for s := range imports {
		result = append(result, typewriter.ImportSpec{
			Path: s,
		})
	}

	return
}

func (g *GenWriter) WriteBody(w io.Writer, t typewriter.Type) {
	err := g.ensureValidation(t)

	if err != nil {
		panic(err)
	}

	m, exists := g.models[t.String()]

	if !exists {
		return
	}

	tmpl, _ := standardTemplates.Get("plural")
	if err := tmpl.Execute(w, m); err != nil {
		panic(err)
	}

	for _, s := range m.methods {
		tmpl, _ := standardTemplates.Get(s) // already validated above
		err := tmpl.Execute(w, m)
		if err != nil {
			panic(err)
		}
	}

	for _, p := range m.projections {
		tmpl, _ := projectionTemplates.Get(p.Method) // already validated above
		err := tmpl.Execute(w, p)
		if err != nil {
			panic(err)
		}
	}

	if includeSortInterface(m.methods) {
		tmpl, _ := standardTemplates.Get("sortInterface") // already validated above
		err := tmpl.Execute(w, m)
		if err != nil {
			panic(err)
		}
	}

	if includeSortSupport(m.methods) {
		tmpl, _ := standardTemplates.Get("sortSupport") // already validated above
		err := tmpl.Execute(w, m)
		if err != nil {
			panic(err)
		}
	}
}

repository: gfoxiii/gen

repo_name: gfoxiii/gen


text:
package geojson

import (
	"math"

	"github.com/tidwall/geojson/geometry"
	"github.com/tidwall/gjson"
)

type Point struct {
	base  geometry.Point
	extra *extra
}

func NewPoint(point geometry.Point) *Point {
	return &Point{base: point}
}

func NewPointZ(point geometry.Point, z float64) *Point {
	return &Point{
		base:  point,
		extra: &extra{dims: 1, values: []float64{z}},
	}
}

func (g *Point) ForEach(iter func(geom Object) bool) bool {
	return iter(g)
}

func (g *Point) Empty() bool {
	return g.base.Empty()
}

func (g *Point) Valid() bool {
	return g.base.Valid()
}

func (g *Point) Rect() geometry.Rect {
	return g.base.Rect()
}

func (g *Point) Spatial() Spatial {
	return g
}

func (g *Point) Center() geometry.Point {
	return g.base
}

func (g *Point) Base() geometry.Point {
	return g.base
}

func (g *Point) AppendJSON(dst []byte) []byte {
	dst = append(dst, `{"type":"Point","coordinates":`...)
	dst = appendJSONPoint(dst, g.base, g.extra, 0)
	dst = g.extra.appendJSONExtra(dst, false)
	dst = append(dst, '}')
	return dst
}

func (g *Point) JSON() string {
	return string(g.AppendJSON(nil))
}

func (g *Point) MarshalJSON() ([]byte, error) {
	return g.AppendJSON(nil), nil
}

func (g *Point) String() string {
	return string(g.AppendJSON(nil))
}

func (g *Point) Within(obj Object) bool {
	return obj.Contains(g)
}

func (g *Point) Contains(obj Object) bool {
	return obj.Spatial().WithinPoint(g.base)
}

func (g *Point) Intersects(obj Object) bool {
	if obj, ok := obj.(*Circle); ok {
		return obj.Contains(g)
	}
	return obj.Spatial().IntersectsPoint(g.base)
}

func (g *Point) WithinRect(rect geometry.Rect) bool {
	return rect.ContainsPoint(g.base)
}

func (g *Point) WithinPoint(point geometry.Point) bool {
	return point.ContainsPoint(g.base)
}

func (g *Point) WithinLine(line *geometry.Line) bool {
	return line.ContainsPoint(g.base)
}

func (g *Point) WithinPoly(poly *geometry.Poly) bool {
	return poly.ContainsPoint(g.base)
}

func (g *Point) IntersectsPoint(point geometry.Point) bool {
	return g.base.IntersectsPoint(point)
}

func (g *Point) IntersectsRect(rect geometry.Rect) bool {
	return g.base.IntersectsRect(rect)
}

func (g *Point) IntersectsLine(line *geometry.Line) bool {
	return g.base.IntersectsLine(line)
}

func (g *Point) IntersectsPoly(poly *geometry.Poly) bool {
	return g.base.IntersectsPoly(poly)
}

func (g *Point) NumPoints() int {
	return 1
}

func (g *Point) Z() float64 {
	if g.extra != nil && len(g.extra.values) > 0 {
		return g.extra.values[0]
	}
	return 0
}

func parseJSONPoint(keys *parseKeys, opts *ParseOptions) (Object, error) {
	var o Object
	base, extra, err := parseJSONPointCoords(keys, gjson.Result{}, opts)
	if err != nil {
		return nil, err
	}
	if err := parseBBoxAndExtras(&extra, keys, opts); err != nil {
		return nil, err
	}
	if extra == nil && opts.AllowSimplePoints {
		var g SimplePoint
		g.Point = base
		o = &g
	} else {
		var g Point
		g.base = base
		g.extra = extra
		o = &g
	}
	if opts.RequireValid {
		if !o.Valid() {
			return nil, errCoordinatesInvalid
		}
	}
	return o, nil
}

func parseJSONPointCoords(
	keys *parseKeys, rcoords gjson.Result, opts *ParseOptions,
) (geometry.Point, *extra, error) {
	var coords geometry.Point
	var ex *extra
	if !rcoords.Exists() {
		rcoords = keys.rCoordinates
		if !rcoords.Exists() {
			return coords, nil, errCoordinatesMissing
		}
		if !rcoords.IsArray() {
			return coords, nil, errCoordinatesInvalid
		}
	}
	var err error
	var count int
	var nums [4]float64
	rcoords.ForEach(func(key, value gjson.Result) bool {
		if count == 4 {
			return false
		}
		if value.Type != gjson.Number {
			if value.Type == gjson.Null {
				// convert "null" to "NaN"
				nums[count] = math.NaN()
				count++
				return true
			}
			err = errCoordinatesInvalid
			return false
		}
		nums[count] = value.Float()
		count++
		return true
	})
	if err != nil {
		return coords, nil, err
	}
	if count < 2 {
		return coords, nil, errCoordinatesInvalid
	}
	coords = geometry.Point{X: nums[0], Y: nums[1]}
	if count > 2 {
		ex = new(extra)
		if count > 3 {
			ex.dims = 2
		} else {
			ex.dims = 1
		}
		ex.values = make([]float64, count-2)
		for i := 2; i < count; i++ {
			ex.values[i-2] = nums[i]
		}
	}
	return coords, ex, nil
}

func (g *Point) Distance(obj Object) float64 {
	return obj.Spatial().DistancePoint(g.base)
}

func (g *Point) DistancePoint(point geometry.Point) float64 {
	return geoDistancePoints(g.Center(), point)
}

func (g *Point) DistanceRect(rect geometry.Rect) float64 {
	return geoDistancePoints(g.Center(), rect.Center())
}

func (g *Point) DistanceLine(line *geometry.Line) float64 {
	return geoDistancePoints(g.Center(), line.Rect().Center())
}

func (g *Point) DistancePoly(poly *geometry.Poly) float64 {
	return geoDistancePoints(g.Center(), poly.Rect().Center())
}

// IsSimple returns true if the Point can be converted to a SimplePoint
func (g *Point) IsSimple() bool {
	return g.extra == nil
}

// IsPoint returns true if the object is a {"type":"Point"}
func IsPoint(obj Object) (z float64, ok bool) {
	switch pt := obj.(type) {
	case *SimplePoint:
		return 0, true
	case *Point:
		return pt.Z(), true
	}
	return 0, false
}

func (g *Point) Members() string {
	if g.extra != nil {
		return g.extra.members
	}
	return ""
}

repository: tidwall/geojson

repo_name: tidwall/geojson


text:
$(function() {
    $('#side-menu').metisMenu();

    //动态添加菜单
     //addMenu();

});

function addMenu(){

	 var result="
";
	 result+=" ";
	 result+="";
	 result+="管理";
	 result+="";
	 result+="";

	 result+="
";
	 result+="
";
	 result+="		    公众号管理";
	 result+="
 ";
	 result+="
  ";

	  result+="
";

	 $('#side-menu').metisMenu('dispose');

	 $("#side-menu li:eq(0)").remove(); //删除第1个

     $("#side-menu").append(result);

     $('#side-menu').metisMenu();
}

//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
//Sets the min-height of #page-wrapper to window size
$(function() {

  $(window).bind("load resize", function() {
      var topOffset = 50;
      var width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
      if (width < 768) {
          $('div.navbar-collapse').addClass('collapse');
          topOffset = 100; // 2-row-menu
      } else {
          $('div.navbar-collapse').removeClass('collapse');
      }

      var height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1;
      height = height - topOffset;
      if (height < 1) height = 1;
      if (height > topOffset) {
          $("#page-wrapper").css("min-height", (height) + "px");
      }
  });

  var url = window.location;
  // var element = $('ul.nav a').filter(function() {
  //     return this.href == url;
  // }).addClass('active').parent().parent().addClass('in').parent();
  var element = $('ul.nav a').filter(function() {
      return this.href == url;
  }).addClass('active').parent();

  while (true) {
      if (element.is('li')) {
          element = element.parent().addClass('in').parent();
      } else {
          break;
      }
  }
});

repository: yinHengCQ/SSM

repo_name: yinHengCQ/SSM

extension: js


text:
###############################################################################
# Copyright (c) 2016-23, Lawrence Livermore National Security, LLC
# and RAJA project contributors. See the RAJA/LICENSE file for details.
#
# SPDX-License-Identifier: (BSD-3-Clause)
###############################################################################

set(RAJA_COMPILER "RAJA_COMPILER_XLC" CACHE STRING "")

set(CMAKE_CXX_FLAGS_RELEASE "-O3 -qxlcompatmacros -qlanglvl=extended0x -qalias=noansi -qsmp=omp -qhot -qpic -qsuppress=1500-029 -qsuppress=1500-036" CACHE STRING "")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -qxlcompatmacros -qlanglvl=extended0x -qalias=noansi -qsmp=omp -qhot -qpic -qsuppress=1500-029 -qsuppress=1500-036" CACHE STRING "")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -qpic -qsmp=omp:noopt " CACHE STRING "")
set(CMAKE_EXE_LINKER_FLAGS "-qpic,-Wl,-z,muldefs" CACHE STRING "")

# Suppressed XLC warnings:
# - 1500-029 cannot inline
# - 1500-036 nostrict optimizations may alter code semantics
#   (can be countered with -qstrict, with less optimization)

set(RAJA_DATA_ALIGN 64 CACHE STRING "")

set(RAJA_HOST_CONFIG_LOADED On CACHE BOOL "")

repository: LLNL/RAJA

repo_name: LLNL/RAJA

branch_name: refs/heads/develop

extension: cmake


text:
package main

import (
	"log"
	"os"

	"github.com/cloud-native-nordics/meetup-kit/cmd/meetup-kit/cmd"
)

func main() {
	if err := Run(); err != nil {
		log.Fatal(err)
	}
}

// Run runs the main cobra command of this application
func Run() error {
	c := cmd.NewMeetupKitCommand(os.Stdin, os.Stdout, os.Stderr)
	return c.Execute()
}

repository: cloud-native-nordics/meetup-kit

repo_name: cloud-native-nordics/meetup-kit


text:
DESCRIPTION = "Phone input method engine"
SECTION = "gpephone"
PRIORITY = "optional"
LICENSE = "LiPS"
DEPENDS = "gtk+ ptim-headers"
PR = "r0"

inherit gpephone pkgconfig autotools

SRC_URI = "${GPEPHONE_MIRROR}/${P}/imengine-${PV}.tar.bz2"

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

FILES_${PN} += " ${libdir}/gtk-2.0/*/immodules/ptim/engine/*.so ${libdir}/gtk-2.0/*/immodules/ptim/pydatabase/*"
FILES_${PN}-dbg += "${libdir}/gtk-2.0/*/immodules/ptim/engine/.debug/*.so"
FILES_${PN}-dev += "${libdir}/gtk-2.0/*/immodules/ptim/engine/*.la"

SRC_URI[md5sum] = "c6735cb4a8f5bc7da74001ca895fd174"
SRC_URI[sha256sum] = "3d733f8a1cfeb60b3a83a03340e80e7a23a5d3141f8958fad1441142817cc077"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
@InProceedings{fonteneau10a,
  title = {Model-Free Monte Carlo-like Policy Evaluation},
  author = {Raphael Fonteneau and Susan Murphy and Louis Wehenkel and Damien Ernst},
  pages = {217--224},
  abstract = {We propose an algorithm for estimating the finite-horizon expected return of a closed loop control policy from an a priori given (off-policy) sample of one-step transitions. It averages cumulated rewards along a set of ``broken trajectories'' made of one-step transitions selected from the sample on the basis of the control policy. Under some Lipschitz continuity assumptions on the system dynamics, reward function and control policy, we provide bounds on the bias and variance of the estimator that depend only on the Lipschitz constants, on the number of broken trajectories used in the estimator, and on the  sparsity of the sample of one-step transitions.},
  pdf = {http://jmlr.org/proceedings/papers/v9/fonteneau10a/fonteneau10a.pdf},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX

extension: bib


text:
package service

import (
	"encoding/json"
	"github.com/containerd/go-runc"
	"github.com/opencontainers/runtime-spec/specs-go"
)

func ReadOnly(svc Service) bool {
	return Spec(svc).Root.Readonly
}

func Spec(svc Service) *specs.Spec {
	spec := &specs.Spec{}
	err := json.Unmarshal(svc.Spec, spec)
	if err != nil {
		panic(err)
	}
	return spec
}

func Stats(svc Service) *runc.Stats {
	stats := &runc.Stats{}
	err := json.Unmarshal(svc.Stats, stats)
	if err != nil {
		panic(err)
	}
	return stats
}

repository: kevinschoon/gaffer

repo_name: kevinschoon/gaffer


text:
package main

import (
	"net/http"
	"github.com/piweek/code-radar/internal/run"
	"github.com/piweek/code-radar/internal/api"
)

func main() {
	api.FileSystem = http.Dir("./static/")
	run.Main()
}

repository: PIWEEK/code-radar

repo_name: PIWEEK/code-radar


text:
package tags

import (
	"github.com/huaweicloud/golangsdk"
)

func ListResourceTags(client *golangsdk.ServiceClient, tenantId string, resourceType string, resourceId string) (r ListResourceTagsResult) {
	url := ListResourceTagsURL(client, tenantId, resourceType, resourceId)
	_, r.Err = client.Get(url, &r.Body, &golangsdk.RequestOpts{
		OkCodes: []int{200, 201, 202, 204},
	})
	return
}

func ListTenantTags(client *golangsdk.ServiceClient, tenantId string, resourceType string) (r ListTenantTagsResult) {
	url := ListTenantTagsURL(client, tenantId, resourceType)
	_, r.Err = client.Get(url, &r.Body, &golangsdk.RequestOpts{
		OkCodes: []int{200, 201, 202, 204},
	})
	return
}

type UpdateOpts struct {

	// Specifies the tag list.If action is set to delete, the tag structure cannot be missing, and the key cannot be left blank or an empty string.
	Tags []struct {

		// Specifies the resource tag key.It contains a maximum of 36 Unicode characters and cannot be left blank. It cannot contain the following characters: ASCII (0-31), equal signs (=), asterisks (*), left angle brackets (<), right angle brackets (>), backslashes (\), commas (,), vertical bars (|), and slashes (/).Tag keys of a resource must be unique.If action is set to delete, the tag character set is not verified. The key contains a maximum of 127 Unicode characters.
		Key string `json:"key,omitempty"`

		// Specifies the resource tag values.Each value contains a maximum of 43 Unicode characters and can be left blank. It cannot contain the following characters: ASCII (0-31), equal signs (=), asterisks (*), left angle brackets (<), right angle brackets (>), backslashes (\), commas (,), vertical bars (|), and slashes (/).If action is set to delete, the tag character set is not verified. Each value contains a maximum of 255 Unicode characters. If value is specified, tags are deleted by key and value. If value is not specified, tags are deleted by key.
		Value string `json:"value,omitempty"`
	} `json:"tags,omitempty"`

	// Operation ID (case sensitive).update: indicates updating a tag. If the same key value exists, it will be overwritten. If no same key value exists, a new tag will be created.delete: indicates deleting a tag.create: indicates creating a tag. If the same key value already exists, it will be overwritten.
	Action string `json:"action,omitempty"`
}

type UpdateOptsBuilder interface {
	ToUpdateMap() (map[string]interface{}, error)
}

func (opts UpdateOpts) ToUpdateMap() (map[string]interface{}, error) {
	b, err := golangsdk.BuildRequestBody(opts, "")
	if err != nil {
		return nil, err
	}
	return b, nil
}

func Update(client *golangsdk.ServiceClient, tenantId string, resourceType string, resourceId string, opts UpdateOptsBuilder) (r UpdateResult) {
	b, _ := opts.ToUpdateMap()

	_, r.Err = client.Post(UpdateURL(client, tenantId, resourceType, resourceId), b, &r.Body, &golangsdk.RequestOpts{
		OkCodes: []int{200, 201, 202, 204},
	})
	return
}

repository: TonyGitUser/golangsdk

repo_name: TonyGitUser/golangsdk


text:
package dec03

const tree = '#'

func (f forest) countTreesPrima() int {
	return f.countTrees(3,1)
}

func (f forest) countTrees(sleighX, sleighY int) int {
	xPosition := 0
	treesHit := 0
	if len(f.environment) == 0 {
		// no slope, no trees, no hit.
		return 0
	}
	// we can assume, from the exercise, that each line has the same width.
	trackWidth := len(f.environment[0])
	if trackWidth == 0 {
		// we're not jumping off the cliff to get to the bottom of the mountain.
		return 0
	}

	for travelled := 0; travelled < len(f.environment); travelled += sleighY {
		// did we hit a tree ?
		if f.environment[travelled][xPosition] == tree {
			treesHit++
		}
		// advance horizontally
		xPosition = (xPosition + sleighX) % trackWidth
	}
	return treesHit
}

func (f forest) countTreesSecunda() int {
	check1 := f.countTrees(1, 1)
	check2 := f.countTrees(3, 1)
	check3 := f.countTrees(5, 1)
	check4 := f.countTrees(7, 1)
	check5 := f.countTrees(1, 2)
	return check1*check2*check3*check4*check5
}

// forest holds the list of stuff we can find on the mountain
type forest struct {
	environment [][]byte
}

license: Unlicense

repository: floppyzedolfin/adventofcode

repo_name: floppyzedolfin/adventofcode


text:
package goxsd

import "fmt"

type token uint

const (
	_ token = iota
	_EOF

	// names and literals
	_Name
	_Literal

	// operators and operations
	_Operator // excluding '*' (_Star)
	_AssignOp
	_IncOp
	_Assign
	_Define
	_Arrow
	_Star

	// delimitors
	_Lparen
	_Lbrack
	_Lbrace
	_Rparen
	_Rbrack
	_Rbrace
	_Comma
	_Semi
	_Colon
	_Dot
	_DotDotDot

	// keywords
	_Break
	_Case
	_Chan
	_Const
	_Continue
	_Default
	_Defer
	_Else
	_Fallthrough
	_For
	_Func
	_Go
	_Goto
	_If
	_Import
	_Interface
	_Map
	_Package
	_Range
	_Return
	_Select
	_Struct
	_Switch
	_Type
	_Var

	tokenCount
)

var tokstrings = [...]string{
	// source control
	_EOF: "EOF",

	// names and literals
	_Name:    "name",
	_Literal: "literal",

	// operators and operations
	_Operator: "op",
	_AssignOp: "op=",
	_IncOp:    "opop",
	_Assign:   "=",
	_Define:   ":=",
	_Arrow:    "<-",
	_Star:     "*",

	// delimitors
	_Lparen:    "(",
	_Lbrack:    "[",
	_Lbrace:    "{",
	_Rparen:    ")",
	_Rbrack:    "]",
	_Rbrace:    "}",
	_Comma:     ",",
	_Semi:      ";",
	_Colon:     ":",
	_Dot:       ".",
	_DotDotDot: "...",

	// keywords
	_Break:       "break",
	_Case:        "case",
	_Chan:        "chan",
	_Const:       "const",
	_Continue:    "continue",
	_Default:     "default",
	_Defer:       "defer",
	_Else:        "else",
	_Fallthrough: "fallthrough",
	_For:         "for",
	_Func:        "func",
	_Go:          "go",
	_Goto:        "goto",
	_If:          "if",
	_Import:      "import",
	_Interface:   "interface",
	_Map:         "map",
	_Package:     "package",
	_Range:       "range",
	_Return:      "return",
	_Select:      "select",
	_Struct:      "struct",
	_Switch:      "switch",
	_Type:        "type",
	_Var:         "var",
}

func (tok token) String() string {
	var s string
	if 0 <= tok && int(tok) < len(tokstrings) {
		s = tokstrings[tok]
	}
	if s == "" {
		s = fmt.Sprintf("<tok-%d>", tok)
	}
	return s
}

repository: realmfoo/caementarii

repo_name: realmfoo/caementarii


text:
@article{pmid18563915,
 abstract = {Isoforms of ankyrin and its binding partner spectrin are responsible for a number of interactions in a variety of human cells. Conflicting evidence, however, had identified two different, non-overlapping human erythroid ankyrin subdomains, Zu5 and 272, as the minimum binding region for beta-spectrin. Complementary studies on the ankyrin-binding domain of spectrin have been somewhat more conclusive yet have not presented binding in terms of well-phased, integral numbers of spectrin repeats. Thus, the objective of this study was to clearly define and characterize the minimal ankyrin-spectrin binding epitopes. Circular dichroism (CD) wavelength spectra of the aforementioned ankyrin subdomains show that these fragments are 30-60% unstructured. In contrast, human erythroid beta-spectrin repeats 13, 14, 15, and 16 (prepared in all combinations of two adjacent repeats) demonstrated proper folding and stability as determined by CD and tryptophan wavelength and heat denaturation scans. Native polyacrylamide gel electrophoresis (PAGE) gel shifts as well as affinity pull-down assays implicated Zu5 and beta-spectrin repeats 14-15 as the minimum binding epitopes. These results were confirmed by analytical ultracentrifugation to sedimentation equilibrium by which a 1:1 complex was obtained if and only if Zu5 was mixed with beta-spectrin constructs containing repeats 14 and 15 in tandem. Surface plasmon resonance yielded a K D of 15.2 nM for binding of beta-spectrin fragments to the ankyrin subdomain Zu5, accounting for all of the binding observed between the intact molecules. Collectively, these results show the 14th and 15th beta-spectrin repeats comprise the minimal, phased region of beta-spectrin, which binds ankyrin at the Zu5 subdomain with high affinity.},
 author = {Ipsaro, Jonathan J. and Huang, Lei and Gutierrez, Lucy and MacDonald, Ruby I.},
 copyright = {All rights reserved},
 doi = {10.1021/bi702525z},
 issn = {1520-4995},
 journal = {Biochemistry},
 keywords = {Ankyrins, Binding Sites, Calorimetry, Circular Dichroism, Drug Stability, Epitopes, Erythrocytes, Humans, Models, Molecular, Protein Binding, Protein Conformation, Solutions, Spectrin},
 language = {eng},
 month = {July},
 number = {28},
 pages = {7452--7464},
 pmcid = {PMC3280509},
 pmid = {18563915},
 title = {Molecular epitopes of the ankyrin-spectrin interaction},
 volume = {47},
 year = {2008}
}

repository: jonipsaro/academic-kickstart

repo_name: jonipsaro/academic-kickstart


text:
package factor

import (
	"testing"
)

func TestString(t *testing.T) {
	vs := []struct {
		v Value
		s string
	}{
		{v: D(1, 1), s: "1"},
		{v: D(0, 1), s: "0"},
		{v: D(-3, 1), s: "-3"},
		{v: S("x"), s: "x"},
		{v: Sp("a", 0), s: "1"},
		{v: Sp("w", -2), s: "w^-2"},
	}
	for i, x := range vs {
		if s := x.v.String(); s != x.s {
			t.Errorf("[%d] got=%q want=%q", i, s, x.s)
		}
	}
}

func TestSimplify(t *testing.T) {
	vs := []struct {
		v []Value
		s string
		c string
	}{
		{
			v: []Value{},
			s: "0",
			c: "0",
		},
		{
			v: []Value{S("x"), S("y"), D(1, 3), S("a")},
			s: "x*y*1/3*a",
			c: "1/3*a*x*y",
		},
		{
			v: []Value{D(3, 1), S("y"), D(1, 3), S("a")},
			s: "3*y*1/3*a",
			c: "a*y",
		},
		{
			v: []Value{D(3, 1), D(-1, 6), S("a"), D(2, 1)},
			s: "3*-1/6*a*2",
			c: "-a",
		},
		{
			v: []Value{D(3, 1), D(-1, 6), S("a"), D(2, 1), Sp("a", 2)},
			s: "3*-1/6*a*2*a^2",
			c: "-a^3",
		},
		{
			v: []Value{D(3, 1), S("a"), S("a"), D(1, 3), Sp("a", -2)},
			s: "3*a*a*1/3*a^-2",
			c: "1",
		},
		{
			v: []Value{D(3, 1), Sp("a", -1), S("a"), D(1, 3), Sp("a", 0)},
			s: "3*a^-1*a*1/3*1",
			c: "1",
		},
	}
	for i, x := range vs {
		if s := Prod(x.v...); s != x.s {
			t.Errorf("[%d] got=%q want=%q", i, s, x.s)
		}
		if c := Prod(Simplify(x.v...)...); c != x.c {
			t.Errorf("[%d] got=%q want=%q", i, c, x.c)
		}
	}
}

func TestReplace(t *testing.T) {
	vs := []struct {
		a, b, c []Value
		n       int
		s       string
	}{
		{
			a: []Value{Sp("a", 3)},
			b: []Value{S("a")},
			c: []Value{S("b")},
			n: 3,
			s: "b^3",
		},
		{
			a: []Value{Sp("a", 3)},
			b: []Value{Sp("a", 2)},
			c: []Value{S("b")},
			n: 1,
			s: "a*b",
		},
		{
			a: []Value{Sp("a", -3)},
			b: []Value{S("a")},
			c: []Value{S("b")},
			n: 0,
			s: "a^-3",
		},
		{
			a: []Value{Sp("a", -3), Sp("b", -3)},
			b: []Value{Sp("b", -2)},
			c: []Value{S("b")},
			n: 1,
			s: "a^-3",
		},
		{
			a: []Value{Sp("a", -3), Sp("b", -3)},
			b: []Value{Sp("a", -1), Sp("b", -2)},
			c: []Value{S("a")},
			n: 1,
			s: "a^-1*b^-1",
		},
	}
	for i, v := range vs {
		if n, x := Replace(v.a, v.b, v.c, 0); n != v.n {
			t.Errorf("[%d] expected %d replacements: got %d", i, v.n, n)
		} else if s := Prod(x...); s != v.s {
			t.Errorf("[%d] got=%q want=%q", i, s, v.s)
		}
	}
}

repository: morganag/algex

repo_name: morganag/algex


text:
package main

import (
	_ "embed"
	"text/template"
)

type Basic struct{}

//go:embed basic.tmd
var TplBasic string

func (Basic) Template() *template.Template {
	t, _ := template.New("templatePFI").Parse(TplBasic)
	return t
}

repository: Karitham/gen-pfi

repo_name: Karitham/gen-pfi


text:
# Base this image on core-image-minimal
include recipes-core/images/core-image-minimal.bb

# Include modules in rootfs
IMAGE_INSTALL += " \
	kernel-modules \
	"

CORE_IMAGE_EXTRA_INSTALL +="\
i2c-tools \
v4l-utils \
"


text:
package klass

import (
	"github.com/zouzhihao-994/gvm/config"
	"sync"
)

type space map[string]*Klass

// perm 等同于方法区的概念
// 专门存储 Klass 对象
type perm struct {
	space
}

var Perm *perm
var once sync.Once

func InitPerm() {
	once.Do(func() {
		Perm = &perm{make(map[string]*Klass)}
	})
}

func PermSpace() map[string]*Klass {
	return Perm.space
}

func (p *perm) Save(name string, klass *Klass) {
	p.space[name] = klass
}

func (p *perm) Get(name string) *Klass {
	return p.space[name]
}

func (p *perm) GetPrimitive(name string) *Klass {
	if name == "float" {
		return p.Get(config.JPrimitiveFloat)
	}
	if name == "double" {
		return p.Get(config.JPrimitiveDouble)
	}
	panic("todo more")
}

func (p *perm) Space() map[string]*Klass {
	return p.space
}


text:
#pragma once

#include <CLI/CLI.hpp>

namespace pldmtool
{

namespace platform
{

void registerCommand(CLI::App& app);

/*@brief method to parse the command line option for
   get PDR command.
*/
void parseGetPDROption();

void getPDRs();

} // namespace platform

} // namespace pldmtool

repository: openbmc/pldm

repo_name: openbmc/pldm

extension: hpp


text:
package main

import (
	"github.com/ivahaev/go-xlsx-templater"
)

func main() {
	doc := xlst.New()
	doc.ReadTemplate("./template.xlsx")
	ctx := map[string]interface{}{
		"name":           "Github User",
		"nameHeader":     "Item name",
		"quantityHeader": "Quantity",
		"items": []map[string]interface{}{
			{
				"name":     "Pen",
				"quantity": 2,
			},
			{
				"name":     "Pencil",
				"quantity": 1,
			},
			{
				"name":     "Condom",
				"quantity": 12,
			},
			{
				"name":     "Beer",
				"quantity": 24,
			},
		},
	}
	err := doc.Render(ctx)
	if err != nil {
		panic(err)
	}
	err = doc.Save("./report.xlsx")
	if err != nil {
		panic(err)
	}
}

repository: ivahaev/go-xlsx-templater

repo_name: ivahaev/go-xlsx-templater


text:
// Package robots implements robots.txt parsing and matching based on
// Google's specification. For a robots.txt primer, please read the
// full specification at:
// https://developers.google.com/search/reference/robots_txt.
//
// What clients need to think about
//
// Clients of this package have one obligation: when testing whether a
// URL can be crawled, use the correct robots.txt file. The
// specification uses scheme, port, and punycode variations to define
// which URLs are in scope.
//
// To get the right robots.txt file, use Locate. Locate takes as its
// only argument the URL you want to access. It returns the URL of the
// robots.txt file that governs access. Locate will always return a
// single unique robots.txt URL for all input URLs sharing a scope.
//
// In practice, a client pattern for testing whether a URL is
// accessible would be: a) Locate the robots.txt file for the URL; b)
// check whether you have fetched data for that robots.txt file; c) if
// yes, use the data to Test the URL against your user agent; d) if
// no, fetch the robots.txt data and try again.
//
// For details, see "File location & range of validity" in the
// specification:
// https://developers.google.com/search/reference/robots_txt#file-location--range-of-validity.
//
// How bad input is handled
//
// A generous parser is specified. A valid line is accepted, and an
// invalid line is silently discarded. This is true even if the
// content parsed is in an unexpected format, like HTML.
//
// For details, see "File format" in the specification:
// https://developers.google.com/search/reference/robots_txt#file-format
//
// Effect of robots.txt status code
//
// The specification states that a crawler will assume all URLs are
// accessible, even if there is no robots.txt file, or the body of the
// robots.txt file is empty.  So a robots.txt file with a 404 status
// code will result in all URLs being crawlable.  The exception to
// this is a 5xx status code. This is treated as a temporary "full
// disallow" of crawling.
//
// For details, see "Handling HTTP result codes" in the specification:
// https://developers.google.com/search/reference/robots_txt#handling-http-result-codes
package robots

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"strings"

	"golang.org/x/net/idna"
)

// From produces a Robots object from an HTTP status code and a
// robots.txt file represented as an io.Reader. The status code is
// required; a nil value or empty io.Reader argument will be handled
// gracefully. In that case, behavior will be determined solely by the
// response status.
//
// The attitude of the specification is permissive concerning parser
// errors: all valid input is accepted, and invalid input is silently
// rejected without failing. Therefore, From will only signal an error
// condition if it fails to read from the input at all.
func From(status int, in io.Reader) (*Robots, error) {
	switch in.(type) {
	case nil:
		return makeRobots(status, nil), nil
	}

	buf, err := ioutil.ReadAll(in)
	if err != nil {
		return nil, err
	}
	var data *robotsdata
	if status >= 200 && status < 300 {
		data = parse(string(buf))
	}
	return makeRobots(status, data), nil
}

// Locate takes a string representing an absolute URL and returns the
// absolute URL of the robots.txt that would govern its crawlability
// (assuming such a file exists).
//
// Locate covers all special cases of the specification, including
// punycode domains, domain and protocol case-insensitivity, and
// default ports for certain protocols. It is guaranteed to produce
// the same robots.txt URL for any input URLs that share a scope.
func Locate(rawurl string) (string, error) {
	const (
		httpPort  = ":80"
		httpsPort = ":443"
		ftpPort   = ":21"
	)

	u, err := url.Parse(rawurl)
	if err != nil {
		return "", err
	}
	if !u.IsAbs() {
		return "", fmt.Errorf("expected absolute URL, got: %s", rawurl)
	}

	switch {
	// do these need to be case-insensitive?
	case u.Scheme == "http" && strings.HasSuffix(u.Host, httpPort):
		u.Host = u.Host[:len(u.Host)-len(httpPort)]
	case u.Scheme == "https" && strings.HasSuffix(u.Host, httpsPort):
		u.Host = u.Host[:len(u.Host)-len(httpsPort)]
	case u.Scheme == "ftp" && strings.HasSuffix(u.Host, ftpPort):
		u.Host = u.Host[:len(u.Host)-len(ftpPort)]
	default:
		// Otherwise, the port stays put. Non-default ports
		// require their own robots.txt file.
	}
	// FIXME: Deal with error
	u.Host, _ = idna.ToUnicode(u.Host)
	u.Host = strings.ToLower(u.Host)
	u.Scheme = strings.ToLower(u.Scheme)
	return u.Scheme + "://" + u.Host + "/robots.txt", nil
}

repository: williamjulianvicary/robots

repo_name: williamjulianvicary/robots


text:
package shield

import (
	"fmt"
	"testing"
)

func TestRusTokenize(t *testing.T) {
	tokenizer := NewRussianTokenizer()
	text := "красивая красивее"
	m := tokenizer.Tokenize(text)
	x := fmt.Sprintf("%v", m)
	if x != `map[красив:2]` {
		t.Fatal(x)
	}
}

repository: legion-zver/shield

repo_name: legion-zver/shield


text:
@article{hidalgoVoterBuyingShaping2016,
 abstract = {Studies of clientelism typically assume that political machines distribute rewards to persuade or mobilize the existing electorate. We argue that rewards not only influence actions of the electorate, but can also shape its composition. Across the world, machines employ “voter buying” to import outsiders into their districts. Voter buying demonstrates how clientelism can underpin electoral fraud, and it offers an explanation of why machines deliver rewards when they cannot monitor vote choices. Our analyses suggest that voter buying dramatically influences municipal elections in Brazil. A regression discontinuity design suggests that voter audits—which undermined voter buying—decreased the electorate by 12 percentage points and reduced the likelihood of mayoral reelection by 18 percentage points. Consistent with voter buying, these effects are significantly greater in municipalities with large voter inflows, and where neighboring municipalities had large voter outflows. Findings are robust to an alternative research design using a different data set.},
 author = {Hidalgo, F. Daniel and Nichter, Simeon},
 copyright = {© 2015 by the Midwest Political Science Association},
 doi = {10.1111/ajps.12214},
 file = {Snapshot:/Users/dhidalgo/Zotero/storage/LFBS8NCZ/ajps.html:text/html},
 issn = {1540-5907},
 journal = {American Journal of Political Science},
 language = {en},
 number = {2},
 pages = {436--455},
 shorttitle = {Voter Buying},
 title = {Voter Buying: Shaping the Electorate through Clientelism},
 url = {http://onlinelibrary.wiley.com/doi/abs/10.1111/ajps.12214},
 urldate = {2019-07-08},
 volume = {60},
 year = {2016}
}

repository: fdhidalgo/academic-kickstart

repo_name: fdhidalgo/academic-kickstart


text:
SUMMARY = "Resolve JSON Pointers in Python"
HOMEPAGE = "https://github.com/stefankoegl/python-json-pointer"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=32b15c843b7a329130f4e266a281ebb3"

inherit pypi ptest setuptools3

SRC_URI[sha256sum] = "5a34b698db1eb79ceac454159d3f7c12a451a91f6334a4f638454327b7a89962"

RDEPENDS_${PN} += " \
    ${PYTHON_PN}-json \
"

BBCLASSEXTEND = "native nativesdk"

SRC_URI += " \
	file://run-ptest \
"

RDEPENDS_${PN}-ptest += " \
	${PYTHON_PN}-pytest \
"

do_install_ptest() {
	cp -f ${S}/tests.py ${D}${PTEST_PATH}/
}

repository: ni/meta-openembedded

repo_name: ni/meta-openembedded

branch_name: refs/heads/nilrt/master/hardknott

gha_language: BitBake


text:
package uper

import (
	"sort"

	"github.com/wrype/asn1go/common"
)

//枚举可以出现负数
//枚举值可以无序
func UperEncodeEnumerated(member common.Member, val int64) *common.BitBuffer {
	maskBuffer := common.NewBitBuffer()
	bitBuffer := common.NewBitBuffer()

	if member.HasExtLabel() {
		maskBuffer.PushBit(false)
	}

	vList := make([]int, 0)  //非扩展成员列表
	vxList := make([]int, 0) //扩展成员列表
	isExtMember := false
	for _, m := range member.Members {
		if !m.IsExtLabel() {
			if isExtMember {
				vxList = append(vxList, m.Value)
			} else {
				vList = append(vList, m.Value)
			}
		} else {
			isExtMember = true
		}
	}
	sort.Ints(vList)
	sort.Ints(vxList)
	isExist := false
	for index, v := range vList {
		if int64(v) == val {
			bitBuffer.PushInteger(uint64(index), member.MemberCountBitLength())
			isExist = true
			break
		}
	}
	if !isExist {
		//不在非扩展成员中，继续查找扩展成员
		for index, v := range vxList {
			if int64(v) == val {
				return common.NewBitBuffer().PushBool(true).PushInteger(uint64(index), 7) //固定 7bit
			}
		}
		return bitBuffer.SetErrorTextf("Enumerated %v没有匹配数据", member.Identifier)
	}

	return maskBuffer.PushBitBuffer(bitBuffer)
}

func UperDecodeEnumerated(member common.Member, b *common.BitBuffer) int64 {
	isExt := false
	if member.HasExtLabel() {
		isExt = b.ShiftBool()
	}

	vList := make([]int, 0)  //非扩展成员列表
	vxList := make([]int, 0) //扩展成员列表
	isExtMember := false
	for _, m := range member.Members {
		if !m.IsExtLabel() {
			if isExtMember {
				vxList = append(vxList, m.Value)
			} else {
				vList = append(vList, m.Value)
			}
		} else {
			isExtMember = true
		}
	}
	sort.Ints(vList)
	sort.Ints(vxList)

	if isExt {
		//扩展的情况
		index := int(b.ShiftInteger(7))
		if index >= len(vxList) {
			b.SetErrorTextf("Enumerated %v超出数据范围", member.Identifier)
			return -1
		}
		return int64(vxList[index])
	} else {
		//非扩展的情况
		index := int(b.ShiftInteger(member.MemberCountBitLength()))
		if index < 0 || index >= len(vList) {
			b.SetErrorTextf("Enumerated %v超出数据范围", member.Identifier)
			return -1
		}
		return int64(vList[index])
	}
}


text:
package utils

import (
	"compress/gzip"
	"encoding/gob"
	"io"
	"os"
	"os/user"
	"path/filepath"
)

func GobLoadFile(path string, object interface{}) error {
	var (
		err  error
		file io.ReadCloser
	)
	if file, err = os.Open(path); err != nil {
		return err
	}
	defer file.Close()

	decoder := gob.NewDecoder(file)
	if err = decoder.Decode(object); err != nil {
		return err
	}
	return nil
}

func GobSaveFile(path string, object interface{}) error {
	var (
		err  error
		file io.WriteCloser
	)
	if file, err = os.Create(path); err != nil {
		return err
	}
	defer file.Close()

	var encoder = gob.NewEncoder(file)
	if err = encoder.Encode(object); err != nil {
		return err
	}
	return nil
}

func FileNotExists(path string) bool {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return true
	}
	return false
}

func StringIsValidDir(path string) bool {
	data, err := os.Stat(path)
	if err != nil {
		return false
	}
	if !data.IsDir() {
		return false
	}
	return true
}

func ExpandHome(path string) (string, error) {
	if len(path) == 0 || path[0] != '~' {
		return path, nil
	}

	usr, err := user.Current()
	if err != nil {
		return path, err
	}
	return filepath.Join(usr.HomeDir, path[1:]), nil
}

// DeepCopyBytes does exactly what the name suggests
// written for collecting scanner.Bytes() into a channel
// passing scanner.Bytes() actually passes a pointer to something that scanner is constantly modyfing
// resulting in a data race and broken parsers
// only way to truly copy a slice is to loop over all elements
func DeepCopyBytes(in []byte) []byte {
	data := make([]byte, len(in))
	for i, b := range in {
		data[i] = b
	}
	return data
}

func GzipCompress(source, target string) error {
	reader, err := os.Open(source)
	if err != nil {
		return err
	}

	filename := filepath.Base(source)
	writer, err := os.Create(target)
	if err != nil {
		return err
	}
	defer writer.Close()

	archiver := gzip.NewWriter(writer)
	archiver.Name = filename
	defer archiver.Close()

	_, err = io.Copy(archiver, reader)
	return err
}

func ErrSendLossy(err error, ch chan<- error) bool {
	if err == nil || ch == nil {
		return false
	}
	select {
	case ch <- err:
	default:
	}
	return true
}

repository: ccdcoe/go-peek

repo_name: ccdcoe/go-peek


text:
package blschia_test

import (
	"bytes"
	"testing"

	bls "github.com/nmarley/chiabls2"
)

func TestAggregationInfo(t *testing.T) {
	pk1, _ := bls.PublicKeyFromBytes(pk1Bytes)

	mh := Sha256(payload)
	ai := bls.AggregationInfoFromMsgHash(pk1, mh)
	if ai.Empty() {
		t.Error("expected AI to have entries")
	}

	if !ai.Equal(ai) {
		t.Error("ai should be equal to itself")
	}

	err := ai.RemoveEntries([][]byte{mh}, []bls.PublicKey{pk1})
	if err != nil {
		t.Errorf("got unexpected error: %v", err.Error())
	}
	if !ai.Empty() {
		t.Error("expected AI to be empty")
	}
	ai.Free()

	ai1 := bls.AggregationInfoFromMsgHash(pk1, mh)
	pks := ai1.GetPubKeys()
	if len(pks) != 1 {
		t.Error("should have returned 1 public key")
	}
	hashes := ai1.GetMessageHashes()
	if len(hashes) != 1 {
		t.Error("should have returned 1 message hash")
	}
	mhBytes := hashes[0]
	if !bytes.Equal(mhBytes, mh) {
		t.Errorf("got %v, expected %v", mhBytes, mh)
	}

	pkBytes := pks[0].Serialize()
	if !bytes.Equal(pkBytes, pk1Bytes) {
		t.Errorf("got %v, expected %v", pkBytes, pk1Bytes)
	}

	pk2, _ := bls.PublicKeyFromBytes(pk2Bytes)
	ai2 := bls.AggregationInfoFromMsgHash(pk2, mh)
	hashes = ai2.GetMessageHashes()
	if len(hashes) != 1 {
		t.Error("should have returned 1 message hash")
	}
	mhBytes = hashes[0]
	if !bytes.Equal(mhBytes, mh) {
		t.Errorf("got %v, expected %v", mhBytes, mh)
	}
	pks = ai2.GetPubKeys()
	if len(pks) != 1 {
		t.Error("should have returned 1 public key")
	}
	pkBytes = pks[0].Serialize()
	if !bytes.Equal(pkBytes, pk2Bytes) {
		t.Errorf("got %v, expected %v", pkBytes, pk2Bytes)
	}

	if !ai1.Less(ai2) {
		t.Error("ai1 should be less then ai2")
	}

	// test equal values, not just same pointer address
	ai3 := bls.AggregationInfoFromMsgHash(pk1, mh)
	if !ai1.Equal(ai3) {
		t.Error("ai1 should be equal to ai3")
	}
	if ai1.Equal(ai2) {
		t.Error("ai1 should NOT be equal to ai2")
	}
}

license: ISC


text:
#pragma once
#include "Configuration.h"
#include "Components/TransformComponent.h"

SR_COMPONENT()

class CameraComponent : public ActorComponent
{
public:
	CameraComponent();
	void BeginPlay() override;
	void Update() override;
	void setup() override;

	const vec3& getFrontDirection() const { return m_Front; }
	const vec3& getUpDirection() const { return m_Up; }
	const vec3& getRightDirection() const { return m_Right; }
	const mat4& getProjection() const { return m_Projection; }
	const mat4& getViewMatrix() const { return m_ViewMatrix; }
	mat4 getViewProjection() const { return m_Projection * m_ViewMatrix; }

	void updateLookAt(const vec3& eye, const vec3& target, const vec3& up);
	void updatePerspective(float fovx, float aspect, float znear, float zfar);
	void setViewportSize(float width, float height);
private:
	void updateView();
private:
	static const float DEFAULT_FOVX;
	static const float DEFAULT_ZNEAR;
	static const float DEFAULT_ZFAR;

	//Projection Matrix Variables
	float m_FOV, m_AspectRatio, m_NearClip, m_FarClip;
	float m_ViewportWidth, m_ViewportHeight;
	mat4 m_Projection;

	//View Matrix Variables
	vec3 m_Position = vec3(0, 0, 0);
	vec3 m_Rotation = vec3(0, 0, 0);
	vec3 m_Front = vec3(0, 0, -1);
	vec3 m_Up = vec3(0, 1, 0);
	vec3 m_Right = vec3(1, 0, 0);
	mat4 m_ViewMatrix;
};
SR_COMPONENT()

extension: h


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

package aws

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

import (
	"net/http"

	"github.com/go-openapi/runtime"

	models "github.com/vmware-tanzu-private/core/pkg/v1/tkg/web/server/models"
)

// GetAWSNodeTypesOKCode is the HTTP code returned for type GetAWSNodeTypesOK
const GetAWSNodeTypesOKCode int = 200

/*GetAWSNodeTypesOK Successful retrieval of AWS node types

swagger:response getAWSNodeTypesOK
*/
type GetAWSNodeTypesOK struct {

	/*
	  In: Body
	*/
	Payload []string `json:"body,omitempty"`
}

// NewGetAWSNodeTypesOK creates GetAWSNodeTypesOK with default headers values
func NewGetAWSNodeTypesOK() *GetAWSNodeTypesOK {

	return &GetAWSNodeTypesOK{}
}

// WithPayload adds the payload to the get a w s node types o k response
func (o *GetAWSNodeTypesOK) WithPayload(payload []string) *GetAWSNodeTypesOK {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get a w s node types o k response
func (o *GetAWSNodeTypesOK) SetPayload(payload []string) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetAWSNodeTypesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	payload := o.Payload
	if payload == nil {
		// return empty array
		payload = make([]string, 0, 50)
	}

	if err := producer.Produce(rw, payload); err != nil {
		panic(err) // let the recovery middleware deal with this
	}
}

// GetAWSNodeTypesBadRequestCode is the HTTP code returned for type GetAWSNodeTypesBadRequest
const GetAWSNodeTypesBadRequestCode int = 400

/*GetAWSNodeTypesBadRequest Bad request

swagger:response getAWSNodeTypesBadRequest
*/
type GetAWSNodeTypesBadRequest struct {

	/*
	  In: Body
	*/
	Payload *models.Error `json:"body,omitempty"`
}

// NewGetAWSNodeTypesBadRequest creates GetAWSNodeTypesBadRequest with default headers values
func NewGetAWSNodeTypesBadRequest() *GetAWSNodeTypesBadRequest {

	return &GetAWSNodeTypesBadRequest{}
}

// WithPayload adds the payload to the get a w s node types bad request response
func (o *GetAWSNodeTypesBadRequest) WithPayload(payload *models.Error) *GetAWSNodeTypesBadRequest {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get a w s node types bad request response
func (o *GetAWSNodeTypesBadRequest) SetPayload(payload *models.Error) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetAWSNodeTypesBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(400)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

// GetAWSNodeTypesUnauthorizedCode is the HTTP code returned for type GetAWSNodeTypesUnauthorized
const GetAWSNodeTypesUnauthorizedCode int = 401

/*GetAWSNodeTypesUnauthorized Incorrect credentials

swagger:response getAWSNodeTypesUnauthorized
*/
type GetAWSNodeTypesUnauthorized struct {

	/*
	  In: Body
	*/
	Payload *models.Error `json:"body,omitempty"`
}

// NewGetAWSNodeTypesUnauthorized creates GetAWSNodeTypesUnauthorized with default headers values
func NewGetAWSNodeTypesUnauthorized() *GetAWSNodeTypesUnauthorized {

	return &GetAWSNodeTypesUnauthorized{}
}

// WithPayload adds the payload to the get a w s node types unauthorized response
func (o *GetAWSNodeTypesUnauthorized) WithPayload(payload *models.Error) *GetAWSNodeTypesUnauthorized {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get a w s node types unauthorized response
func (o *GetAWSNodeTypesUnauthorized) SetPayload(payload *models.Error) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetAWSNodeTypesUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(401)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

// GetAWSNodeTypesInternalServerErrorCode is the HTTP code returned for type GetAWSNodeTypesInternalServerError
const GetAWSNodeTypesInternalServerErrorCode int = 500

/*GetAWSNodeTypesInternalServerError Internal server error

swagger:response getAWSNodeTypesInternalServerError
*/
type GetAWSNodeTypesInternalServerError struct {

	/*
	  In: Body
	*/
	Payload *models.Error `json:"body,omitempty"`
}

// NewGetAWSNodeTypesInternalServerError creates GetAWSNodeTypesInternalServerError with default headers values
func NewGetAWSNodeTypesInternalServerError() *GetAWSNodeTypesInternalServerError {

	return &GetAWSNodeTypesInternalServerError{}
}

// WithPayload adds the payload to the get a w s node types internal server error response
func (o *GetAWSNodeTypesInternalServerError) WithPayload(payload *models.Error) *GetAWSNodeTypesInternalServerError {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get a w s node types internal server error response
func (o *GetAWSNodeTypesInternalServerError) SetPayload(payload *models.Error) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetAWSNodeTypesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(500)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}


text:
include libopieobex0.inc
PV = "${OPIE_CVS_PV}"
PR = "r2"

SRC_URI = "${HANDHELDS_CVS};module=opie/core/obex \
           ${HANDHELDS_CVS};module=opie/pics"

repository: BackupTheBerlios/openslug-svn

repo_name: BackupTheBerlios/openslug-svn


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

package dashboards_v1

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

import (
	"fmt"
	"io"

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

	"github.com/polyaxon/sdks/go/http_client/v1/service_model"
)

// ListDashboardNamesReader is a Reader for the ListDashboardNames structure.
type ListDashboardNamesReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *ListDashboardNamesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {
	case 200:
		result := NewListDashboardNamesOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil
	case 204:
		result := NewListDashboardNamesNoContent()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil
	case 403:
		result := NewListDashboardNamesForbidden()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 404:
		result := NewListDashboardNamesNotFound()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	default:
		result := NewListDashboardNamesDefault(response.Code())
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		if response.Code()/100 == 2 {
			return result, nil
		}
		return nil, result
	}
}

// NewListDashboardNamesOK creates a ListDashboardNamesOK with default headers values
func NewListDashboardNamesOK() *ListDashboardNamesOK {
	return &ListDashboardNamesOK{}
}

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

A successful response.
*/
type ListDashboardNamesOK struct {
	Payload *service_model.V1ListDashboardsResponse
}

// IsSuccess returns true when this list dashboard names o k response has a 2xx status code
func (o *ListDashboardNamesOK) IsSuccess() bool {
	return true
}

// IsRedirect returns true when this list dashboard names o k response has a 3xx status code
func (o *ListDashboardNamesOK) IsRedirect() bool {
	return false
}

// IsClientError returns true when this list dashboard names o k response has a 4xx status code
func (o *ListDashboardNamesOK) IsClientError() bool {
	return false
}

// IsServerError returns true when this list dashboard names o k response has a 5xx status code
func (o *ListDashboardNamesOK) IsServerError() bool {
	return false
}

// IsCode returns true when this list dashboard names o k response a status code equal to that given
func (o *ListDashboardNamesOK) IsCode(code int) bool {
	return code == 200
}

// Code gets the status code for the list dashboard names o k response
func (o *ListDashboardNamesOK) Code() int {
	return 200
}

func (o *ListDashboardNamesOK) Error() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesOK  %+v", 200, o.Payload)
}

func (o *ListDashboardNamesOK) String() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesOK  %+v", 200, o.Payload)
}

func (o *ListDashboardNamesOK) GetPayload() *service_model.V1ListDashboardsResponse {
	return o.Payload
}

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

	o.Payload = new(service_model.V1ListDashboardsResponse)

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

	return nil
}

// NewListDashboardNamesNoContent creates a ListDashboardNamesNoContent with default headers values
func NewListDashboardNamesNoContent() *ListDashboardNamesNoContent {
	return &ListDashboardNamesNoContent{}
}

/*
ListDashboardNamesNoContent describes a response with status code 204, with default header values.

No content.
*/
type ListDashboardNamesNoContent struct {
	Payload interface{}
}

// IsSuccess returns true when this list dashboard names no content response has a 2xx status code
func (o *ListDashboardNamesNoContent) IsSuccess() bool {
	return true
}

// IsRedirect returns true when this list dashboard names no content response has a 3xx status code
func (o *ListDashboardNamesNoContent) IsRedirect() bool {
	return false
}

// IsClientError returns true when this list dashboard names no content response has a 4xx status code
func (o *ListDashboardNamesNoContent) IsClientError() bool {
	return false
}

// IsServerError returns true when this list dashboard names no content response has a 5xx status code
func (o *ListDashboardNamesNoContent) IsServerError() bool {
	return false
}

// IsCode returns true when this list dashboard names no content response a status code equal to that given
func (o *ListDashboardNamesNoContent) IsCode(code int) bool {
	return code == 204
}

// Code gets the status code for the list dashboard names no content response
func (o *ListDashboardNamesNoContent) Code() int {
	return 204
}

func (o *ListDashboardNamesNoContent) Error() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesNoContent  %+v", 204, o.Payload)
}

func (o *ListDashboardNamesNoContent) String() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesNoContent  %+v", 204, o.Payload)
}

func (o *ListDashboardNamesNoContent) GetPayload() interface{} {
	return o.Payload
}

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

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

	return nil
}

// NewListDashboardNamesForbidden creates a ListDashboardNamesForbidden with default headers values
func NewListDashboardNamesForbidden() *ListDashboardNamesForbidden {
	return &ListDashboardNamesForbidden{}
}

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

You don't have permission to access the resource.
*/
type ListDashboardNamesForbidden struct {
	Payload interface{}
}

// IsSuccess returns true when this list dashboard names forbidden response has a 2xx status code
func (o *ListDashboardNamesForbidden) IsSuccess() bool {
	return false
}

// IsRedirect returns true when this list dashboard names forbidden response has a 3xx status code
func (o *ListDashboardNamesForbidden) IsRedirect() bool {
	return false
}

// IsClientError returns true when this list dashboard names forbidden response has a 4xx status code
func (o *ListDashboardNamesForbidden) IsClientError() bool {
	return true
}

// IsServerError returns true when this list dashboard names forbidden response has a 5xx status code
func (o *ListDashboardNamesForbidden) IsServerError() bool {
	return false
}

// IsCode returns true when this list dashboard names forbidden response a status code equal to that given
func (o *ListDashboardNamesForbidden) IsCode(code int) bool {
	return code == 403
}

// Code gets the status code for the list dashboard names forbidden response
func (o *ListDashboardNamesForbidden) Code() int {
	return 403
}

func (o *ListDashboardNamesForbidden) Error() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesForbidden  %+v", 403, o.Payload)
}

func (o *ListDashboardNamesForbidden) String() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesForbidden  %+v", 403, o.Payload)
}

func (o *ListDashboardNamesForbidden) GetPayload() interface{} {
	return o.Payload
}

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

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

	return nil
}

// NewListDashboardNamesNotFound creates a ListDashboardNamesNotFound with default headers values
func NewListDashboardNamesNotFound() *ListDashboardNamesNotFound {
	return &ListDashboardNamesNotFound{}
}

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

Resource does not exist.
*/
type ListDashboardNamesNotFound struct {
	Payload interface{}
}

// IsSuccess returns true when this list dashboard names not found response has a 2xx status code
func (o *ListDashboardNamesNotFound) IsSuccess() bool {
	return false
}

// IsRedirect returns true when this list dashboard names not found response has a 3xx status code
func (o *ListDashboardNamesNotFound) IsRedirect() bool {
	return false
}

// IsClientError returns true when this list dashboard names not found response has a 4xx status code
func (o *ListDashboardNamesNotFound) IsClientError() bool {
	return true
}

// IsServerError returns true when this list dashboard names not found response has a 5xx status code
func (o *ListDashboardNamesNotFound) IsServerError() bool {
	return false
}

// IsCode returns true when this list dashboard names not found response a status code equal to that given
func (o *ListDashboardNamesNotFound) IsCode(code int) bool {
	return code == 404
}

// Code gets the status code for the list dashboard names not found response
func (o *ListDashboardNamesNotFound) Code() int {
	return 404
}

func (o *ListDashboardNamesNotFound) Error() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesNotFound  %+v", 404, o.Payload)
}

func (o *ListDashboardNamesNotFound) String() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] listDashboardNamesNotFound  %+v", 404, o.Payload)
}

func (o *ListDashboardNamesNotFound) GetPayload() interface{} {
	return o.Payload
}

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

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

	return nil
}

// NewListDashboardNamesDefault creates a ListDashboardNamesDefault with default headers values
func NewListDashboardNamesDefault(code int) *ListDashboardNamesDefault {
	return &ListDashboardNamesDefault{
		_statusCode: code,
	}
}

/*
ListDashboardNamesDefault describes a response with status code -1, with default header values.

An unexpected error response.
*/
type ListDashboardNamesDefault struct {
	_statusCode int

	Payload *service_model.RuntimeError
}

// IsSuccess returns true when this list dashboard names default response has a 2xx status code
func (o *ListDashboardNamesDefault) IsSuccess() bool {
	return o._statusCode/100 == 2
}

// IsRedirect returns true when this list dashboard names default response has a 3xx status code
func (o *ListDashboardNamesDefault) IsRedirect() bool {
	return o._statusCode/100 == 3
}

// IsClientError returns true when this list dashboard names default response has a 4xx status code
func (o *ListDashboardNamesDefault) IsClientError() bool {
	return o._statusCode/100 == 4
}

// IsServerError returns true when this list dashboard names default response has a 5xx status code
func (o *ListDashboardNamesDefault) IsServerError() bool {
	return o._statusCode/100 == 5
}

// IsCode returns true when this list dashboard names default response a status code equal to that given
func (o *ListDashboardNamesDefault) IsCode(code int) bool {
	return o._statusCode == code
}

// Code gets the status code for the list dashboard names default response
func (o *ListDashboardNamesDefault) Code() int {
	return o._statusCode
}

func (o *ListDashboardNamesDefault) Error() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] ListDashboardNames default  %+v", o._statusCode, o.Payload)
}

func (o *ListDashboardNamesDefault) String() string {
	return fmt.Sprintf("[GET /api/v1/orgs/{owner}/dashboards/names][%d] ListDashboardNames default  %+v", o._statusCode, o.Payload)
}

func (o *ListDashboardNamesDefault) GetPayload() *service_model.RuntimeError {
	return o.Payload
}

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

	o.Payload = new(service_model.RuntimeError)

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

	return nil
}

repository: polyaxon/sdks

repo_name: polyaxon/sdks

gha_language: Java


text:
package main

import (
    "github.com/google/gopacket"
    "github.com/google/gopacket/pcap"
    "github.com/davecgh/go-spew/spew"
)

const (
    InterfaceName    = "any"
//    FilterExpression = "port 443"
    FilterExpression = "tcp and port 443 and tcp[(((tcp[12:1] & 0xf0) >> 2)):1] = 0x16 and ((tcp[(((tcp[12:1] & 0xf0) >> 2)+5):1] = 0x01) or (tcp[(((tcp[12:1] & 0xf0) >> 2)+5):1] = 0x02))"
)

func main () {
    // open device(s) for reading
    if handle, err := pcap.OpenLive(InterfaceName, 1600, true, pcap.BlockForever); err != nil {
        panic(err)
    // set filter
    } else if err := handle.SetBPFFilter(FilterExpression); err != nil {
        panic(err)
    } else {
        // start capture
        packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
        // handle packets
        for packet := range packetSource.Packets() {
            spew.Dump(packet)
        }
    }
}

repository: rahulsom/TLSHandshakeDecoder

repo_name: rahulsom/TLSHandshakeDecoder


text:
SUMMARY = "HTTP library with thread-safe connection pooling, file post, and more."
HOMEPAGE = "https://urllib3.readthedocs.io/"
AUTHOR = "Andrey Petrov <andrey.petrov@shazow.net>"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=c2823cb995439c984fd62a973d79815c"

SRC_URI = "https://files.pythonhosted.org/packages/b0/b1/7bbf5181f8e3258efae31702f5eab87d8a74a72a0aa78bc8c08c1466e243/urllib3-1.26.8.tar.gz"
SRC_URI[md5sum] = "50831ca7b19bbe2781abb0a4c2d51760"
SRC_URI[sha256sum] = "0e7c33d9a63e7ddfcb86780aac87befc2fbddf46c58dbb487e0855f7ceec283c"

S = "${WORKDIR}/urllib3-1.26.8"

RDEPENDS:${PN} = ""

inherit setuptools3


text:
/**
 * @file   logsumexp_wirelength_cuda_atomic.cpp
 * @author Yibo Lin
 * @date   Jul 2018
 * @brief  Compute log-sum-exp wirelength and gradient according to NTUPlace3
 */
#include "utility/src/torch.h"
#include "utility/src/utils.h"

DREAMPLACE_BEGIN_NAMESPACE

template <typename T, typename V>
int computeLogSumExpWirelengthCudaAtomicLauncher(
    const T* x, const T* y, const int* pin2net_map,
    const unsigned char* net_mask, int num_nets, int num_pins, const T* gamma,
    T* exp_xy, T* exp_nxy, T* exp_xy_sum, T* exp_nxy_sum, V* xy_max, V* xy_min,
    T* partial_wl,  // wirelength of each net
    const T* grad_tensor, T* grad_x_tensor,
    T* grad_y_tensor  // the gradient is partial total wirelength to partial pin
                      // position
);

/// @brief add net weights to gradient
template <typename T>
void integrateNetWeightsCudaLauncher(const int* pin2net_map,
                                     const unsigned char* net_mask,
                                     const T* net_weights, T* grad_x_tensor,
                                     T* grad_y_tensor, int num_pins);

typedef int V;

/// @brief Compute log-sum-exp wirelength according to NTUPlace3
///     gamma * (log(\sum exp(x_i/gamma)) + log(\sum exp(-x_i/gamma)))
/// @param pos cell locations, array of x locations and then y locations
/// @param pin2net_map map pin to net
/// @param net_weights weight of nets
/// @param net_mask an array to record whether compute the where for a net or
/// not
/// @param gamma a scalar tensor for the parameter in the equation
std::vector<at::Tensor> logsumexp_wirelength_atomic_forward(
    at::Tensor pos, at::Tensor pin2net_map, at::Tensor net_weights,
    at::Tensor net_mask,
    at::Tensor gamma  // a scalar tensor
) {
  CHECK_FLAT_CUDA(pos);
  CHECK_EVEN(pos);
  CHECK_CONTIGUOUS(pos);
  CHECK_FLAT_CUDA(pin2net_map);
  CHECK_CONTIGUOUS(pin2net_map);
  CHECK_FLAT_CUDA(net_weights);
  CHECK_CONTIGUOUS(net_weights);
  CHECK_FLAT_CUDA(net_mask);
  CHECK_CONTIGUOUS(net_mask);

  int num_nets = net_mask.numel();
  int num_pins = pin2net_map.numel();

  // log-sum-exp for x, log-sum-exp for -x, log-sum-exp for y, log-sum-exp for
  // -y
  at::Tensor partial_wl = at::zeros({4, num_nets}, pos.options());
  at::Tensor exp_xy = at::zeros_like(pos);
  at::Tensor exp_nxy = at::zeros_like(pos);
  at::Tensor exp_xy_sum = at::zeros({2, num_nets}, pos.options());
  at::Tensor exp_nxy_sum = at::zeros({2, num_nets}, pos.options());

  // it is ok for xy_max and xy_min to be integer
  // we do not really need accurate max/min, just some values to scale x/y
  // therefore, there is no need to scale xy_max and xy_min to improve accuracy
  at::Tensor xy_max = at::full({2, num_nets}, std::numeric_limits<V>::min(),
                               at::CUDA(at::kInt));
  at::Tensor xy_min = at::full({2, num_nets}, std::numeric_limits<V>::max(),
                               at::CUDA(at::kInt));

  DREAMPLACE_DISPATCH_FLOATING_TYPES(
      pos, "computeLogSumExpWirelengthCudaAtomicLauncher", [&] {
        computeLogSumExpWirelengthCudaAtomicLauncher<scalar_t, V>(
            DREAMPLACE_TENSOR_DATA_PTR(pos, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(pos, scalar_t) + num_pins,
            DREAMPLACE_TENSOR_DATA_PTR(pin2net_map, int),
            DREAMPLACE_TENSOR_DATA_PTR(net_mask, unsigned char), num_nets,
            num_pins, DREAMPLACE_TENSOR_DATA_PTR(gamma, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_xy, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_nxy, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_xy_sum, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_nxy_sum, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(xy_max, V),
            DREAMPLACE_TENSOR_DATA_PTR(xy_min, V),
            DREAMPLACE_TENSOR_DATA_PTR(partial_wl, scalar_t), nullptr, nullptr,
            nullptr);
      });

  if (net_weights.numel()) {
    partial_wl.mul_(net_weights.view({1, num_nets}));
  }
  // significant speedup is achieved by using summation in ATen
  auto wl = partial_wl.sum();
  return {wl, exp_xy, exp_nxy, exp_xy_sum, exp_nxy_sum};
}

/// @brief Compute gradient
/// @param grad_pos input gradient from back-propagation
/// @param pos locations of pins
/// @param exp_xy array of exp(x/gamma) and then exp(y/gamma)
/// @param exp_nxy array of exp(-x/gamma) and then exp(-y/gamma)
/// @param exp_xy_sum array of \sum(exp(x/gamma)) for each net and then
/// \sum(exp(y/gamma))
/// @param exp_nxy_sum array of \sum(exp(-x/gamma)) for each net and then
/// \sum(exp(-y/gamma))
/// @param pin2net_map map pin to net
/// @param net_weights weight of nets
/// @param net_mask an array to record whether compute the where for a net or
/// not
/// @param gamma a scalar tensor for the parameter in the equation
at::Tensor logsumexp_wirelength_atomic_backward(
    at::Tensor grad_pos, at::Tensor pos, at::Tensor exp_xy, at::Tensor exp_nxy,
    at::Tensor exp_xy_sum, at::Tensor exp_nxy_sum, at::Tensor pin2net_map,
    at::Tensor net_weights, at::Tensor net_mask,
    at::Tensor gamma  // a scalar tensor
) {
  CHECK_FLAT_CUDA(pos);
  CHECK_EVEN(pos);
  CHECK_CONTIGUOUS(pos);
  CHECK_FLAT_CUDA(exp_xy);
  CHECK_EVEN(exp_xy);
  CHECK_CONTIGUOUS(exp_xy);
  CHECK_FLAT_CUDA(exp_nxy);
  CHECK_EVEN(exp_nxy);
  CHECK_CONTIGUOUS(exp_nxy);
  CHECK_FLAT_CUDA(exp_xy_sum);
  CHECK_EVEN(exp_xy_sum);
  CHECK_CONTIGUOUS(exp_xy_sum);
  CHECK_FLAT_CUDA(exp_nxy_sum);
  CHECK_EVEN(exp_nxy_sum);
  CHECK_CONTIGUOUS(exp_nxy_sum);
  CHECK_FLAT_CUDA(pin2net_map);
  CHECK_CONTIGUOUS(pin2net_map);
  CHECK_FLAT_CUDA(net_weights);
  CHECK_CONTIGUOUS(net_weights);
  CHECK_FLAT_CUDA(net_mask);
  CHECK_CONTIGUOUS(net_mask);

  at::Tensor grad_out = at::zeros_like(pos);

  int num_nets = net_mask.numel();
  int num_pins = pin2net_map.numel();

  DREAMPLACE_DISPATCH_FLOATING_TYPES(
      pos, "computeLogSumExpWirelengthCudaAtomicLauncher", [&] {
        computeLogSumExpWirelengthCudaAtomicLauncher<scalar_t, V>(
            DREAMPLACE_TENSOR_DATA_PTR(pos, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(pos, scalar_t) + num_pins,
            DREAMPLACE_TENSOR_DATA_PTR(pin2net_map, int),
            DREAMPLACE_TENSOR_DATA_PTR(net_mask, unsigned char), num_nets,
            num_pins, DREAMPLACE_TENSOR_DATA_PTR(gamma, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_xy, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_nxy, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_xy_sum, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(exp_nxy_sum, scalar_t), nullptr, nullptr,
            nullptr, DREAMPLACE_TENSOR_DATA_PTR(grad_pos, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(grad_out, scalar_t),
            DREAMPLACE_TENSOR_DATA_PTR(grad_out, scalar_t) + num_pins);
        if (net_weights.numel()) {
          integrateNetWeightsCudaLauncher(
              DREAMPLACE_TENSOR_DATA_PTR(pin2net_map, int),
              DREAMPLACE_TENSOR_DATA_PTR(net_mask, unsigned char),
              DREAMPLACE_TENSOR_DATA_PTR(net_weights, scalar_t),
              DREAMPLACE_TENSOR_DATA_PTR(grad_out, scalar_t),
              DREAMPLACE_TENSOR_DATA_PTR(grad_out, scalar_t) + num_pins,
              num_pins);
        }
      });
  return grad_out;
}

DREAMPLACE_END_NAMESPACE

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  m.def("forward", &DREAMPLACE_NAMESPACE::logsumexp_wirelength_atomic_forward,
        "LogSumExpWirelength forward (CUDA)");
  m.def("backward", &DREAMPLACE_NAMESPACE::logsumexp_wirelength_atomic_backward,
        "LogSumExpWirelength backward (CUDA)");
}

extension: cpp


text:
package date

import "time"

const (
	apiDateLayout   = "2006-01-02T15:04:05Z"
	apiDbDateLayout = "2006-01-02 15:04:05"
)

//GetNow - Returns current time in standard zone (UTC)
func GetNow() time.Time {
	return time.Now().UTC()
}

//GetNowString - Same as GetNow but this returns as a formatted string
func GetNowString() string {
	return GetNow().Format(apiDateLayout)
}

func GetNowDBString() string {
	return GetNow().Format(apiDbDateLayout)
}