text:
@proceedings{naacl-2019-2019-north-american,
    title = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    editor = "Kar, Sudipta  and
      Nadeem, Farah  and
      Burdick, Laura  and
      Durrett, Greg  and
      Han, Na-Rae",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3000",
}
@inproceedings{dzendzik-etal-2019-dish,
    title = "Is It Dish Washer Safe? Automatically Answering {``}Yes/No{''} Questions Using Customer Reviews",
    author = "Dzendzik, Daria  and
      Vogel, Carl  and
      Foster, Jennifer",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3001",
    doi = "10.18653/v1/N19-3001",
    pages = "1--6",
}
@inproceedings{bordia-bowman-2019-identifying,
    title = "Identifying and Reducing Gender Bias in Word-Level Language Models",
    author = "Bordia, Shikha  and
      Bowman, Samuel R.",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3002",
    doi = "10.18653/v1/N19-3002",
    pages = "7--15",
}
@inproceedings{munot-nenkova-2019-emotion,
    title = "Emotion Impacts Speech Recognition Performance",
    author = "Munot, Rushab  and
      Nenkova, Ani",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3003",
    doi = "10.18653/v1/N19-3003",
    pages = "16--21",
}
@inproceedings{li-etal-2019-strength,
    title = "The Strength of the Weakest Supervision: Topic Classification Using Class Labels",
    author = "Li, Jiatong  and
      Zheng, Kai  and
      Xu, Hua  and
      Mei, Qiaozhu  and
      Wang, Yue",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3004",
    doi = "10.18653/v1/N19-3004",
    pages = "22--28",
}
@inproceedings{paul-etal-2019-handling,
    title = "Handling Noisy Labels for Robustly Learning from Self-Training Data for Low-Resource Sequence Labeling",
    author = "Paul, Debjit  and
      Singh, Mittul  and
      Hedderich, Michael A.  and
      Klakow, Dietrich",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3005",
    doi = "10.18653/v1/N19-3005",
    pages = "29--34",
}
@inproceedings{han-kando-2019-opinion,
    title = "Opinion Mining with Deep Contextualized Embeddings",
    author = "Han, Wen-Bin  and
      Kando, Noriko",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3006",
    doi = "10.18653/v1/N19-3006",
    pages = "35--42",
}
@inproceedings{chen-etal-2019-bag,
    title = "A Bag-of-concepts Model Improves Relation Extraction in a Narrow Knowledge Domain with Limited Data",
    author = "Chen, Jiyu  and
      Verspoor, Karin  and
      Zhai, Zenan",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3007",
    doi = "10.18653/v1/N19-3007",
    pages = "43--52",
}
@inproceedings{ahamad-2019-generating,
    title = "Generating Text through Adversarial Training Using Skip-Thought Vectors",
    author = "Ahamad, Afroz",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3008",
    doi = "10.18653/v1/N19-3008",
    pages = "53--60",
}
@inproceedings{manning-2019-partially,
    title = "A Partially Rule-Based Approach to {AMR} Generation",
    author = "Manning, Emma",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3009",
    doi = "10.18653/v1/N19-3009",
    pages = "61--70",
}
@inproceedings{kabbara-2019-computational,
    title = "Computational Investigations of Pragmatic Effects in Natural Language",
    author = "Kabbara, Jad",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3010",
    doi = "10.18653/v1/N19-3010",
    pages = "71--76",
}
@inproceedings{morabia-etal-2019-sedtwik,
    title = "{SEDTW}ik: Segmentation-based Event Detection from Tweets Using {W}ikipedia",
    author = "Morabia, Keval  and
      Bhanu Murthy, Neti Lalita  and
      Malapati, Aruna  and
      Samant, Surender",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3011",
    doi = "10.18653/v1/N19-3011",
    pages = "77--85",
}
@inproceedings{hirasawa-etal-2019-multimodal,
    title = "Multimodal Machine Translation with Embedding Prediction",
    author = "Hirasawa, Tosho  and
      Yamagishi, Hayahide  and
      Matsumura, Yukio  and
      Komachi, Mamoru",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3012",
    doi = "10.18653/v1/N19-3012",
    pages = "86--91",
}
@inproceedings{gupta-dipadova-2019-deep,
    title = "Deep Learning and Sociophonetics: Automatic Coding of Rhoticity Using Neural Networks",
    author = "Gupta, Sarah  and
      DiPadova, Anthony",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3013",
    doi = "10.18653/v1/N19-3013",
    pages = "92--96",
}
@inproceedings{kim-etal-2019-data,
    title = "Data Augmentation by Data Noising for Open-vocabulary Slots in Spoken Language Understanding",
    author = "Kim, Hwa-Yeon  and
      Roh, Yoon-Hyung  and
      Kim, Young-Kil",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3014",
    doi = "10.18653/v1/N19-3014",
    pages = "97--102",
}
@inproceedings{dammalapati-etal-2019-expectation,
    title = "Expectation and Locality Effects in the Prediction of Disfluent Fillers and Repairs in {E}nglish Speech",
    author = "Dammalapati, Samvit  and
      Rajkumar, Rajakrishnan  and
      Agarwal, Sumeet",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3015",
    doi = "10.18653/v1/N19-3015",
    pages = "103--109",
}
@inproceedings{balazs-matsuo-2019-gating,
    title = "Gating Mechanisms for Combining Character and Word-level Word Representations: an Empirical Study",
    author = "Balazs, Jorge  and
      Matsuo, Yutaka",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3016",
    doi = "10.18653/v1/N19-3016",
    pages = "110--124",
}
@inproceedings{debnath-shrivastava-2019-pregroup,
    title = "A Pregroup Representation of Word Order Alternation Using {H}indi Syntax",
    author = "Debnath, Alok  and
      Shrivastava, Manish",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3017",
    doi = "10.18653/v1/N19-3017",
    pages = "125--135",
}
@inproceedings{ghosh-chowdhury-etal-2019-speak,
    title = "Speak up, Fight Back! Detection of Social Media Disclosures of Sexual Harassment",
    author = "Ghosh Chowdhury, Arijit  and
      Sawhney, Ramit  and
      Mathur, Puneet  and
      Mahata, Debanjan  and
      Ratn Shah, Rajiv",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3018",
    doi = "10.18653/v1/N19-3018",
    pages = "136--146",
}
@inproceedings{mishra-etal-2019-snap,
    title = "{SNAP}-{BATNET}: Cascading Author Profiling and Social Network Graphs for Suicide Ideation Detection on Social Media",
    author = "Mishra, Rohan  and
      Prakhar Sinha, Pradyumn  and
      Sawhney, Ramit  and
      Mahata, Debanjan  and
      Mathur, Puneet  and
      Ratn Shah, Rajiv",
    booktitle = "Proceedings of the 2019 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Student Research Workshop",
    month = jun,
    year = "2019",
    address = "Minneapolis, Minnesota",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N19-3019",
    doi = "10.18653/v1/N19-3019",
    pages = "147--156",
}

repository: emorynlp/nlprankings

repo_name: emorynlp/nlprankings

gha_license_id: NOASSERTION

gha_language: TeX


text:
package commands

type CommonConfiguration struct {
	AuthenticityToken string `url:"authenticity_token"`
	Method            string `url:"_method"`
}

type GCPIaaSConfiguration struct {
	Project              string `url:"iaas_configuration[project],omitempty" json:"project"`
	DefaultDeploymentTag string `url:"iaas_configuration[default_deployment_tag],omitempty" json:"default_deployment_tag"`
	AuthJSON             string `url:"iaas_configuration[auth_json],omitempty" json:"auth_json"`
}

type AzureIaaSConfiguration struct {
	SubscriptionID                string `url:"iaas_configuration[subscription_id],omitempty" json:"subscription_id"`
	TenantID                      string `url:"iaas_configuration[tenant_id],omitempty" json:"tenant_id"`
	ClientID                      string `url:"iaas_configuration[client_id],omitempty" json:"client_id"`
	ClientSecret                  string `url:"iaas_configuration[client_secret],omitempty" json:"client_secret"`
	ResourceGroupName             string `url:"iaas_configuration[resource_group_name],omitempty" json:"resource_group_name"`
	BoshStorageAccountName        string `url:"iaas_configuration[bosh_storage_account_name],omitempty" json:"bosh_storage_account_name"`
	DefaultSecurityGroup          string `url:"iaas_configuration[default_security_group],omitempty" json:"default_security_group"`
	SSHPublicKey                  string `url:"iaas_configuration[ssh_public_key],omitempty" json:"ssh_public_key"`
	DeploymentsStorageAccountName string `url:"iaas_configuration[deployments_storage_account_name],omitempty" json:"deployments_storage_account_name"`
}

type AWSIaaSConfiguration struct {
	AccessKeyID     string `url:"iaas_configuration[access_key_id],omitempty" json:"access_key_id"`
	SecretAccessKey string `url:"iaas_configuration[secret_access_key],omitempty" json:"secret_access_key"`
	VpcID           string `url:"iaas_configuration[vpc_id],omitempty" json:"vpc_id"`
	SecurityGroup   string `url:"iaas_configuration[security_group],omitempty" json:"security_group"`
	KeyPairName     string `url:"iaas_configuration[key_pair_name],omitempty" json:"key_pair_name"`
	Region          string `url:"iaas_configuration[region],omitempty" json:"region"`
	Encrypted       *bool  `url:"iaas_configuration[encrypted],omitempty" json:"encrypted"`
}

type CommonIaaSConfiguration struct {
	SSHPrivateKey string `url:"iaas_configuration[ssh_private_key],omitempty" json:"ssh_private_key"`
}

type IaaSConfiguration struct {
	GCPIaaSConfiguration
	AzureIaaSConfiguration
	AWSIaaSConfiguration
	CommonIaaSConfiguration
}

type DirectorConfiguration struct {
	NTPServers                string                  `url:"director_configuration[ntp_servers_string],omitempty" json:"ntp_servers_string"`
	MetricsIP                 string                  `url:"director_configuration[metrics_ip],omitempty" json:"metrics_ip"`
	EnableVMResurrectorPlugin *bool                   `url:"director_configuration[resurrector_enabled],omitempty" json:"resurrector_enabled"`
	EnablePostDeployScripts   *bool                   `url:"director_configuration[post_deploy_enabled],omitempty" json:"post_deploy_enabled"`
	RecreateAllVMs            *bool                   `url:"director_configuration[bosh_recreate_on_next_deploy],omitempty" json:"bosh_recreate_on_next_deploy"`
	EnableBoshDeployRetries   *bool                   `url:"director_configuration[retry_bosh_deploys],omitempty" json:"retry_bosh_deploys"`
	HMPagerDutyOptions        HMPagerDutyOptions      `url:"director_configuration[hm_pager_duty_options],omitempty" json:"hm_pager_duty_options,omitempty"`
	HMEmailPlugin             HMEmailPlugin           `url:"director_configuration[hm_emailer_options],omitempty" json:"hm_emailer_options,omitempty"`
	BlobStoreType             string                  `url:"director_configuration[blobstore_type],omitempty" json:"blobstore_type"`
	S3BlobstoreOptions        S3BlobstoreOptions      `url:"director_configuration[s3_blobstore_options],omitempty" json:"s3_blobstore_options,omitempty"`
	DatabaseType              string                  `url:"director_configuration[database_type],omitempty" json:"database_type"`
	ExternalDatabaseOptions   ExternalDatabaseOptions `url:"director_configuration[external_database_options],omitempty" json:"external_database_options,omitempty"`
	MaxThreads                *int                    `url:"director_configuration[max_threads],omitempty" json:"max_threads"`
	DirectorHostname          string                  `url:"director_configuration[director_hostname],omitempty" json:"director_hostname"`
}

type AvailabilityZonesConfiguration struct {
	AvailabilityZones []string `url:"availability_zones[availability_zones][][iaas_identifier],omitempty" json:"availability_zones"`
}

type SecurityConfiguration struct {
	TrustedCertificates string `url:"security_tokens[trusted_certificates],omitempty" json:"trusted_certificates"`
	VMPasswordType      string `url:"security_tokens[vm_password_type],omitempty" json:"vm_password_type"`
}

type BoshConfiguration struct {
	IaaSConfiguration
	DirectorConfiguration
	AvailabilityZonesConfiguration
	SecurityConfiguration
	CommonConfiguration
}

type HMPagerDutyOptions struct {
	Enabled    *bool  `url:"enabled,omitempty" json:"enabled"`
	ServiceKey string `url:"service_key,omitempty" json:"service_key"`
	HTTPProxy  string `url:"http_proxy,omitempty" json:"http_proxy"`
}

type HMEmailPlugin struct {
	Enabled    *bool  `url:"enabled,omitempty" json:"enabled"`
	Host       string `url:"host,omitempty" json:"host"`
	Port       *int   `url:"port,omitempty" json:"port"`
	Domain     string `url:"domain,omitempty" json:"domain"`
	From       string `url:"from,omitempty" json:"from"`
	Recipients string `url:"recipients[value],omitempty" json:"recipients"`
	Username   string `url:"smtp_user,omitempty" json:"smtp_user"`
	Password   string `url:"smtp_password,omitempty" json:"smtp_password"`
	TLS        *bool  `url:"tls,omitempty" json:"tls"`
}

type S3BlobstoreOptions struct {
	Endpoint         string `url:"endpoint,omitempty" json:"endpoint"`
	BucketName       string `url:"bucket_name,omitempty" json:"bucket_name"`
	Accesskey        string `url:"access_key,omitempty" json:"access_key"`
	SecretKey        string `url:"secret_key,omitempty" json:"secret_key"`
	SignatureVersion string `url:"signature_version,omitempty" json:"signature_version"`
	Region           string `url:"region,omitempty" json:"region"`
}

type ExternalDatabaseOptions struct {
	Host     string `url:"host,omitempty" json:"host"`
	Port     *int   `url:"port,omitempty" json:"port"`
	Username string `url:"user,omitempty" json:"user"`
	Password string `url:"password,omitempty" json:"password"`
	Database string `url:"database,omitempty" json:"database"`
}

repository: adi-mishra/om

license_type: permissive

repo_name: adi-mishra/om

branch_name: refs/heads/master

extension: go


text:
package main

// RequestContext holds request struct
type RequestContext struct {
	Request        *AuthorizationRequest
	ServiceAccount *ServiceAccount
	Username       string
	UserGroups     []string
}

// NewRequestContext builds request context out of req object
func NewRequestContext(req *AuthorizationRequest) *RequestContext {
	username := req.Spec.User
	usergroups := req.Spec.Group
	serviceAccount := NewServiceAccount(username)

	return &RequestContext{
		Request:        req,
		ServiceAccount: serviceAccount,
		Username:       username,
		UserGroups:     usergroups,
	}
}


text:
DESCRIPTION = "Open webOS edition of the server-side JavaScript environment that uses a \
asynchronous event-driven model."
AUTHOR = "Joyent, Inc. and other Node contributors"
LICENSE = "MIT & Zlib"
LIC_FILES_CHKSUM = "file://LICENSE;md5=d6237f3a840aef5b7880fb4e49eecfe5"
PV = "0.4.12-webos2+gitr${SRCPV}"
PR = "r1"

DEPENDS = "openssl"

SRC_URI = "git://github.com/openwebos/nodejs.git;protocol=http;branch=master"
S = "${WORKDIR}/git"
SRCREV = "3cd6a1367e1d697eef8b69f5fd6e35774db93244"

inherit cmake pythonnative

# build out of the source tree, otherwise the build will fail
OECMAKE_SOURCEPATH = ".."
OECMAKE_BUILDPATH = "build"
# select correct core os option; rockhopper is HP/Palms development platform
EXTRA_OECMAKE="-DTARGET_CORE_OS=rockhopper -DCMAKE_SYSTEM_PROCESSOR=arm"

license: MIT

extension: bb


text:
DESCRIPTION = "slsnif is a serial line sniffer. \
It listens to the specified serial port and logs all data coming through it. \
slsnif works transparently for both the device connected to the serial port \
and the controlling software for this device."
LICENSE = "GPL"
SECTION = "console"
PR = "r0"

SRC_URI = "http://www.dakotacom.net/~ymg/files/slsnif-${PV}.tar.gz"

inherit autotools

SRC_URI[md5sum] = "78eeff8ba36ee0c3a954ec0878d2a997"
SRC_URI[sha256sum] = "315eb08a14255c137b435cb4f3c1dbfa67427be1c6bec62ff77a54246161c83e"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


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

package testdata

// Sandbox is a default JSON config for a sandbox.
const Sandbox = `
{
    "metadata": {
        "name": "default-sandbox",
        "namespace": "default",
        "attempt": 1,
        "uid": "hdishd83djaidwnduwk28bcsb"
    },
    "linux": {
    },
    "log_directory": "/tmp"
}
`

repository: comzyh/gvisor

repo_name: comzyh/gvisor


text:
package main

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"

	"github.com/cloudfoundry/cli/plugin"
)

// CliBuildpackUsage represents Buildpack Usage CLI interface
type CliBuildpackUsage struct{}

// AppSearchResults represents top level attributes of JSON response from Cloud Foundry API
type AppSearchResults struct {
	TotalResults int                  `json:"total_results"`
	Resources    []AppSearchResources `json:"resources"`
}

// AppSearchResources represents resources attribute of JSON response from Cloud Foundry API
type AppSearchResources struct {
	Entity AppSearchEntity `json:"entity"`
}

// AppSearchEntity represents entity attribute of resources attribute within JSON response from Cloud Foundry API
type AppSearchEntity struct {
	Name              string `json:"name"`
	Buildpack         string `json:"buildpack"`
	DetectedBuildpack string `json:"detected_buildpack"`
}

// GetMetadata provides the Cloud Foundry CLI with metadata to provide user about how to use buildpack-usage command
func (c *CliBuildpackUsage) GetMetadata() plugin.PluginMetadata {
	return plugin.PluginMetadata{
		Name: "CliBuildpackUsage",
		Version: plugin.VersionType{
			Major: 1,
			Minor: 0,
			Build: 0,
		},
		Commands: []plugin.Command{
			{
				Name:     "buildpack-usage",
				HelpText: "Command to view buildpack usage in current CLI target context.",
				UsageDetails: plugin.Usage{
					Usage: "buildpack-usage\n   cf buildpack-usage",
				},
			},
		},
	}
}

func main() {
	plugin.Start(new(CliBuildpackUsage))
}

// RemoveDuplicates makes the strings in a given slice all unique
func RemoveDuplicates(xs *sort.StringSlice) {
	found := make(map[string]bool)
	j := 0
	for i, x := range *xs {
		if !found[x] {
			found[x] = true
			(*xs)[j] = (*xs)[i]
			j++
		}
	}
	*xs = (*xs)[:j]
}

// Run is what is executed by the Cloud Foundry CLI when the buildpack-usage command is specified
func (c CliBuildpackUsage) Run(cliConnection plugin.CliConnection, args []string) {
	res := c.GetAppData(cliConnection)

	var buildpacksUsed sort.StringSlice

	for _, val := range res.Resources {
		bp := val.Entity.Buildpack
		if bp == "" {
			bp = val.Entity.DetectedBuildpack
		}
		buildpacksUsed = append(buildpacksUsed, bp)
	}

	RemoveDuplicates(&buildpacksUsed)
	buildpacksUsed.Sort()

	fmt.Println("")
	fmt.Printf("%v buildpacks found across %v app deployments\n\n", len(buildpacksUsed), res.TotalResults)
	fmt.Printf("Buildpacks Used\n----------------\n")
	for _, buildpack := range buildpacksUsed {
		fmt.Printf("%v\n", buildpack)
	}
}

// GetAppData requests all of the Application data from Cloud Foundry
func (c CliBuildpackUsage) GetAppData(cliConnection plugin.CliConnection) AppSearchResults {
	//  "total_pages": 2,
	//  "prev_url": null,
	//  "next_url": "/v2/apps?order-direction=asc&page=2&results-per-page=100",

	cmd := []string{"curl", "/v2/apps?results-per-page=100"}
	output, _ := cliConnection.CliCommandWithoutTerminalOutput(cmd...)
	res := &AppSearchResults{}
	json.Unmarshal([]byte(strings.Join(output, "")), &res)

	return *res
}


text:
DESCRIPTION = "The Event Notify Test Runner (entr) is a general purpose Unix utility intended to make rapid feedback and automated testing natural and completely ordinary."
HOMEPAGE = "http://smarden.org/runit/"

LICENSE = "ISC"
PR = "r1"

SRC_URI = "http://entrproject.org/code/entr-${PV}.tar.gz"
LIC_FILES_CHKSUM = "file://LICENSE;md5=261f92e548f84496f9216ce8d1be78ee"

SRC_URI[md5sum] = "072eed7153296a8fae6ebdedefed9fd4"
SRC_URI[sha256sum] = "a42746d81c548d7e557d500f93422b8ec9731d719309eb2601b8be69ae0dc8eb"

S = "${WORKDIR}/eradman-entr-c15b0be493fc"
EXTRA_OEMAKE += "CFLAGS='-D_GNU_SOURCE -D_LINUX_PORT -Imissing -DRELEASE=\"3.6\"'"

do_configure() {
        cd ${S}
        DESTDIR=${D} ./configure
}

do_compile() {
	oe_runmake
}

do_install() {
	install -d ${D}${bindir}
	install -m 0755 ${S}/entr ${D}${bindir}
}


text:
@inproceedings{Sethi2014,
 author = {Sethi, A.  and Tapio, V. and Juntti, M.},
 booktitle = {Wireless Communications and Networking Conference (WCNC), 2014 IEEE},
 doi = {10.1109/WCNC.2014.6952167},
 month = {April},
 organization = {IEEE},
 pages = {781--785},
 title = {Self-interference channel for full duplex transceivers},
 year = {2014}
}

repository: aloksethi/academic-kickstart

repo_name: aloksethi/academic-kickstart

extension: bib


text:
DESCRIPTION = "GStreamer plug-in that allows communication with OpenMAX IL components"
AUTHOR = "Katsuya Matsubara <matsu@igel.co.jp>"
BUGTRACKER = ""

DEFAULT_PREFERENCE = "-1"
DEPENDS = "gstreamer"
RDEPENDS_${PN} = "libomxil"
LICENSE = "LGPLv2.1"
LICENSE_FLAGS = "commercial"

require gst-plugins.inc
inherit gettext

LIBV="0.10"
PR = "r1"

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

LIC_FILES_CHKSUM = "file://COPYING;md5=fbc093901857fcd118f065f900982c24"
EXTRA_OECONF += "--disable-valgrind"

# for armadillo800eva
SRCREV_armadillo800eva = "43e0be40d82f83308d0a17cd74060b280c30c2a8"
SRC_URI_armadillo800eva = " \
    git://github.com/matsu/gst-openmax.git \
    file://gst-openmax.conf \
"

SRCREV = "3dad1ec6803bb2f2627188ce0e957dbeaa57b1be"
SRC_URI = " \
    git://github.com/renesas-devel/gst-openmax.git \
    file://0001-base_videodec-change-the-tile-height-for-T-L-address.patch \
    file://0001-Stop-using-deprecated-GLib-thread-API.patch \
    file://disable_configure.patch \
"

S = "${WORKDIR}/git/"

# for -Werror-deprecated-declarations
CPPFLAGS += "-Wno-deprecated-declarations"
EXTRA_OECONF := "${@'${EXTRA_OECONF}'.replace('--disable-experimental', '--enable-experimental')}"

do_configure_prepend() {
    (cd ${S}; sh autogen.sh --noconfigure)
}

do_install_append_armadillo800eva() {
    install -d ${D}/home/root/.config/
    install -m 644 ${WORKDIR}/gst-openmax.conf ${D}/home/root/.config/.
}

FILES_${PN} += "${libdir}/gstreamer-${LIBV}/libgstomx.so /home/root/.config"
FILES_${PN}-dev += "${libdir}/gstreamer-0.10/libgstomx.la"
FILES_${PN}-staticdev += "${libdir}/gstreamer-0.10/libgstomx.a"
FILES_${PN}-dbg += "${libdir}/gstreamer-0.10/.debug/"

gha_language: Python


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

# Usage:
# enum2str_generate
#    PATH           <path to generate files in>
#    CLASS_NAME     <name of the class (file names will be PATH/CLASS_NAME.{hpp,cpp})>
#    FUNC_NAME      <the name of the function>
#    INCLUDES       <files to include (where the enums are)>
#    NAMESPACE      <namespace to use>
#    ENUMS          <list of enums to generate>
#    BLACKLIST      <blacklist for enum constants>
#    USE_CONSTEXPR  <whether to use constexpr or not (default: off)>
#    USE_C_STRINGS  <whether to use c strings instead of std::string or not (default: off)>
function( enum2str_generate )
   set( TARGET_LIST PATH CLASS_NAME FUNC_NAME INCLUDES ENUMS NAMESPACE BLACKLIST USE_CONSTEXPR USE_C_STRINGS )
   math( EXPR ARGC_M1 "${ARGC} - 1" )

   #########################################
   # Split ars into sections (TARGET_LIST) #
   #########################################

   foreach( I RANGE 0 ${ARGC_M1} )
      set( ARG ${ARGV${I}} )
      set( SKIP OFF )
      foreach( J IN LISTS TARGET_LIST )
         if( ARG STREQUAL J )
            set( CURRENT_TARGET ${ARG} )
            set( ${ARG} )
            set( SKIP ON )
            break()
         endif( ARG STREQUAL J )
      endforeach( J IN LISTS TARGET_LIST )

      if( SKIP )
         continue()
      endif( SKIP )

      if( CURRENT_TARGET STREQUAL "" )
         message( WARNING "enum2str_generate: no target set; skip ${ARG}" )
         continue()
      endif( CURRENT_TARGET STREQUAL "" )

      list( APPEND ${CURRENT_TARGET} ${ARG} )
   endforeach( I RANGE 1 ${ARGC_M1} )

   if( USE_C_STRINGS )
      set( STRING_TYPE "const char *" )
   else( USE_C_STRINGS )
      set( STRING_TYPE "std::string " )
   endif( USE_C_STRINGS )

   message( STATUS "Generating enum2str files" )

   __enum2str_checkSet( PATH )
   __enum2str_checkSet( CLASS_NAME )
   __enum2str_checkSet( NAMESPACE )
   __enum2str_checkSet( FUNC_NAME )

   set( HPP_FILE "${PATH}/${CLASS_NAME}.hpp" )
   set( CPP_FILE "${PATH}/${CLASS_NAME}.cpp" )

   enum2str_init()

   #########################
   # Loading include files #
   #########################

   get_property( INC_DIRS DIRECTORY ${CMAKE_HOME_DIRECTORY} PROPERTY INCLUDE_DIRECTORIES )
   message( STATUS "  - Resolving includes:" )

   foreach( I IN LISTS INCLUDES )
      set( FOUND 0 )
      set( TEMP )
      find_path( TEMP NAMES ${I} )
      list( APPEND INC_DIRS ${TEMP} )
      foreach( J IN LISTS INC_DIRS )
         if( EXISTS "${J}/${I}" )
            message( STATUS "    - ${I}: ${J}/${I}" )
            file( READ "${J}/${I}" TEMP )
            string( APPEND RAW_DATA "${TEMP}" )
            set( FOUND 1 )
            break()
         endif( EXISTS "${J}/${I}" )
      endforeach( J IN LISTS INC_DIRS )

      if( NOT "${FOUND}" STREQUAL "1" )
         message( FATAL_ERROR "Unable to find ${I}! (Try running include_directories(...))" )
      endif( NOT "${FOUND}" STREQUAL "1" )
   endforeach( I IN LISTS INCLUDES )

   #####################
   # Finding the enums #
   #####################

   set( CONSTANSTS 0 )

   foreach( I IN LISTS ENUMS )
      set( ENUM_NS "" )
      string( REGEX REPLACE ".*::" "" ENUM_NAME "${I}" )
      if( "${I}" MATCHES "(.*)::[^:]+" )
         string( REGEX REPLACE "(.*)::[^:]+" "\\1::" ENUM_NS "${I}" )
      endif( "${I}" MATCHES "(.*)::[^:]+" )

      string( REGEX MATCH "enum[ \t\n]+${ENUM_NAME}[ \t\n]+(:[^{]+)?{[^}]*}" P1 "${RAW_DATA}" )
      if( "${P1}" STREQUAL "" )
         string( REGEX MATCH "enum[ \t\n]+{[^}]*}[ \t\n]+${ENUM_NAME};" P1 "${RAW_DATA}" )

         if( "${P1}" STREQUAL "" )
            message( WARNING "enum '${I}' not found!" )
            continue()
         endif( "${P1}" STREQUAL "" )
      endif( "${P1}" STREQUAL "" )
      string( REGEX REPLACE "//[^\n]*" "" P1 "${P1}" )
      string( REGEX REPLACE "/\\*[^\\*]*\\*/" "" P1 "${P1}" )
      string( REGEX REPLACE "enum[ \t\n]+${ENUM_NAME}[ \t\n]+(:[^{]+)?" "" P1 "${P1}" )
      string( REGEX REPLACE "enum[ \t\n]{" "" P1 "${P1}" )
      string( REGEX REPLACE "}[ \t\n]*${ENUM_NAME}[ \t\n]*;" "" P1 "${P1}" )
      string( REGEX REPLACE "[ \t\n{};]" "" P1 "${P1}" )
      string( REGEX REPLACE ",$" "" P1 "${P1}" ) # Remove trailing ,
      string( REGEX REPLACE "," ";" L1 "${P1}" ) # Make a List

      set( ENUMS_TO_USE )
      set( RESULTS )

      # Checking enums
      foreach( J IN LISTS L1 )
         set( EQUALS "" )
         if( "${J}" MATCHES ".+=.+" )
            string( REGEX REPLACE ".+=(.+)" "\\1" EQUALS "${J}" )
         endif( "${J}" MATCHES ".+=.+" )
         string( REGEX REPLACE "=.*" "" J "${J}" )

         if( "${J}" IN_LIST BLACKLIST )
            continue()
         endif( "${J}" IN_LIST BLACKLIST )

         if( "${EQUALS}" STREQUAL "" )
            list( APPEND ENUMS_TO_USE "${J}" )
         else( "${EQUALS}" STREQUAL "" )
            # Avoid duplicates:
            if( "${J}" IN_LIST ENUMS_TO_USE )
               continue()
            endif( "${J}" IN_LIST ENUMS_TO_USE )
            if( "${EQUALS}" IN_LIST ENUMS_TO_USE )
               continue()
            endif( "${EQUALS}" IN_LIST ENUMS_TO_USE )
            if( "${EQUALS}" IN_LIST RESULTS )
               continue()
            endif( "${EQUALS}" IN_LIST RESULTS )

            list( APPEND RESULTS "${EQUALS}" )
            list( APPEND ENUMS_TO_USE "${J}" )
         endif( "${EQUALS}" STREQUAL "" )
      endforeach( J IN LISTS L1 )

      enum2str_add( "${I}" )
      list( LENGTH ENUMS_TO_USE NUM_ENUMS )
      math( EXPR CONSTANSTS "${CONSTANSTS} + ${NUM_ENUMS}" )
   endforeach( I IN LISTS ENUMS )

   list( LENGTH ENUMS NUM_ENUMS )
   message( STATUS "  - Generated ${NUM_ENUMS} enum2str functions" )
   message( STATUS "  - Found a total of ${CONSTANSTS} constants" )

   enum2str_end()
   message( "" )
endfunction( enum2str_generate )

macro( __enum2str_checkSet )
   if( NOT DEFINED ${ARGV0} )
      message( FATAL_ERROR "enum2str_generate: ${ARGV0} not set" )
   endif( NOT DEFINED ${ARGV0} )
endmacro( __enum2str_checkSet )

function( enum2str_add )
   if( USE_CONSTEXPR )
      file( APPEND "${HPP_FILE}" "   /*!\n    * \\brief Converts the enum ${ARGV0} to a c string\n" )
      file( APPEND "${HPP_FILE}" "    * \\param _var The enum value to convert\n" )
      file( APPEND "${HPP_FILE}" "    * \\returns _var converted to a c string\n    */\n" )
      file( APPEND "${HPP_FILE}" "   static constexpr const char *${FUNC_NAME}( ${ARGV0} _var ) noexcept {\n" )
      file( APPEND "${HPP_FILE}" "      switch ( _var ) {\n" )

      foreach( I IN LISTS ENUMS_TO_USE )
         file( APPEND "${HPP_FILE}" "         case ${ENUM_NS}${I}: return \"${I}\";\n" )
      endforeach( I IN LISTS ENUMS_TO_USE )

      file( APPEND "${HPP_FILE}" "         default: return \"<UNKNOWN>\";\n" )
      file( APPEND "${HPP_FILE}" "      }\n   }\n\n" )
   else( USE_CONSTEXPR )
      file( APPEND "${HPP_FILE}" "   static ${STRING_TYPE}${FUNC_NAME}( ${ARGV0} _var ) noexcept;\n" )

      file( APPEND "${CPP_FILE}" "/*!\n * \\brief Converts the enum ${ARGV0} to a ${STRING_TYPE}\n" )
      file( APPEND "${CPP_FILE}" " * \\param _var The enum value to convert\n" )
      file( APPEND "${CPP_FILE}" " * \\returns _var converted to a ${STRING_TYPE}\n */\n" )
      file( APPEND "${CPP_FILE}" "${STRING_TYPE}${CLASS_NAME}::${FUNC_NAME}( ${ARGV0} _var ) noexcept {\n" )
      file( APPEND "${CPP_FILE}" "   switch ( _var ) {\n" )

      foreach( I IN LISTS ENUMS_TO_USE )
         file( APPEND "${CPP_FILE}" "      case ${ENUM_NS}${I}: return \"${I}\";\n" )
      endforeach( I IN LISTS ENUMS_TO_USE )

      file( APPEND "${CPP_FILE}" "      default: return \"<UNKNOWN>\";\n" )
      file( APPEND "${CPP_FILE}" "   }\n}\n\n" )
   endif( USE_CONSTEXPR )
endfunction( enum2str_add )

function( enum2str_init )
   string( TOUPPER ${CLASS_NAME} CLASS_NAME_UPPERCASE )

   file( WRITE  "${HPP_FILE}" "/*!\n" )
   file( APPEND "${HPP_FILE}" "  * \\file ${CLASS_NAME}.hpp\n" )
   file( APPEND "${HPP_FILE}" "  * \\warning This is an automatically generated file!\n" )
   file( APPEND "${HPP_FILE}" "  */\n\n" )
   file( APPEND "${HPP_FILE}" "#pragma once\n\n" )
   file( APPEND "${HPP_FILE}" "#include <string>\n" )

   foreach( I IN LISTS INCLUDES )
      file( APPEND "${HPP_FILE}" "#include <${I}>\n" )
   endforeach( I IN LISTS INCLUDES )

   file( APPEND "${HPP_FILE}" "\nnamespace ${NAMESPACE} {\n\n" )
   file( APPEND "${HPP_FILE}" "class ${CLASS_NAME} {\n" )
   file( APPEND "${HPP_FILE}" " public:\n" )

   if( NOT USE_CONSTEXPR )
      file( WRITE  "${CPP_FILE}" "/*!\n" )
      file( APPEND "${CPP_FILE}" "  * \\file ${CLASS_NAME}.cpp\n" )
      file( APPEND "${CPP_FILE}" "  * \\warning This is an automatically generated file!\n" )
      file( APPEND "${CPP_FILE}" "  */\n\n" )
      file( APPEND "${CPP_FILE}" "#include \"${CLASS_NAME}.hpp\"\n\n" )
      file( APPEND "${CPP_FILE}" "namespace ${NAMESPACE} {\n\n" )
   endif( NOT USE_CONSTEXPR )
endfunction( enum2str_init )

function( enum2str_end )
   string( TOUPPER ${CLASS_NAME} CLASS_NAME_UPPERCASE )

   file( APPEND "${HPP_FILE}" "};\n\n}\n\n" )
   if( NOT USE_CONSTEXPR )
      file( APPEND "${CPP_FILE}" "\n}\n" )
   endif( NOT USE_CONSTEXPR )

endfunction( enum2str_end )

extension: cmake


text:
LICENSE = "GPL"
DESCRIPTION = "The Useful Sound Daemon"
SECTION = "libs"
PRIORITY = "optional"
DEPENDS = "pth"

SRC_URI = "http://mattcamp.paunix.org/usound/usound-${PV}.tar.gz"
S = "${WORKDIR}/usound"

do_compile() {
	for dir in lib daemon
	do
		cd ${S}/$dir
		oe_runmake
	done
}

do_stage() {
	oe_libinstall -a -C lib libusound ${STAGING_LIBDIR}
	install -m 0644 lib/usound.h ${STAGING_INCDIR}/
}

do_install() {
	install -d ${D}${bindir}
	install -m 0755 daemon/usound ${D}${bindir}
}

SRC_URI[md5sum] = "f863e1c02a8f7b634fd3102274163f8e"
SRC_URI[sha256sum] = "31299e0308d7e1879cba6c54e3c06b1ba8de028d6cf8dc6ff99c0fe9974cefe2"


text:
package db

import (
	"github.com/Masterminds/squirrel"
	"reflect"
)

func FieldEq(record interface{}, fieldName string, fieldValue interface{}) squirrel.Eq {
	fields := reflect.TypeOf(record)
	found := ""
	if field, ok := fields.FieldByName(fieldName); ok {
		found = field.Tag.Get("stbl")
	}
	return squirrel.Eq{found: fieldValue}
}


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

package clockalignedmetrics

import (
	httpUtility "cim/http_utility"
	"cim/logs"
	"cim/types"
	"encoding/json"
	"fmt"

	"io/ioutil"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/expfmt"
)

const (
	closed = "CLOSED"
	open   = "OPEN"
)

type clockAlignedConfig struct {
	ScrapeEnabled string   `json:"scrape"`
	Path          string   `json:"path"`
	Ports         []string `json:"ports"`
	Scheme        string   `json:"scheme"`
	MeasInterval  string   `json:"measurementInterval"`
	MaxRetention  string   `json:"maxRetention"`
}

var (
	mc      *MetricsCollector
	success float64
	once    sync.Once
	//maxRetention = 10 // no of bucket
	config clockAlignedConfig
)

// MetricsCollector implements the prometheus.Collector interface.
type MetricsCollector struct {
	Buckets map[int]*Bucket
}

type Bucket struct {
	BucketID      int
	Status        string
	CaFetchedData []*dto.MetricFamily
	TimeStamp     time.Time
}

type handler struct {
	// exporterMetricsRegistry is a separate registry for the metrics.
	exporterMetricsRegistry *prometheus.Registry
}

func newMetricsCollector() *MetricsCollector {
	maxNumBuckets, _ := strconv.Atoi(config.MaxRetention)
	buckets := make(map[int]*Bucket)
	for i := 1; i <= maxNumBuckets; i++ {
		b := &Bucket{
			BucketID:      i,
			Status:        open,
			CaFetchedData: []*dto.MetricFamily{},
		}
		buckets[i] = b
	}
	return &MetricsCollector{Buckets: buckets}
}

//RunAppMetricCollection start collecting metrics from app
func RunAppMetricCollection() {
	//logs.LogConf.Info("cim started at:", time.Now())
	currentTime := time.Now().Unix()
	logs.LogConf.Info("measurement interval is:", config.MeasInterval)
	measInterval, err := time.ParseDuration(config.MeasInterval)
	if err != nil {
		logs.LogConf.Error("error while getting the interval", err)
		return
	}

	nextScrapeTime := int(measInterval.Seconds()) - int((float64(currentTime)+measInterval.Seconds()))%int(measInterval.Seconds())
	//nextScrapeTime := int(measInterval.Seconds()) - int(currentTime)%int(measInterval.Seconds())

	logs.LogConf.Info("nextscrapetime within:", time.Duration(nextScrapeTime)*time.Second)

	//start ticker
	ticker := time.NewTicker(time.Duration(nextScrapeTime) * time.Second)

	go func() {
		for {
			select {
			case <-ticker.C:
				//scrape metrics from app
				scrapetime := time.Now().Round(5 * time.Second)
				once.Do(func() {
					ticker = time.NewTicker(measInterval)
				})
				//logs.LogConf.Info("scraping time :", scrapetime)
				for bucketID, details := range mc.Buckets {

					if details.Status == open {
						collectMetrics(bucketID, scrapetime)
						break
					}
				}

			}
		}
	}()
}

func collectMetrics(id int, scrapeTime time.Time) {

	var (
		parser expfmt.TextParser
		result []*dto.MetricFamily
	)

	//scrape application metrics
	for _, port := range config.Ports {
		appResp, err := httpUtility.HttpGet(config.Scheme+"://localhost:"+port+config.Path, "application/json", nil)
		if err != nil {
			logs.LogConf.Error("error while getting the metrics from app", err, time.Now())
		}

		if appResp != nil && appResp.Body != nil {
			appBody, err := ioutil.ReadAll(appResp.Body)
			if err != nil {
				logs.LogConf.Error("error while reading the app response body", err)
			}

			appResp.Body.Close()
			appMetrics, err := parser.TextToMetricFamilies(strings.NewReader(string(appBody)))
			if err != nil {
				logs.LogConf.Error("error while parsing app text to metric family", err)
			}

			for _, mf := range appMetrics {
				for _, metric := range mf.Metric {
					var sourcePort = new(dto.LabelPair)
					name := "source_port"
					sport := port
					sourcePort.Name = &name
					sourcePort.Value = &sport
					metric.Label = append(metric.Label, sourcePort)
					result = append(result, mf)
				}
			}

		}
	}

	//scrape cim metrics
	cimResp, err := httpUtility.HttpGet(fmt.Sprintf("http://localhost:%d/metrics", types.CIMRestPort), "application/json", nil)
	if err != nil {
		logs.LogConf.Error("error while getting the metrics from cim", err, time.Now())
	}

	if cimResp != nil && cimResp.Body != nil {

		cimBody, err := ioutil.ReadAll(cimResp.Body)
		if err != nil {
			logs.LogConf.Error("error while reading the cim response body", err)
		}

		cimResp.Body.Close()

		cimMetrics, err := parser.TextToMetricFamilies(strings.NewReader(string(cimBody)))
		if err != nil {
			logs.LogConf.Error("error while parsing cim text to metric family", err)
		}

		for _, mf := range cimMetrics {
			for _, metric := range mf.Metric {
				var sourcePort = new(dto.LabelPair)
				name := "source_port"
				val := strconv.Itoa(types.CIMRestPort)
				sourcePort.Name = &name
				sourcePort.Value = &val
				metric.Label = append(metric.Label, sourcePort)
				result = append(result, mf)
			}
		}
	}

	if result != nil {
		mc.Buckets[id].CaFetchedData = result
		mc.Buckets[id].Status = closed
		mc.Buckets[id].TimeStamp = scrapeTime
	}
}

//IsClockAlignedMetricsEnabled check if clock aligned metrics is enabled
func IsClockAlignedMetricsEnabled() bool {
	mmaasAnnotations := types.PodDetails.Annotations["xgvela.com/mmaas"]
	logs.LogConf.Info("mmaas annotation details are:", mmaasAnnotations)
	if mmaasAnnotations == "" {
		logs.LogConf.Info("clock aligned metrics exposition is disabled")
		return false
	}

	err := json.Unmarshal([]byte(mmaasAnnotations), &config)
	if err != nil {
		logs.LogConf.Error("error while getting mmaas annotations", err)
		return false
	}

	if config.ScrapeEnabled == "true" {
		return true
	}

	return false
}

branch_name: refs/heads/main


text:
add_library(MyTarget INTERFACE IMPORTED)
set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME -flag)
set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME item1 item2)
set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME /path/to/item1)
set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME \\path\\to\\item1)
set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME c:\\path\\to\\item1)


text:
package main

import "github.com/miroslavLalev/migrate/internal/cli"

func main() {
	cli.Main(Version)
}

repository: miroslavLalev/migrate

repo_name: miroslavLalev/migrate


text:
0_2B9JIQAX 0_3DN4DBVK 0_3U27C7NN 0_5I9ID9F8 0_5JRGD84A 0_5SPUFPVS 0_9PQVSCAG 0_CZFMHT6Q 0_EG8PSKWC 0_G89E7UI2 0_J2E4RRGB 0_K83Q6ZTS 0_MCP4GU5X 0_NWQKEH3B 0_PG88NTNT 0_PNKFQANI 0_RIKUGHRX 0_SH6TQCTP 0_T4GM9VZA 0_TZKT263E 0_UJRP75IC 0_W74W8V79 0_WD2I7ZXM 0_WTWTUJ7H 0_XMJAN6B3

@inproceedings{satayamas2004widecoverage,
	title = {{Wide-Coverage} Grammar Extraction from Thai Treebank},
	booktitle = {Proceedings of Papillon 2004 Workshops on Multilingual Lexical Databases},
	author = {Satayamas, V. and Kawtrakul, A.},
	year = {2004}
}
@article{ajdukiewicz1935diesyntaktische,
	title = {Die syntaktische Konnexität},
	volume = {1},
	number = {1},
	journal = {Studia Philosophica},
	author = {Ajdukiewicz, K.},
	year = {1935},
	pages = {27}
}
@article{nivre2005dependency,
	title = {Dependency grammar and dependency parsing},
	volume = {5133},
	journal = {{MSI} report},
	author = {Nivre, J.},
	year = {2005}
}
@inproceedings{ruangrajitpakorn2010acurrent,
	title = {A Current Status of Thai Categorial Grammars and Their Applications},
	booktitle = {Open Conference on 8th Asian language workshop in the 23rd International Conference on Computational Linguistics {(COLING} 2010), Beijing, China},
	author = {Ruangrajitpakorn, T. and Supnithi, T.},
	year = {2010}
}
@phdthesis{collins1999headdriven,
	type = {{PhD} Thesis},
	title = {Head-driven statistical models for natural language parsing},
	school = {University of Pennsylvania},
	author = {Collins, M.},
	year = {1999}
}
@inproceedings{mcdonald2007characterizing,
	title = {Characterizing the errors of data-driven dependency parsing models},
	booktitle = {Proc. of the Joint Conf. on Empirical Methods in Natural Language Processing and Computational Natural Language Learning {(EMNLP-CoNLL)}},
	author = {{McDonald}, R. and Nivre, J.},
	year = {2007},
	keywords = {constructions, unread}
}
@incollection{hudak2001limericks,
	title = {Limericks and rhyme in Thai},
	isbn = {974-347-222-3},
	url = {http://purl.org/sealang/hudak2001limericks.pdf},
	booktitle = {Essays in Tai Linguistics},
	publisher = {Chulalongkorn University Press},
	author = {Hudak, Thomas J},
	editor = {Kalaya Tingsabadh, M. R and Abramson, Arthur S},
	year = {2001},
	note = {495.911},
	keywords = {limericks{\textbar}rhyme},
	pages = {41--50}
}
@techreport{sudprasert2008dependency,
	type = {Technical Report},
	title = {Dependency Annotation Guideline for Thai, version 1.4 (in Thai)},
	url = {http://naist.cpe.ku.ac.th/tred/},
	author = {Sudprasert, S.},
	year = {2008}
}
@inproceedings{ma2008improving,
	title = {Improving word alignment using syntactic dependencies},
	booktitle = {Proceedings of the {ACL-08:} {HLT} Second Workshop on Syntax and Structure in Statistical Translation {(SSST-2)}},
	author = {Ma, Y. and Ozdowska, S. and Sun, Y. and Way, A.},
	year = {2008},
	pages = {69–77}
}
@inproceedings{chang2009discriminative,
	title = {Discriminative Reordering with Chinese Grammatical Relations Features},
	booktitle = {Proceedings of the Third Workshop on Syntax and Structure in Statistical Translation},
	author = {Chang, P. C and Tseng, H. and Jurafsky, D. and Manning, C. D},
	year = {2009},
	pages = {51–59}
}
@techreport{sornlertlamvanich1997orchidthai,
	title = {{ORCHID:} Thai part-of-speech tagged corpus},
	shorttitle = {{ORCHID}},
	number = {{TR-NECTEC-1997-001}},
	author = {Sornlertlamvanich, V. and Charoenporn, T. and Isahara, H.},
	year = {1997},
	pages = {5–19}
}
@article{thepkanjana2009resultative,
	title = {Resultative constructions with “implied-result” and “entailed-result” verbs in Thai and English: a contrastive study},
	volume = {47},
	issn = {0024-3949},
	shorttitle = {Resultative constructions with “implied-result” and “entailed-result” verbs in Thai and English},
	url = {http://www.thefreelibrary.com/-a0204693751},
	number = {3},
	journal = {Linguistics},
	author = {Thepkanjana, K. and Uehara, S.},
	year = {2009},
	pages = {589–618}
}
@inproceedings{wacharamanotham2007thedevelopment,
	address = {Thailand},
	title = {The Development of Web-based Annotation System for Thai Treebank},
	url = {http://naist.cpe.ku.ac.th/tred/},
	author = {Wacharamanotham, C. and Suktarachan, M. and Kawtrakul, A.},
	year = {2007},
	pages = {305}
}
@inproceedings{gimenez2004svmtool,
	title = {{SVMTool:} A general {POS} tagger generator based on Support Vector Machines},
	shorttitle = {{SVMTool}},
	booktitle = {In Proceedings of the 4th International Conference on Language Resources and Evaluation},
	author = {Giménez, J. and Marquez, L.},
	year = {2004}
}
@misc{chang2001libsvma,
	title = {{LIBSVM:} a library for support vector machines},
	url = {http://www.csie.ntu.edu.tw/cjlin/libsvm},
	author = {Chang, C. and Lin, C.},
	year = {2001}
}
@article{kubler2009dependency,
	title = {Dependency Parsing},
	volume = {2},
	number = {1},
	journal = {Synthesis Lectures on Human Language Technologies},
	author = {Kübler, S. and {McDonald}, R. and Nivre, J.},
	editor = {Hirst, G.},
	year = {2009},
	pages = {1--127}
}
@inproceedings{boonkwan2009amemorybased,
	title = {A memory-based approach to the treatment of serial verb construction in combinatory categorial grammar},
	booktitle = {Proceedings of the 12th Conference of the European Chapter of the Association for Computational Linguistics: Student Research Workshop},
	author = {Boonkwan, P.},
	year = {2009},
	pages = {10–18}
}
@inproceedings{buchholz2006conllxshared,
	title = {{CoNLL-X} shared task on Multilingual Dependency Parsing},
	booktitle = {Tenth Conference on Computational Natural Language Learning},
	author = {Buchholz, S. and Marsi, E.},
	year = {2006},
	pages = {149}
}
@article{matsui2007classification,
	title = {Classification of Thai Resultatives: Serial Verb and Other Similar Constructions},
	volume = {4},
	shorttitle = {Classification of Thai Resultatives},
	journal = {Jimbun ronkyu {[Humanities} Review] 56},
	author = {Matsui, N.},
	year = {2007}
}
@inproceedings{ruangrajitpakorn2009asyntactic,
	title = {A syntactic resource for Thai: {CG} treebank},
	shorttitle = {A syntactic resource for Thai},
	booktitle = {Proceedings of the 7th Workshop on Asian Language Resources},
	author = {Ruangrajitpakorn, T. and Trakultaweekoon, K. and Supnithi, T.},
	year = {2009},
	pages = {96–101}
}
@inproceedings{boonkwan2011grammar,
	address = {Chiang Mai},
	title = {Grammar Induction from Text Using Small Syntactic Prototypes},
	booktitle = {Proceedings of the 5th International Joint Conference on Natural Language Processing (to appear)},
	author = {Boonkwan, P. and Steedman, M.},
	year = {2011}
}
@inproceedings{chanev2006dependency,
	title = {Dependency conversion and parsing of the {BulTreeBank}},
	booktitle = {Proc. of the {LREC-Workshop} Merging and Layering Linguistic Information},
	author = {Chanev, A. and Simov, K. and Osenova, P. and Marinov, S.},
	year = {2006}
}
@book{steedman2000thesyntactic,
	title = {The syntactic process},
	volume = {131},
	publisher = {{MIT} Press},
	author = {Steedman, M.},
	year = {2000}
}
@article{warotamasikkhadit1997fronting,
	title = {Fronting and backing topicalization in Thai},
	volume = {27},
	journal = {{Mon-Khmer} Studies},
	author = {Warotamasikkhadit, U.},
	year = {1997},
	pages = {303–6}
}
@inproceedings{daum2004automatic,
	title = {Automatic transformation of phrase treebanks to dependency trees},
	booktitle = {Proceedings of {LREC}},
	author = {Daum, M. and Foth, K. and Menzel, W.},
	year = {2004}
}

license: Zlib

repository: wannaphong/thcg

repo_name: wannaphong/thcg


text:
DESCRIPTION = "Lightweight web browser capable of handling many of the \
web standards in use today."
HOMEPAGE = "http://www.netsurf-browser.org/"
SECTION = "x11/network"
LICENSE = "GPLv2"

SRC_URI = "http://www.netsurf-browser.org/downloads/releases/netsurf-${PV}-src.tar.gz \
	   file://fix_makefile.patch \
	   file://debugxml_fix.patch \
	   file://netsurf.png \
	   file://netsurf.desktop \
	   file://Makefile.config"

PR = "r1"

# Workaround for 2.6 tarball (unpacks into netsurf/, not netsurf-2.6/ )
S = "${WORKDIR}/netsurf"

DEPENDS = "gtk+ lemon-native re2c-native jpeg openssl curl libxml2 \
	   libglade hubbub libcss libnsgif libnsbmp lcms"

EXTRA_OEMAKE = "CURDIR=${S} DESTDIR=${D} PREFIX=${prefix}"

do_configure() {
	cp ${WORKDIR}/Makefile.config ${S}/
}

do_install() {
	oe_runmake install
	install -d ${D}/${datadir}/applications
	install -d ${D}/${datadir}/pixmaps
	install -m 0644 ${WORKDIR}/netsurf.png ${D}/${datadir}/pixmaps/
	install -m 0644 ${WORKDIR}/netsurf.desktop ${D}/${datadir}/applications/
}

SRC_URI[md5sum] = "8653789d2ede6dbbfe79882afc7538fc"
SRC_URI[sha256sum] = "366ad15e1879776b54882fd6f3fa4e421a049644c029e4c14fc163b76c6fc190"


text:
// Code generated by ros-gen-go.
// source: WrenchStamped.msg
// DO NOT EDIT!
package geometry_msgs

import (
	"io"

	"github.com/cnord/rosgo/msgs/std_msgs"
	"github.com/cnord/rosgo/ros"
)

type _MsgWrenchStamped struct {
	text   string
	name   string
	md5sum string
}

func (t *_MsgWrenchStamped) Text() string {
	return t.text
}

func (t *_MsgWrenchStamped) Name() string {
	return t.name
}

func (t *_MsgWrenchStamped) MD5Sum() string {
	return t.md5sum
}

func (t *_MsgWrenchStamped) NewMessage() ros.Message {
	m := new(WrenchStamped)

	return m
}

var (
	MsgWrenchStamped = &_MsgWrenchStamped{
		`# A wrench with reference coordinate frame and timestamp
Header header
Wrench wrench
`,
		"geometry_msgs/WrenchStamped",
		"d78d3cb249ce23087ade7e7d0c40cfa7",
	}
)

type WrenchStamped struct {
	Header std_msgs.Header
	Wrench Wrench
}

func (m *WrenchStamped) Serialize(w io.Writer) (err error) {
	if err = ros.SerializeMessageField(w, "Header", &m.Header); err != nil {
		return err
	}

	if err = ros.SerializeMessageField(w, "Wrench", &m.Wrench); err != nil {
		return err
	}

	return
}

func (m *WrenchStamped) Deserialize(r io.Reader) (err error) {
	// Header
	if err = ros.DeserializeMessageField(r, "Header", &m.Header); err != nil {
		return err
	}

	// Wrench
	if err = ros.DeserializeMessageField(r, "Wrench", &m.Wrench); err != nil {
		return err
	}

	return
}

repository: cnord/rosgo

repo_name: cnord/rosgo

gha_language: Go


text:
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/yyoshiki41/go-siwa"
)

func main() {
	client := siwa.NewClient()
	keys, err := client.Keys(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	for _, k := range keys {
		fmt.Printf("%#v\n", k)
	}
}

repository: isgasho/go-siwa

repo_name: isgasho/go-siwa


text:
package keeper

import (
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/Dipper-Labs/Dipper-Protocol/app/v0/mint/internal/types"
	sdk "github.com/Dipper-Labs/Dipper-Protocol/types"
	abci "github.com/tendermint/tendermint/abci/types"
)

func TestNewQuerier(t *testing.T) {
	input := newTestInput(t)
	querier := NewQuerier(input.mintKeeper)

	query := abci.RequestQuery{
		Path: "",
		Data: []byte{},
	}

	_, err := querier(input.ctx, []string{types.QueryParameters}, query)
	require.NoError(t, err)

	_, err = querier(input.ctx, []string{types.QueryInflation}, query)
	require.NoError(t, err)

	_, err = querier(input.ctx, []string{types.QueryAnnualProvisions}, query)
	require.NoError(t, err)

	_, err = querier(input.ctx, []string{"foo"}, query)
	require.Error(t, err)
}

func TestQueryParams(t *testing.T) {
	input := newTestInput(t)

	var params types.Params

	res, sdkErr := queryParams(input.ctx, input.mintKeeper)
	require.NoError(t, sdkErr)

	err := input.cdc.UnmarshalJSON(res, &params)
	require.NoError(t, err)

	require.Equal(t, input.mintKeeper.GetParams(input.ctx), params)
}

func TestQueryInflation(t *testing.T) {
	input := newTestInput(t)

	var inflation sdk.Dec

	res, sdkErr := queryInflation(input.ctx, input.mintKeeper)
	require.NoError(t, sdkErr)

	err := input.cdc.UnmarshalJSON(res, &inflation)
	require.NoError(t, err)

	require.Equal(t, input.mintKeeper.GetMinter(input.ctx).Inflation, inflation)
}

func TestQueryAnnualProvisions(t *testing.T) {
	input := newTestInput(t)

	var annualProvisions sdk.Dec

	res, sdkErr := queryAnnualProvisions(input.ctx, input.mintKeeper)
	require.NoError(t, sdkErr)

	err := input.cdc.UnmarshalJSON(res, &annualProvisions)
	require.NoError(t, err)

	require.Equal(t, input.mintKeeper.GetMinter(input.ctx).AnnualProvisions, annualProvisions)
}

repository: Dipper-Labs/Dipper-Protocol

repo_name: Dipper-Labs/Dipper-Protocol


text:
require ${PN}.inc

SRC_URI = "http://sources.openembedded.org/opie-1.2.5-split_core_${APPNAME}.tar.bz2;name=split_core_appname \
	   http://sources.openembedded.org/opie-1.2.5-split_core_apps_calibrate.tar.bz2;name=split_core_apps_calibrate \
	   http://sources.openembedded.org/opie-1.2.5-split_core_launcher.tar.bz2;name=split_core_launcher \
	   file://opie-session \
	   file://post-session \
	   file://pre-session \
	   file://opie-login.conf"
SRC_URI[split_core_appname.md5sum] = "88d0bdbc49a59529ce43880f6df82212"
SRC_URI[split_core_appname.sha256sum] = "263a3734c3f9aadacb9d84ff1ae38b717f1eadd66c59c227769a7e26309fb85d"
SRC_URI[split_core_apps_calibrate.md5sum] = "ee5e06b781e92f01271d883f91f101b0"
SRC_URI[split_core_apps_calibrate.sha256sum] = "5e0164a195a166fd15451164edf8a44d8f3a9f81dcf3edc3a8975f24bd4b45b6"
SRC_URI[split_core_launcher.md5sum] = "cd3708a2d074f108d81ffea590995725"
SRC_URI[split_core_launcher.sha256sum] = "fca1501398f1e4d0690455b145b17a68287de422592bca73c2afdf6762d021ce"


text:
DESCRIPTION = "GStreamer elements to use the Video Processing Engine (VPE) found on some TI devices"

LICENSE = "LGPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=fbc093901857fcd118f065f900982c24"

require gst-plugins-ti.inc

PR = "${INC_PR}.1"
SRCREV = "b14e905feee2470952184f570f97deeb8e88b619"

SRC_URI = "git://git.ti.com/glsdk/gst-plugin-vpe.git;protocol=git"

repository: varigit/meta-arago-var

repo_name: varigit/meta-arago-var


text:
@article{henschke_rethinking_2016,
 author = {Henschke, Natasha and Everett, Jason D. and Richardson, Anthony J. and Suthers, Iain M.},
 doi = {10.1016/j.tree.2016.06.007},
 file = {Henschke et al. - 2016 - Rethinking the Role of Salps in the Ocean.pdf:/Users/ric325/Zotero/storage/NLCJ5D9Z/Henschke et al. - 2016 - Rethinking the Role of Salps in the Ocean.pdf:application/pdf;Henschke_etal_2016_TREE_Salps_Supplement.pdf:/Users/ric325/Zotero/storage/TVTNZTTE/Henschke_etal_2016_TREE_Salps_Supplement.pdf:application/pdf},
 issn = {01695347},
 journal = {Trends in Ecology & Evolution},
 language = {en},
 month = {September},
 number = {9},
 pages = {720--733},
 title = {Rethinking the Role of Salps in the Ocean},
 url = {https://linkinghub.elsevier.com/retrieve/pii/S0169534716300763},
 urldate = {2019-10-24},
 volume = {31},
 year = {2016}
}


text:
package autgofig

import (
	"github.com/devthane/autgofig/pkg/autgofig"
	"testing"
	"os"
	"runtime"
	"fmt"
)

type TestObj struct {
	StringField string
	IntField    int
}

func TestIntegrationYaml(t *testing.T) {
	var (
		Separator    string
		HomeDir      string
		ConfLocation string
	)

	name := "config-yaml-test"

	if runtime.GOOS == "windows" {
		Separator = "\\"
		HomeDir = os.Getenv("userprofile")
	} else {
		Separator = "/"
		HomeDir = os.Getenv("HOME")
	}

	ConfLocation = HomeDir + Separator + "." + name + ".yml"

	file, err := os.Create(ConfLocation)
	if err != nil {
		t.Fatal(err)
	}

	file.Write([]byte(
		fmt.Sprintf("StringField: YamlTest\nIntField: \"5\"\n"),
	))
	file.Close()
	defer os.Remove(ConfLocation)

	config := new(TestObj)
	autgofig.LoadConfig(config, name)

	if config.StringField != "YamlTest" || config.IntField != 5 {
		t.Fail()
	}
}

func TestIntegrationEnv(t *testing.T) {
	os.Setenv("StringField", "EnvTest")
	os.Setenv("IntField", "10")
	defer os.Clearenv()

	config := new(TestObj)
	autgofig.LoadConfig(config, "config-env-test")

	if config.StringField != "EnvTest" || config.IntField != 10 {
		t.Fail()
	}
}

func TestIntegrationPriority(t *testing.T) {
	var (
		Separator    string
		HomeDir      string
		ConfLocation string
	)

	os.Setenv("StringField", "PriorityTest")
	defer os.Clearenv()

	name := "config-priority-test"

	if runtime.GOOS == "windows" {
		Separator = "\\"
		HomeDir = os.Getenv("userprofile")
	} else {
		Separator = "/"
		HomeDir = os.Getenv("HOME")
	}

	ConfLocation = HomeDir + Separator + "." + name + ".yml"

	file, err := os.Create(ConfLocation)
	if err != nil {
		t.Fatal(err)
	}

	file.Write([]byte(
		fmt.Sprintf("StringField: YamlTest\nIntField: \"5\"\n"),
	))
	file.Close()
	defer os.Remove(ConfLocation)

	config := new(TestObj)
	autgofig.LoadConfig(config, name)

	if config.StringField != "PriorityTest" || config.IntField != 5 {
		t.Fail()
	}
}

repository: devthane/autgofig

repo_name: devthane/autgofig

gha_license_id: MIT


text:
@Article{caron:ral:2021,
  author    = {Caron, Guillaume},
  title     = {Defocus-based Direct Visual Servoing},
  journal   = {IEEE Robotics and Automation Letters},
  year      = {2021},
  volume    = {6},
  number    = {2},
  pages     = {4057--4064},
  month     = {April},
  doi       = {10.1109/LRA.2021.3067845},
  url       = {https://hal.archives-ouvertes.fr/hal-03155667/document},
  keywords  = {Cameras, Convergence, Brightness, Kernel, Transforms, Apertures, Visual Servoing, Sensor-based Control},
  abstract  = {Direct Visual Servoing (DVS) considers pixel brightness directly as input of robot control. Recent DVS variants consider image processing as smoothing or frequency domain transforms, resulting in large convergence domains. This paper proposes to consider defocus to optically smooth images without processing. The resulting Defocus-based DVS shows convergence domains competing with the state-of-the-art, larger in some challenging cases, for lower complexity.},
  publisher = {IEEE-INST Electrical Electronics Engineers Inc},
  address   = {445 Hoes Lane, Piscataway, NJ 08855-4141, USA}
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/quickstep_queryoptimizer_rules_PruneColumns.dir/PruneColumns.cpp.o"
  "libquickstep_queryoptimizer_rules_PruneColumns.pdb"
  "libquickstep_queryoptimizer_rules_PruneColumns.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/quickstep_queryoptimizer_rules_PruneColumns.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

repository: kpgaffney/quickstep-optimizer-rs

repo_name: kpgaffney/quickstep-optimizer-rs


text:
package gettext

import (
	"fmt"
	"io/fs"
	"io/ioutil"
	"runtime"
)

type fileMapping struct {
	data []byte

	isMapped bool
}

func (m *fileMapping) Close() error {
	runtime.SetFinalizer(m, nil)
	if !m.isMapped {
		return nil
	}
	return m.closeMapping()
}

func openMapping(f fs.File) (*fileMapping, error) {
	fi, err := f.Stat()
	if err != nil {
		return nil, err
	}

	m := new(fileMapping)

	if fi.Mode().IsRegular() {
		size := fi.Size()
		if size == 0 {
			return m, nil
		}
		if size < 0 {
			return nil, fmt.Errorf("file %q has negative size", fi.Name())
		}
		if size != int64(int(size)) {
			return nil, fmt.Errorf("file %q is too large", fi.Name())
		}

		if err := m.tryMap(f, size); err == nil {
			runtime.SetFinalizer(m, (*fileMapping).Close)
			return m, nil
		}
	}

	// On mapping failure, fall back to reading the file into
	// memory directly.
	m.data, err = ioutil.ReadAll(f)
	return m, err
}

repository: snapcore/go-gettext

repo_name: snapcore/go-gettext


text:
package main

import (
	"go-micro.dev/cmd/gomu/cmd"

	// register commands
	_ "go-micro.dev/cmd/gomu/cmd/cli"
)

func main() {
	cmd.Run()
}

repository: suryatmodulus/go-micro

repo_name: suryatmodulus/go-micro


text:
package brands

// Thing is the base entity, all Public APIs should have these properties
type Thing struct {
	ID           string   `json:"id,omitempty"`
	APIURL       string   `json:"apiUrl,omitempty"`
	Types        []string `json:"types,omitempty"`
	DirectType   string   `json:"directType,omitempty"`
	PrefLabel    string   `json:"prefLabel,omitempty"`
	IsDeprecated bool     `json:"isDeprecated,omitempty"`
}

// Brand represent a brand owned by an organisation, current only used is relation to FT brands
type Brand struct {
	Thing
	DescriptionXML string  `json:"descriptionXML,omitempty"`
	Strapline      string  `json:"strapline,omitempty"`
	ImageURL       string  `json:"_imageUrl,omitempty"` // NB Temp hack
	Parent         *Thing  `json:"parentBrand,omitempty"`
	Children       []Thing `json:"childBrands,omitempty"`
}

// NeoBrand is the same as Brand, but it receives an extra field and multiple parents.
type NeoBrand struct {
	NeoThing
	DescriptionXML string     `json:"descriptionXML,omitempty"`
	Strapline      string     `json:"strapline,omitempty"`
	ImageURL       string     `json:"imageUrl,omitempty"` // NB Temp hack
	Parent         NeoThing   `json:"parent,omitempty"`
	Children       []NeoThing `json:"children,omitempty"`
	Authority      string     `json:"authority,omitempty"`
}

type NeoThing struct {
	ID           string   `json:"id,omitempty"`
	Types        []string `json:"types,omitempty"`
	PrefLabel    string   `json:"prefLabel,omitempty"`
	IsDeprecated bool     `json:"isDeprecated,omitempty"`
}

type ConceptApiResponse struct {
	Concept
	ImageURL       string           `json:"imageUrl,omitempty"`
	DescriptionXML string           `json:"descriptionXML,omitempty"`
	Strapline      string           `json:"strapline,omitempty"`
	Broader        []RelatedConcept `json:"broaderConcepts,omitempty"`
	Narrower       []RelatedConcept `json:"narrowerConcepts,omitempty"`
}

type RelatedConcept struct {
	Concept Concept `json:concept,omitempty`
}

type Concept struct {
	ID           string `json:"id,omitempty"`
	ApiURL       string `json:"apiUrl,omitempty"`
	PrefLabel    string `json:"prefLabel,omitempty"`
	Type         string `json:"type,omitempty"`
	IsDeprecated bool   `json:"isDeprecated,omitempty"`
}

repository: Financial-Times/public-brands-api

repo_name: Financial-Times/public-brands-api


text:
@inproceedings{alt_knowledge-driven_2023,
	address = {Rhodes, Greece},
	title = {Knowledge-{Driven} {Robot} {Program} {Synthesis} from {Human} {VR} {Demonstrations}},
	copyright = {All rights reserved},
	url = {http://arxiv.org/abs/2306.02739},
	doi = {10.48550/arXiv.2306.02739},
	abstract = {Aging societies, labor shortages and increasing wage costs call for assistance robots capable of autonomously performing a wide array of real-world tasks. Such open-ended robotic manipulation requires not only powerful knowledge representations and reasoning (KR\&R) algorithms, but also methods for humans to instruct robots what tasks to perform and how to perform them. In this paper, we present a system for automatically generating executable robot control programs from human task demonstrations in virtual reality (VR). We leverage common-sense knowledge and game engine-based physics to semantically interpret human VR demonstrations, as well as an expressive and general task representation and automatic path planning and code generation, embedded into a state-of-the-art cognitive architecture. We demonstrate our approach in the context of force-sensitive fetch-and-place for a robotic shopping assistant. The source code is available at https://github.com/ease-crc/vr-program-synthesis.},
	urldate = {2023-06-06},
	publisher = {arXiv},
	author = {Alt, Benjamin and Kenfack, Franklin Kenghagho and Haidu, Andrei and Katic, Darko and Jäkel, Rainer and Beetz, Michael},
	month = sep,
	year = {2023},
	note = {arXiv:2306.02739 [cs]},
	keywords = {68T30, Computer Science - Artificial Intelligence, Computer Science - Robotics, D.1, F.3, I.2},
	file = {Alt et al_2023_Knowledge-Driven Robot Program Synthesis from Human VR Demonstrations.pdf:C\:\\Users\\alt\\Google Drive\\zotero\\Alt et al_2023_Knowledge-Driven Robot Program Synthesis from Human VR Demonstrations.pdf:application/pdf;arXiv.org Snapshot:C\:\\Users\\alt\\Zotero\\storage\\9PHHGSAD\\2306.html:text/html},
  arxiv={2306.02739},
  pdf={knowledge_KR23.pdf}
}


text:
package i18n

import (
	"github.com/volatile/core"
	"golang.org/x/text/language"
)

// Matcher is a matching function used by the handler.
type Matcher func(*core.Context) (language.Tag, language.Confidence)

// Match matches the first of the given tags to reach a certain confidence threshold with an available locale.
// The tags should therefore be specified in order of preference.
// Extensions are ignored for matching.
func Match(tt ...language.Tag) (t language.Tag, c language.Confidence) {
	t, _, c = matcher.Match(tt...)
	return
}

// MatchString parses string s and matches the first of the given tags to reach a certain confidence threshold with an available locale.
// The string can be a single language tag or a list of language tags with preference values (from the Accept-Language header, for example).
func MatchString(s string) (language.Tag, language.Confidence) {
	pref, _, _ := language.ParseAcceptLanguage(s)
	return Match(pref...)
}

// MatcherAcceptLanguageHeader matches the Accept-Language header.
func MatcherAcceptLanguageHeader(c *core.Context) (language.Tag, language.Confidence) {
	return MatchString(c.Request.Header.Get("Accept-Language"))
}

// MatcherFormValue matches the "locale" form value.
func MatcherFormValue(c *core.Context) (language.Tag, language.Confidence) {
	return MatchString(c.Request.FormValue("locale"))
}

// TODO: Matchers for location, GeoIP, subdomain, TLD, request path.


text:
@Misc{phrack-49:14,
  author =    {Aleph One},
  title =     {{Smashing the Stack for Fun and Profit}},
  howpublished = {Phrack 49:14},
  note =      {\url{http://phrack.org/issues.html?issue=49&id=14}}}

@Misc{phrack-58:4,
  author =    {Nergal },
  title =     {{Advanced return-into-lib(c) Exploits: the PaX Case Study}},
  howpublished = {Phrack 58:4},
  note =      {\url{http://phrack.org/issues.html?issue=58&id=4}}}

@Misc{phrack-57:8,
  author =    {MaXX},
  title =     {{Vudo malloc Tricks}},
  howpublished = {Phrack 57:8},
  note =      {\url{http://phrack.org/issues.html?issue=57&id=8}}}

@Misc{phrack-57:9,
  author =    {anonymous author},
  title =     {{Once upon a free()}},
  howpublished = {Phrack 57:9},
  note =      {\url{http://phrack.org/issues.html?issue=57&id=9}}}

@Misc{phrack-61:6,
  author =    {jp},
  title =     {{Advanced Doug Lea's malloc Exploits}},
  howpublished = {Phrack 61:6},
  note =      {\url{http://phrack.org/issues.html?issue=61&id=6}}}

@Misc{phrack-59:7,
  author =    {riq and gera },
  title =     {{Advances in Format String Exploitation}},
  howpublished = {Phrack 59:7},
  note =      {\url{http://phrack.org/issues.html?issue=59&id=7}}}

@Misc{phrack-56:9,
  author =    {klog},
  title =     {{Backdooring Binary Objects}},
  howpublished = {Phrack 56:9},
  note =      {\url{http://phrack.org/issues.html?issue=56&id=9}}}

@Misc{phrack-56:7,
  author =    {Silvio Cesare},
  title =     {{Shared Library Call Redirection via ELF PLT Infection}},
  howpublished = {Phrack 56:7},
  note =      {\url{http://phrack.org/issues.html?issue=56&id=7}}}

@Misc{grugq:cheating-the-elf,
  author =    {the grugq},
  title =     {{Cheating the ELF: Subversive Dynamic Linking to Libraries }}}

@Misc{oneill:modern-elf-injection,
  author =    {Ryan O'Neill},
  title =     {{Modern Day ELF Runtime Infection via GOT Poisoning}},
  month =     {May},
  year =      2009,
  note =      {\url{http://vx.netlux.org/lib/vrn00.html}}}

@Misc{bugtraq-2000/May/90,
  author =    {Tim Newsham},
  title =     {{non-exec stack}},
  howpublished = {Bugtraq},
  month =     {May},
  year =      2000,
  note =      {\url{http://seclists.org/bugtraq/2000/May/90} (pointed out by Dino Dai Zovi)}
}

@Misc{bugtraq-2000/Nov/32,
  author =    {Gerardo Richarte},
  title =     {{Re: Future of Buffer Overflows}},
  howpublished = {Bugtraq},
  month =     {October},
  year =      2000,
  note =      {\url{http://seclists.org/bugtraq/2000/Nov/32}}}

Ofir Arkin

@TechReport{arkin:icmp-usage-scanning,
  author = 	 {Ofir Arkin},
  title = 	 {{ICMP Usage in Scanning, The Complete Know-how}},
  institution =  {The Sys-Security Group},
  year = 	 2001,
  note = 	 {version 3.0}}

repository: pictyeye/nail

repo_name: pictyeye/nail


text:
/**
 *
 * Author:  Juarez Paulino(coderemite)
 * Email: juarez.paulino@gmail.com
 *
 */
#include <bits/stdc++.h>
using namespace std;
int main() {
  int n; cin >> n;
  string a; cin >> a;
  sort(begin(a), end(a));
  a.resize(unique(begin(a), end(a)) - begin(a));
  cout << (n > 26 ? -1 : n-(int)a.size());
}

repository: juarezpaulino/coderemite

repo_name: juarezpaulino/coderemite

extension: cpp


text:
package handlers

import (
	"bufio"
	"bytes"
	"log"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

func TestCleanHost(t *testing.T) {
	tests := []struct {
		in, want string
	}{
		{"www.google.com", "www.google.com"},
		{"www.google.com foo", "www.google.com"},
		{"www.google.com/foo", "www.google.com"},
		{" first character is a space", ""},
	}
	for _, tt := range tests {
		got := cleanHost(tt.in)
		if tt.want != got {
			t.Errorf("cleanHost(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}

func TestCanonicalHost(t *testing.T) {
	gorilla := "http://www.gorillatoolkit.org"

	rr := httptest.NewRecorder()
	r := newRequest(http.MethodGet, "http://www.example.com/")

	testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})

	// Test a re-direct: should return a 302 Found.
	CanonicalHost(gorilla, http.StatusFound)(testHandler).ServeHTTP(rr, r)

	if rr.Code != http.StatusFound {
		t.Fatalf("bad status: got %v want %v", rr.Code, http.StatusFound)
	}

	if rr.Header().Get("Location") != gorilla+r.URL.Path {
		t.Fatalf("bad re-direct: got %q want %q", rr.Header().Get("Location"), gorilla+r.URL.Path)
	}
}

func TestKeepsQueryString(t *testing.T) {
	google := "https://www.google.com"

	rr := httptest.NewRecorder()
	querystring := url.Values{"q": {"golang"}, "format": {"json"}}.Encode()
	r := newRequest(http.MethodGet, "http://www.example.com/search?"+querystring)

	testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
	CanonicalHost(google, http.StatusFound)(testHandler).ServeHTTP(rr, r)

	want := google + r.URL.Path + "?" + querystring
	if rr.Header().Get("Location") != want {
		t.Fatalf("bad re-direct: got %q want %q", rr.Header().Get("Location"), want)
	}
}

func TestBadDomain(t *testing.T) {
	rr := httptest.NewRecorder()
	r := newRequest(http.MethodGet, "http://www.example.com/")

	testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})

	// Test a bad domain - should return 200 OK.
	CanonicalHost("%", http.StatusFound)(testHandler).ServeHTTP(rr, r)

	if rr.Code != http.StatusOK {
		t.Fatalf("bad status: got %v want %v", rr.Code, http.StatusOK)
	}
}

func TestEmptyHost(t *testing.T) {
	rr := httptest.NewRecorder()
	r := newRequest(http.MethodGet, "http://www.example.com/")

	testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})

	// Test a domain that returns an empty url.Host from url.Parse.
	CanonicalHost("hello.com", http.StatusFound)(testHandler).ServeHTTP(rr, r)

	if rr.Code != http.StatusOK {
		t.Fatalf("bad status: got %v want %v", rr.Code, http.StatusOK)
	}
}

func TestHeaderWrites(t *testing.T) {
	gorilla := "http://www.gorillatoolkit.org"

	testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	// Catch the log output to ensure we don't write multiple headers.
	var b bytes.Buffer
	buf := bufio.NewWriter(&b)
	tl := log.New(buf, "test: ", log.Lshortfile)

	srv := httptest.NewServer(
		CanonicalHost(gorilla, http.StatusFound)(testHandler))
	defer srv.Close()
	srv.Config.ErrorLog = tl

	_, err := http.Get(srv.URL)
	if err != nil {
		t.Fatal(err)
	}

	err = buf.Flush()
	if err != nil {
		t.Fatal(err)
	}

	// We rely on the error not changing: net/http does not export it.
	if strings.Contains(b.String(), "multiple response.WriteHeader calls") {
		t.Fatalf("re-direct did not return early: multiple header writes")
	}
}

repository: gorilla/handlers

repo_name: gorilla/handlers


text:
CMAKE_MINIMUM_REQUIRED( VERSION 3.0 )

if(HUMMINGBIRD_DOWNLOADS_SILENT)
    SET(HUMMINGBIRD_GIT_PROGRESS FALSE)
    SET(HUMMINGBIRD_DOWNLOAD_NO_PROGRESS 1)
    SET(HUMMINGBIRD_FILE_DOWNLOAD_SHOW_PROGRESS FALSE)
else()
    SET(HUMMINGBIRD_GIT_PROGRESS TRUE)
    SET(HUMMINGBIRD_DOWNLOAD_NO_PROGRESS 0)
    SET(HUMMINGBIRD_FILE_DOWNLOAD_SHOW_PROGRESS TRUE)
endif()

MESSAGE("HUMMINGBIRD_DOWNLOADS_SILENT: " ${HUMMINGBIRD_DOWNLOADS_SILENT})
MESSAGE("HUMMINGBIRD_GIT_PROGRESS: " ${HUMMINGBIRD_GIT_PROGRESS})
MESSAGE("HUMMINGBIRD_DOWNLOAD_NO_PROGRESS: " ${HUMMINGBIRD_DOWNLOAD_NO_PROGRESS})
MESSAGE("HUMMINGBIRD_FILE_DOWNLOAD_SHOW_PROGRESS: " ${HUMMINGBIRD_FILE_DOWNLOAD_SHOW_PROGRESS})

include(ExternalProject)

find_package(Git REQUIRED)

macro(HUMMINGBIRD_DOWNLOAD_FILE NAME URL FILE)
    if(NOT EXISTS ${HUMMINGBIRD_DEPENDENCIES_SOURCE_DIRECTORY}/${NAME}/${FILE})
        if(HUMMINGBIRD_FILE_DOWNLOAD_SHOW_PROGRESS)
            file(DOWNLOAD ${URL} ${HUMMINGBIRD_DEPENDENCIES_SOURCE_DIRECTORY}/${NAME}/${FILE} SHOW_PROGRESS)
        else()
            file(DOWNLOAD ${URL} ${HUMMINGBIRD_DEPENDENCIES_SOURCE_DIRECTORY}/${NAME}/${FILE})
        endif()
    endif()
endmacro()

macro(HUMMINGBIRD_DOWNLOAD_URL NAME URL)
    ExternalProject_Add(${NAME}_download PREFIX ${NAME}
        SOURCE_DIR ${HUMMINGBIRD_DEPENDENCIES_SOURCE_DIRECTORY}/${NAME}

        URL ${URL}
        DOWNLOAD_NO_PROGRESS ${HUMMINGBIRD_DOWNLOAD_NO_PROGRESS}

        CONFIGURE_COMMAND ""
        BUILD_COMMAND ""
        UPDATE_COMMAND ""
        INSTALL_COMMAND ""
    )

    add_library(${NAME} STATIC IMPORTED)
endmacro()

macro(HUMMINGBIRD_DOWNLOAD_URL_HASH NAME URL HASH_ALGO HASH)
    ExternalProject_Add(${NAME}_download PREFIX ${NAME}
        SOURCE_DIR ${HUMMINGBIRD_DEPENDENCIES_SOURCE_DIRECTORY}/${NAME}

        URL ${URL}
        URL_HASH ${HASH_ALGO}=${HASH}
        DOWNLOAD_NO_PROGRESS ${HUMMINGBIRD_DOWNLOAD_NO_PROGRESS}

        CONFIGURE_COMMAND ""
        BUILD_COMMAND ""
        UPDATE_COMMAND ""
        INSTALL_COMMAND ""
    )

    add_library(${NAME} STATIC IMPORTED)
endmacro()

macro(HUMMINGBIRD_GIT_CLONE NAME REPOSITORY)
    set(TAG ${ARGN})

    list(LENGTH TAG EXIST_TAG)

    if(${EXIST_TAG} GREATER 0)
        ExternalProject_Add( "${NAME}_${TAG}_download" PREFIX ${NAME}
            SOURCE_DIR ${HUMMINGBIRD_DEPENDENCIES_SOURCE_DIRECTORY}/${NAME}

            GIT_REPOSITORY ${REPOSITORY}
            GIT_TAG ${TAG}
            GIT_PROGRESS ${HUMMINGBIRD_GIT_PROGRESS}

            CONFIGURE_COMMAND ""
            BUILD_COMMAND ""
            UPDATE_COMMAND ""
            INSTALL_COMMAND ""
        )
    else()
        ExternalProject_Add(${NAME}_download PREFIX ${NAME}
            SOURCE_DIR ${HUMMINGBIRD_DEPENDENCIES_SOURCE_DIRECTORY}/${NAME}

            GIT_REPOSITORY ${REPOSITORY}
            GIT_PROGRESS ${HUMMINGBIRD_GIT_PROGRESS}

            CONFIGURE_COMMAND ""
            BUILD_COMMAND ""
            UPDATE_COMMAND ${GIT_EXECUTABLE} pull
            INSTALL_COMMAND ""
            )
    endif()

    add_library(${NAME} STATIC IMPORTED)
endmacro()

repository: irov/hummingbird

repo_name: irov/hummingbird


text:
// Package bolt provides an bolt-backed store implementation.
//
// The data stored in bolt is structured as follows:
//
//    bucket(/tasks/v1/tasks) key(:task_id) -> Content of submitted task (i.e. flux code).
//    bucket(/tasks/v1/task_meta) key(:task_id) -> Protocol Buffer encoded backend.StoreTaskMeta,
//                                    so we have a consistent view of runs in progress and max concurrency.
//    bucket(/tasks/v1/org_by_task_id) key(task_id) -> The organization ID (stored as encoded string) associated with given task.
//    bucket(/tasks/v1/name_by_task_id) key(:task_id) -> The user-supplied name of the script.
//    bucket(/tasks/v1/run_ids) -> Counter for run IDs
//    bucket(/tasks/v1/orgs).bucket(:org_id) key(:task_id) -> Empty content; presence of :task_id allows for lookup from org to tasks.
// Note that task IDs are stored big-endian uint64s for sorting purposes,
// but presented to the users with leading 0-bytes stripped.
// Like other components of the system, IDs presented to users may be `0f12` rather than `f12`.
package bolt

import (
	"context"
	"errors"
	"fmt"
	"math"
	"time"

	bolt "github.com/coreos/bbolt"
	platform "github.com/influxdata/influxdb"
	"github.com/influxdata/influxdb/snowflake"
	"github.com/influxdata/influxdb/task/backend"
	"github.com/influxdata/influxdb/task/options"
)

// ErrDBReadOnly is an error for when the database is set to read only.
// Tasks needs to be able to write to the db.
var ErrDBReadOnly = errors.New("db is read only")

// ErrMaxConcurrency is an error for when the max concurrency is already
// reached for a task when you try to schedule a task.
var ErrMaxConcurrency = errors.New("max concurrency reached")

// ErrRunNotFound is an error for when a run isn't found in a FinishRun method.
var ErrRunNotFound = errors.New("run not found")

// ErrNotFound is an error for when a task could not be found
var ErrNotFound = errors.New("task not found")

// Store is task store for bolt.
type Store struct {
	db     *bolt.DB
	bucket []byte
	idGen  platform.IDGenerator

	minLatestCompleted int64
}

const basePath = "/tasks/v1/"

var (
	tasksPath    = []byte(basePath + "tasks")
	orgsPath     = []byte(basePath + "orgs")
	taskMetaPath = []byte(basePath + "task_meta")
	orgByTaskID  = []byte(basePath + "org_by_task_id")
	nameByTaskID = []byte(basePath + "name_by_task_id")
	runIDs       = []byte(basePath + "run_ids")
)

// Option is a optional configuration for the store.
type Option func(*Store)

// NoCatchUp allows you to skip any task that was supposed to run during down time.
func NoCatchUp(st *Store) { st.minLatestCompleted = time.Now().Unix() }

// New gives us a new Store based on "github.com/coreos/bbolt"
func New(db *bolt.DB, rootBucket string, opts ...Option) (*Store, error) {
	if db.IsReadOnly() {
		return nil, ErrDBReadOnly
	}
	bucket := []byte(rootBucket)

	err := db.Update(func(tx *bolt.Tx) error {
		// create root
		root, err := tx.CreateBucketIfNotExists(bucket)
		if err != nil {
			return err
		}
		// create the buckets inside the root
		for _, b := range [][]byte{
			tasksPath, orgsPath, taskMetaPath,
			orgByTaskID, nameByTaskID, runIDs,
		} {
			_, err := root.CreateBucketIfNotExists(b)
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	st := &Store{db: db, bucket: bucket, idGen: snowflake.NewDefaultIDGenerator(), minLatestCompleted: math.MinInt64}
	for _, opt := range opts {
		opt(st)
	}
	return st, nil
}

// CreateTask creates a task in the boltdb task store.
func (s *Store) CreateTask(ctx context.Context, req backend.CreateTaskRequest) (platform.ID, error) {
	o, err := backend.StoreValidator.CreateArgs(req)
	if err != nil {
		return platform.InvalidID(), err
	}
	// Get ID
	id := s.idGen.ID()
	err = s.db.Update(func(tx *bolt.Tx) error {
		// get the root bucket
		b := tx.Bucket(s.bucket)
		name := []byte(o.Name)
		// Encode ID
		encodedID, err := id.Encode()
		if err != nil {
			return err
		}

		// write script
		err = b.Bucket(tasksPath).Put(encodedID, []byte(req.Script))
		if err != nil {
			return err
		}

		// name
		err = b.Bucket(nameByTaskID).Put(encodedID, name)
		if err != nil {
			return err
		}

		// Encode org ID
		encodedOrg, err := req.Org.Encode()
		if err != nil {
			return err
		}

		// org
		orgB, err := b.Bucket(orgsPath).CreateBucketIfNotExists(encodedOrg)
		if err != nil {
			return err
		}

		err = orgB.Put(encodedID, nil)
		if err != nil {
			return err
		}

		err = b.Bucket(orgByTaskID).Put(encodedID, encodedOrg)
		if err != nil {
			return err
		}

		stm := backend.NewStoreTaskMeta(req, o)
		stmBytes, err := stm.Marshal()
		if err != nil {
			return err
		}
		metaB := b.Bucket(taskMetaPath)
		return metaB.Put(encodedID, stmBytes)
	})

	if err != nil {
		return platform.InvalidID(), err
	}

	return id, nil
}

func (s *Store) UpdateTask(ctx context.Context, req backend.UpdateTaskRequest) (backend.UpdateTaskResult, error) {
	var res backend.UpdateTaskResult
	op, err := backend.StoreValidator.UpdateArgs(req)
	if err != nil {
		return res, err
	}

	encodedID, err := req.ID.Encode()
	if err != nil {
		return res, err
	}

	err = s.db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		bt := b.Bucket(tasksPath)

		v := bt.Get(encodedID)
		if v == nil {
			return backend.ErrTaskNotFound
		}
		res.OldScript = string(v)
		if res.OldScript == "" {
			return errors.New("task script not stored properly")
		}
		var newScript string
		if !req.Options.IsZero() || req.Script != "" {
			if err = req.UpdateFlux(res.OldScript); err != nil {
				return err
			}
			newScript = req.Script
		}
		if req.Script == "" {
			// Need to build op from existing script.
			op, err = options.FromScript(res.OldScript)
			if err != nil {
				return err
			}
			newScript = res.OldScript
		} else {
			op, err = options.FromScript(req.Script)
			if err != nil {
				return err
			}
			if err := bt.Put(encodedID, []byte(req.Script)); err != nil {
				return err
			}
			if err := b.Bucket(nameByTaskID).Put(encodedID, []byte(op.Name)); err != nil {
				return err
			}
		}

		var orgID platform.ID

		if err := orgID.Decode(b.Bucket(orgByTaskID).Get(encodedID)); err != nil {
			return err
		}

		stmBytes := b.Bucket(taskMetaPath).Get(encodedID)
		if stmBytes == nil {
			return backend.ErrTaskNotFound
		}
		var stm backend.StoreTaskMeta
		if err := stm.Unmarshal(stmBytes); err != nil {
			return err
		}
		stm.UpdatedAt = time.Now().Unix()
		res.OldStatus = backend.TaskStatus(stm.Status)

		if req.Status != "" {
			stm.Status = string(req.Status)
		}
		if req.AuthorizationID.Valid() {
			stm.AuthorizationID = uint64(req.AuthorizationID)
		}
		stmBytes, err = stm.Marshal()
		if err != nil {
			return err
		}
		if err := b.Bucket(taskMetaPath).Put(encodedID, stmBytes); err != nil {
			return err
		}
		res.NewMeta = stm

		res.NewTask = backend.StoreTask{
			ID:     req.ID,
			Org:    orgID,
			Name:   op.Name,
			Script: newScript,
		}

		return nil
	})
	return res, err
}

// ListTasks lists the tasks based on a filter.
func (s *Store) ListTasks(ctx context.Context, params backend.TaskSearchParams) ([]backend.StoreTaskWithMeta, error) {
	if params.PageSize < 0 {
		return nil, errors.New("ListTasks: PageSize must be positive")
	}
	if params.PageSize > platform.TaskMaxPageSize {
		return nil, fmt.Errorf("ListTasks: PageSize exceeds maximum of %d", platform.TaskMaxPageSize)
	}
	lim := params.PageSize
	if lim == 0 {
		lim = platform.TaskDefaultPageSize
	}
	taskIDs := make([]platform.ID, 0, lim)
	var tasks []backend.StoreTaskWithMeta

	if err := s.db.View(func(tx *bolt.Tx) error {
		var c *bolt.Cursor
		b := tx.Bucket(s.bucket)
		if params.Org.Valid() {
			encodedOrg, err := params.Org.Encode()
			if err != nil {
				return err
			}
			orgB := b.Bucket(orgsPath).Bucket(encodedOrg)
			if orgB == nil {
				return ErrNotFound
			}
			c = orgB.Cursor()
		} else {
			c = b.Bucket(tasksPath).Cursor()
		}
		if params.After.Valid() {
			encodedAfter, err := params.After.Encode()
			if err != nil {
				return err
			}
			c.Seek(encodedAfter)
			for k, _ := c.Next(); k != nil && len(taskIDs) < lim; k, _ = c.Next() {
				var nID platform.ID
				if err := nID.Decode(k); err != nil {
					return err
				}
				taskIDs = append(taskIDs, nID)
			}
		} else {
			for k, _ := c.First(); k != nil && len(taskIDs) < lim; k, _ = c.Next() {
				var nID platform.ID
				if err := nID.Decode(k); err != nil {
					return err
				}
				taskIDs = append(taskIDs, nID)
			}
		}

		tasks = make([]backend.StoreTaskWithMeta, len(taskIDs))
		for i := range taskIDs {
			// TODO(docmerlin): optimization: don't check <-ctx.Done() every time though the loop
			select {
			case <-ctx.Done():
				return ctx.Err()
			default:
				// TODO(docmerlin): change the setup to reduce the number of lookups to 1 or 2.
				encodedID, err := taskIDs[i].Encode()
				if err != nil {
					return err
				}
				tasks[i].Task.ID = taskIDs[i]
				tasks[i].Task.Script = string(b.Bucket(tasksPath).Get(encodedID))
				tasks[i].Task.Name = string(b.Bucket(nameByTaskID).Get(encodedID))
			}
		}
		if params.Org.Valid() {
			for i := range taskIDs {
				select {
				case <-ctx.Done():
					return ctx.Err()
				default:
					tasks[i].Task.Org = params.Org
				}
			}
			goto POPULATE_META
		}
		for i := range taskIDs {
			select {
			case <-ctx.Done():
				return ctx.Err()
			default:
				encodedID, err := taskIDs[i].Encode()
				if err != nil {
					return err
				}

				var orgID platform.ID
				if err := orgID.Decode(b.Bucket(orgByTaskID).Get(encodedID)); err != nil {
					return err
				}
				tasks[i].Task.Org = orgID
			}
		}

	POPULATE_META:
		for i := range taskIDs {
			select {
			case <-ctx.Done():
				return ctx.Err()
			default:
				encodedID, err := taskIDs[i].Encode()
				if err != nil {
					return err
				}

				var stm backend.StoreTaskMeta
				if err := stm.Unmarshal(b.Bucket(taskMetaPath).Get(encodedID)); err != nil {
					return err
				}

				if stm.LatestCompleted < s.minLatestCompleted {
					stm.LatestCompleted = s.minLatestCompleted
					stm.AlignLatestCompleted()
				}

				tasks[i].Meta = stm
			}
		}
		return nil
	}); err != nil {
		if err == ErrNotFound {
			return nil, nil
		}
		return nil, err
	}
	return tasks, nil
}

// FindTaskByID finds a task with a given an ID.  It will return nil if the task does not exist.
func (s *Store) FindTaskByID(ctx context.Context, id platform.ID) (*backend.StoreTask, error) {
	var orgID platform.ID
	var script, name string
	encodedID, err := id.Encode()
	if err != nil {
		return nil, err
	}
	err = s.db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		scriptBytes := b.Bucket(tasksPath).Get(encodedID)
		if scriptBytes == nil {
			return backend.ErrTaskNotFound
		}
		script = string(scriptBytes)

		if err := orgID.Decode(b.Bucket(orgByTaskID).Get(encodedID)); err != nil {
			return err
		}

		name = string(b.Bucket(nameByTaskID).Get(encodedID))
		return nil
	})
	if err != nil {
		return nil, err
	}

	return &backend.StoreTask{
		ID:     id,
		Org:    orgID,
		Name:   name,
		Script: script,
	}, err
}

func (s *Store) FindTaskMetaByID(ctx context.Context, id platform.ID) (*backend.StoreTaskMeta, error) {
	var stm backend.StoreTaskMeta
	encodedID, err := id.Encode()
	if err != nil {
		return nil, err
	}
	err = s.db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		stmBytes := b.Bucket(taskMetaPath).Get(encodedID)
		if stmBytes == nil {
			return backend.ErrTaskNotFound
		}
		return stm.Unmarshal(stmBytes)
	})
	if err != nil {
		return nil, err
	}

	if stm.LatestCompleted < s.minLatestCompleted {
		stm.LatestCompleted = s.minLatestCompleted
		stm.AlignLatestCompleted()
	}

	return &stm, nil
}

func (s *Store) FindTaskByIDWithMeta(ctx context.Context, id platform.ID) (*backend.StoreTask, *backend.StoreTaskMeta, error) {
	var stmBytes []byte
	var orgID platform.ID
	var script, name string
	encodedID, err := id.Encode()
	if err != nil {
		return nil, nil, err
	}
	err = s.db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		scriptBytes := b.Bucket(tasksPath).Get(encodedID)
		if scriptBytes == nil {
			return backend.ErrTaskNotFound
		}
		script = string(scriptBytes)

		// Assign copies of everything so we don't hold a stale reference to a bolt-maintained byte slice.
		stmBytes = append(stmBytes, b.Bucket(taskMetaPath).Get(encodedID)...)

		if err := orgID.Decode(b.Bucket(orgByTaskID).Get(encodedID)); err != nil {
			return err
		}

		name = string(b.Bucket(nameByTaskID).Get(encodedID))
		return nil
	})
	if err != nil {
		return nil, nil, err
	}

	stm := backend.StoreTaskMeta{}
	if err := stm.Unmarshal(stmBytes); err != nil {
		return nil, nil, err
	}

	if stm.LatestCompleted < s.minLatestCompleted {
		stm.LatestCompleted = s.minLatestCompleted
		stm.AlignLatestCompleted()
	}

	return &backend.StoreTask{
		ID:     id,
		Org:    orgID,
		Name:   name,
		Script: script,
	}, &stm, nil
}

// DeleteTask deletes the task.
func (s *Store) DeleteTask(ctx context.Context, id platform.ID) (deleted bool, err error) {
	encodedID, err := id.Encode()
	if err != nil {
		return false, err
	}
	err = s.db.Batch(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		if check := b.Bucket(tasksPath).Get(encodedID); check == nil {
			return backend.ErrTaskNotFound
		}
		if err := b.Bucket(taskMetaPath).Delete(encodedID); err != nil {
			return err
		}
		if err := b.Bucket(tasksPath).Delete(encodedID); err != nil {
			return err
		}
		if err := b.Bucket(nameByTaskID).Delete(encodedID); err != nil {
			return err
		}

		org := b.Bucket(orgByTaskID).Get(encodedID)
		if len(org) > 0 {
			if err := b.Bucket(orgsPath).Bucket(org).Delete(encodedID); err != nil {
				return err
			}
		}
		return b.Bucket(orgByTaskID).Delete(encodedID)
	})
	if err != nil {
		if err == backend.ErrTaskNotFound {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func (s *Store) CreateNextRun(ctx context.Context, taskID platform.ID, now int64) (backend.RunCreation, error) {
	var rc backend.RunCreation

	encodedID, err := taskID.Encode()
	if err != nil {
		return rc, err
	}

	if err := s.db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		stmBytes := b.Bucket(taskMetaPath).Get(encodedID)
		if stmBytes == nil {
			return backend.ErrTaskNotFound
		}

		var stm backend.StoreTaskMeta
		err := stm.Unmarshal(stmBytes)
		if err != nil {
			return err
		}

		if stm.LatestCompleted < s.minLatestCompleted {
			stm.LatestCompleted = s.minLatestCompleted
			stm.AlignLatestCompleted()
		}

		rc, err = stm.CreateNextRun(now, func() (platform.ID, error) {
			return s.idGen.ID(), nil
		})
		if err != nil {
			return err
		}
		rc.Created.TaskID = taskID

		stmBytes, err = stm.Marshal()
		if err != nil {
			return err
		}
		return tx.Bucket(s.bucket).Bucket(taskMetaPath).Put(encodedID, stmBytes)
	}); err != nil {
		return backend.RunCreation{}, err
	}

	return rc, nil
}

// FinishRun removes runID from the list of running tasks and if its `now` is later then last completed update it.
func (s *Store) FinishRun(ctx context.Context, taskID, runID platform.ID) error {
	encodedID, err := taskID.Encode()
	if err != nil {
		return err
	}

	return s.db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		stmBytes := b.Bucket(taskMetaPath).Get(encodedID)
		var stm backend.StoreTaskMeta
		if err := stm.Unmarshal(stmBytes); err != nil {
			return err
		}
		if !stm.FinishRun(runID) {
			return ErrRunNotFound
		}

		stmBytes, err := stm.Marshal()
		if err != nil {
			return err
		}

		return tx.Bucket(s.bucket).Bucket(taskMetaPath).Put(encodedID, stmBytes)
	})
}

func (s *Store) ManuallyRunTimeRange(_ context.Context, taskID platform.ID, start, end, requestedAt int64) (*backend.StoreTaskMetaManualRun, error) {
	encodedID, err := taskID.Encode()
	if err != nil {
		return nil, err
	}
	var mRun *backend.StoreTaskMetaManualRun

	if err = s.db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		stmBytes := b.Bucket(taskMetaPath).Get(encodedID)
		var stm backend.StoreTaskMeta
		if err := stm.Unmarshal(stmBytes); err != nil {
			return err
		}
		makeID := func() (platform.ID, error) { return s.idGen.ID(), nil }
		if err := stm.ManuallyRunTimeRange(start, end, requestedAt, makeID); err != nil {
			return err
		}

		stmBytes, err := stm.Marshal()
		if err != nil {
			return err
		}
		mRun = stm.ManualRuns[len(stm.ManualRuns)-1]

		return tx.Bucket(s.bucket).Bucket(taskMetaPath).Put(encodedID, stmBytes)
	}); err != nil {
		return nil, err
	}
	return mRun, nil
}

// Close closes the store
func (s *Store) Close() error {
	return s.db.Close()
}

// DeleteOrg synchronously deletes an org and all their tasks from a bolt store.
func (s *Store) DeleteOrg(ctx context.Context, id platform.ID) error {
	orgID, err := id.Encode()
	if err != nil {
		return err
	}

	return s.db.Batch(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		ob := b.Bucket(orgsPath).Bucket(orgID)
		if ob == nil {
			return backend.ErrOrgNotFound
		}
		c := ob.Cursor()
		i := 0
		for k, _ := c.First(); k != nil; k, _ = c.Next() {
			i++
			// check for cancelation every 256 tasks deleted
			if i&0xFF == 0 {
				select {
				case <-ctx.Done():
					return ctx.Err()
				default:
				}
			}
			if err := b.Bucket(tasksPath).Delete(k); err != nil {
				return err
			}
			if err := b.Bucket(taskMetaPath).Delete(k); err != nil {
				return err
			}
			if err := b.Bucket(orgByTaskID).Delete(k); err != nil {
				return err
			}
			if err := b.Bucket(nameByTaskID).Delete(k); err != nil {
				return err
			}
		}
		// check for cancelation one last time before we return
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
			return b.Bucket(orgsPath).DeleteBucket(orgID)
		}
	})
}

repository: kungehero/influxdb

repo_name: kungehero/influxdb