prompt
stringlengths
353
6.99k
full-code-of-function
stringlengths
42
7k
__index_level_0__
int64
1
820k
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: time.rb path of file: ./repos/i18n/lib/i18n/tests/localization the code of the file until where you have to start completion: # encoding: utf-8 module I18n module Tests module Localization module Time def setup super setup_time_translations @time = ::Time.utc(2008, 3, 1, 6, 0) @other_time = ::Time.utc(2008, 3, 1, 18, 0) end test "localize
def setup_time_translations I18n.backend.store_translations :de, { :time => { :formats => { :default => "%a, %d. %b %Y %H:%M:%S %z", :short => "%d. %b %H:%M", :long => "%d. %B %Y %H:%M", }, :am => 'am', :pm => 'pm' } } end
439,423
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: logger_golog.go path of file: ./repos/faygo/vendor/github.com/couchbase/goutils/logging the code of the file until where you have to start completion: // Copyright (c) 2016-2019 Couchbase, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License
func (gl *goLogger) Requestm(rlevel Level, msg string, kv Map) { if gl.logger == nil { return } if REQUEST <= gl.level { e := newLogEntry(msg, REQUEST) e.Rlevel = rlevel e.Data = kv gl.log(e) } }
249,180
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: endpoint.rs path of file: ./repos/aws-sdk-rust/sdk/cloudfrontkeyvaluestore/src/config the code of the file until where you have to start completion: // Code generated
fn test_2() { let params = crate::config::endpoint::Params::builder().build().expect("invalid params"); let resolver = crate::config::endpoint::DefaultResolver::new(); let endpoint = resolver.resolve_endpoint(&params); let error = endpoint.expect_err("expected error: KVS ARN must be provided to use this service [KVS ARN must be provided to use this service]"); assert_eq!(format!("{}", error), "KVS ARN must be provided to use this service") }
756,098
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: chain_id_test.go path of file: ./repos/ethermint/types the code of the file until where you have to start completion: package types import ( "math/big" "strings" "testing" "github.com/stretchr/testify/require" ) func TestParseChainID(t *testing.T) { testCases := []struct { name string chainID string expError bool expInt *big.Int }{ { "valid chain-id, single digit", "ethermint_1-1", false, big.NewInt(1), }, { "valid chain-id, multiple digits", "aragonchain_256-1", false, big.NewInt(256), }, { "invalid chain-id, double dash", "aragonchain-1-1", true, nil, }, { "invalid chain-id, double underscore", "aragonchain_1_1", true, nil, }, { "invalid chain-id, dash only", "-", true, nil, }, { "invalid chain-id, undefined identifier and EIP155", "-1", true, nil, }, { "invalid chain-id, undefined identifier", "_1-1", true, nil, }, { "invalid chain-id, uppercases", "ETHERMINT_1-1", true, nil, }, { "invalid chain-id, mixed cases", "Ethermint_1-1", true, nil, }, { "invalid chain-id, special chars", "$&*#!_1-1", true, nil, }, { "invalid eip155 chain-id, cannot start with 0", "ethermint_001-1", true, nil, }, { "invalid eip155 chain-id, cannot invalid base", "ethermint_0x212-1", true, nil, }, { "invalid eip155 chain-id, non-integer", "ethermint_ethermint_9000-1", true, nil, }, { "invalid epoch, undefined", "ethermint_-", true, nil, }, { "blank chain ID", " ", true, nil, }, { "empty chain ID", "", true, nil, }, { "empty content for chain id, eip155 and epoch numbers", "_-", true,
func TestParseChainID(t *testing.T) { testCases := []struct { name string chainID string expError bool expInt *big.Int }{ { "valid chain-id, single digit", "ethermint_1-1", false, big.NewInt(1), }, { "valid chain-id, multiple digits", "aragonchain_256-1", false, big.NewInt(256), }, { "invalid chain-id, double dash", "aragonchain-1-1", true, nil, }, { "invalid chain-id, double underscore", "aragonchain_1_1", true, nil, }, { "invalid chain-id, dash only", "-", true, nil, }, { "invalid chain-id, undefined identifier and EIP155", "-1", true, nil, }, { "invalid chain-id, undefined identifier", "_1-1", true, nil, }, { "invalid chain-id, uppercases", "ETHERMINT_1-1", true, nil, }, { "invalid chain-id, mixed cases", "Ethermint_1-1", true, nil, }, { "invalid chain-id, special chars", "$&*#!_1-1", true, nil, }, { "invalid eip155 chain-id, cannot start with 0", "ethermint_001-1", true, nil, }, { "invalid eip155 chain-id, cannot invalid base", "ethermint_0x212-1", true, nil, }, { "invalid eip155 chain-id, non-integer", "ethermint_ethermint_9000-1", true, nil, }, { "invalid epoch, undefined", "ethermint_-", true, nil, }, { "blank chain ID", " ", true, nil, }, { "empty chain ID", "", true, nil, }, { "empty content for chain id, eip155 and epoch numbers", "_-", true, nil, }, { "long chain-id", "ethermint_" + strings.Repeat("1", 40) + "-1", true, nil, }, } for _, tc := range testCases { chainIDEpoch, err := ParseChainID(tc.chainID) if tc.expError { require.Error(t, err, tc.name) require.Nil(t, chainIDEpoch) require.False(t, IsValidChainID(tc.chainID), tc.name) } else { require.NoError(t, err, tc.name) require.Equal(t, tc.expInt, chainIDEpoch, tc.name) require.True(t, IsValidChainID(tc.chainID)) } } }
79,426
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sunspec.go path of file: ./repos/evcc/util/modbus the code of the file until where you have to start completion: package modbus import ( "fmt" "strconv" "strings" ) // SunSpecOperation is a sunspec modbus operation type SunSpecOperation struct { Model, Block int Point string } // ParsePoint parses sunspec point from string func ParsePoint(selector string) (SunSpecOperation, error) { var ( res
func ParsePoint(selector string) (SunSpecOperation, error) { var ( res SunSpecOperation err error ) el := strings.Split(selector, ":") if len(el) < 2 || len(el) > 3 { return res, fmt.Errorf("invalid sunspec format: %s", selector) } if res.Model, err = strconv.Atoi(el[0]); err != nil { return res, fmt.Errorf("invalid sunspec model: %s", selector) } if len(el) == 3 { // block is the middle element res.Block, err = strconv.Atoi(el[1]) if err != nil { return res, fmt.Errorf("invalid sunspec block: %s", selector) } } res.Point = el[len(el)-1] return res, nil }
290,394
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: socket_linux.go path of file: ./repos/fabio/vendor/github.com/vishvananda/netlink the code of the file until where you have to start completion: package netlink import ( "errors" "fmt" "net" "syscall" "github.com/vishvananda/netlink/nl" "golang.org/x/sys/unix" ) const ( sizeofSocketID = 0x30 sizeofSocketRequest = sizeofSocketID + 0x8 sizeofSocket = sizeofSocketID + 0x18 ) type socketRequest struct { Family uint8 Protocol uint8 Ext uint8 pad uint8 States uint32 ID SocketID } type writeBuffer struct { Bytes []byte pos int } func (b *writeBuffer) Write(c byte) { b.Bytes[b.pos] = c b.pos
func SocketDiagTCPInfo(family uint8) ([]*InetDiagTCPInfoResp, error) { s, err := nl.Subscribe(unix.NETLINK_INET_DIAG) if err != nil { return nil, err } defer s.Close() req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, unix.NLM_F_DUMP) req.AddData(&socketRequest{ Family: family, Protocol: unix.IPPROTO_TCP, Ext: (1 << (INET_DIAG_VEGASINFO - 1)) | (1 << (INET_DIAG_INFO - 1)), States: uint32(0xfff), // All TCP states }) s.Send(req) var result []*InetDiagTCPInfoResp loop: for { msgs, from, err := s.Receive() if err != nil { return nil, err } if from.Pid != nl.PidKernel { return nil, fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel) } if len(msgs) == 0 { return nil, errors.New("no message nor error from netlink") } for _, m := range msgs { switch m.Header.Type { case unix.NLMSG_DONE: break loop case unix.NLMSG_ERROR: native := nl.NativeEndian() error := int32(native.Uint32(m.Data[0:4])) return nil, syscall.Errno(-error) } sockInfo := &Socket{} if err := sockInfo.deserialize(m.Data); err != nil { return nil, err } attrs, err := nl.ParseRouteAttr(m.Data[sizeofSocket:]) if err != nil { return nil, err } res, err := attrsToInetDiagTCPInfoResp(attrs, sockInfo) if err != nil { return nil, err } result = append(result, res) } } return result, nil }
596,473
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: acts_as_inheritable.rb path of file: ./repos/acts_as_inheritable/lib the code of the file until where you have to start completion: require 'active_record' require 'acts_as_inheritable/version' module ActsAsInheritable def acts_as_inheritable(options) fail ArgumentError, "Hash expected, got #{options.class.name}" unless options.is_a?(Hash) fail ArgumentError, 'Empty options' if options[:attributes].blank? && options[:associations].blank? class_attribute :inheritable_configuration self.inheritable_configuration = {} self.inheritable_configuration.merge!(options) class_eval do def has_parent? parent.present? end
def inherit_attributes(force = false, not_force_for = [], method_to_update = nil) available_methods = ['update_attributes', 'update_columns'] if has_parent? && self.class.inheritable_configuration[:attributes] # Attributes self.class.inheritable_configuration[:attributes].each do |attribute| current_val = send(attribute) if (force && !not_force_for.include?(attribute)) || current_val.blank? if method_to_update && available_methods.include?(method_to_update) send(method_to_update, {attribute => parent.send(attribute)}) else send("#{attribute}=", parent.send(attribute)) end end
495,899
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: expressrouteserviceproviders_client_example_test.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // DO NOT EDIT. package armnetwork_test import ( "context" "log" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetw
func ExampleExpressRouteServiceProvidersClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnetwork.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := clientFactory.NewExpressRouteServiceProvidersClient().NewListPager(nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range page.Value { // You could use page here. We use blank identifier for just demo purposes. _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // page.ExpressRouteServiceProviderListResult = armnetwork.ExpressRouteServiceProviderListResult{ // Value: []*armnetwork.ExpressRouteServiceProvider{ // { // Name: to.Ptr("providerName"), // Type: to.Ptr("Microsoft.Network/expressRouteServiceProviders"), // ID: to.Ptr("/subscriptions//resourceGroups//providers/Microsoft.Network/expressRouteServiceProviders/"), // Properties: &armnetwork.ExpressRouteServiceProviderPropertiesFormat{ // BandwidthsOffered: []*armnetwork.ExpressRouteServiceProviderBandwidthsOffered{ // { // OfferName: to.Ptr("50Mbps"), // ValueInMbps: to.Ptr[int32](50), // }, // { // OfferName: to.Ptr("100Mbps"), // ValueInMbps: to.Ptr[int32](100), // }, // { // OfferName: to.Ptr("200Mbps"), // ValueInMbps: to.Ptr[int32](200), // }, // { // OfferName: to.Ptr("500Mbps"), // ValueInMbps: to.Ptr[int32](500), // }, // { // OfferName: to.Ptr("1Gbps"), // ValueInMbps: to.Ptr[int32](1000), // }, // { // OfferName: to.Ptr("2Gbps"), // ValueInMbps: to.Ptr[int32](2000), // }, // { // OfferName: to.Ptr("5Gbps"), // ValueInMbps: to.Ptr[int32](5000), // }, // { // OfferName: to.Ptr("10Gbps"), // ValueInMbps: to.Ptr[int32](10000), // }}, // PeeringLocations: []*string{ // to.Ptr("peeringLocation1"), // to.Ptr("peeringLocation2")}, // ProvisioningState: to.Ptr(armnetwork.ProvisioningStateSucceeded), // }, // }}, // } } }
264,160
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: errors.go path of file: ./repos/glide/vendor/github.com/codegangsta/cli the code of the file until where you have to start completion: package cli import ( "fmt" "io" "os" "strings" ) // OsExiter is the fu
func (m MultiError) Error() string { errs := make([]string, len(m.Errors)) for i, err := range m.Errors { errs[i] = err.Error() } return strings.Join(errs, "\n") }
676,428
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: d.go path of file: ./repos/codeforces-go/leetcode/weekly/301/d the code of the file until where you have to start completion: package main // https://space.bilibili.com/206214/dynamic const mod, mx int = 1e9 + 7, 1e4 + 20
func pow(x, n int) int { res := 1 for ; n > 0; n >>= 1 { if n&1 == 1 { res = res * x % mod } x = x * x % mod } return res }
131,006
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: windows.go path of file: ./repos/faygo/vendor/github.com/fsnotify/fsnotify the code of the file until where you have to start completion: // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package fsnotify import ( "errors" "fmt" "os" "path/filepath" "runtime" "sync" "syscall" "unsafe" ) // Watcher watches a set of files, delivering events to a channel. type Watcher struct { Events chan Event Errors chan error isClosed bool // Set to true when Close() is first called mu sync.Mutex // Map access port syscall.Handle //
func (w *Watcher) addWatch(pathname string, flags uint64) error { dir, err := getDir(pathname) if err != nil { return err } if flags&sysFSONLYDIR != 0 && pathname != dir { return nil } ino, err := getIno(dir) if err != nil { return err } w.mu.Lock() watchEntry := w.watches.get(ino) w.mu.Unlock() if watchEntry == nil { if _, e := syscall.CreateIoCompletionPort(ino.handle, w.port, 0, 0); e != nil { syscall.CloseHandle(ino.handle) return os.NewSyscallError("CreateIoCompletionPort", e) } watchEntry = &watch{ ino: ino, path: dir, names: make(map[string]uint64), } w.mu.Lock() w.watches.set(ino, watchEntry) w.mu.Unlock() flags |= provisional } else { syscall.CloseHandle(ino.handle) } if pathname == dir { watchEntry.mask |= flags } else { watchEntry.names[filepath.Base(pathname)] |= flags } if err = w.startRead(watchEntry); err != nil { return err } if pathname == dir { watchEntry.mask &= ^provisional } else { watchEntry.names[filepath.Base(pathname)] &= ^provisional } return nil }
249,302
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: container_top.go path of file: ./repos/sealer/vendor/github.com/docker/docker/client the code of the file until where you have to start completion: package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" "net/url" "strings" "github.com/
func (cli *Client) ContainerTop(ctx context.Context, containerID string, arguments []string) (container.ContainerTopOKBody, error) { var response container.ContainerTopOKBody query := url.Values{} if len(arguments) > 0 { query.Set("ps_args", strings.Join(arguments, " ")) } resp, err := cli.get(ctx, "/containers/"+containerID+"/top", query, nil) defer ensureReaderClosed(resp) if err != nil { return response, err } err = json.NewDecoder(resp.body).Decode(&response) return response, err }
721,364
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: boot.rb path of file: ./repos/truffleruby/src/main/ruby/truffleruby/core/truffle the code of the file until where you have to start completion: # frozen_string_literal: true # Copyright (c) 2016, 2
def self.find_in_environment_paths(name, env_value) env_value.to_s.split(File::PATH_SEPARATOR).each do |path| name_in_path = "#{path}/#{name}" return name_in_path if File.exist?(name_in_path) end nil end
177,323
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: helm_v3.go path of file: ./repos/devspace/vendor/github.com/loft-sh/utils/pkg/downloader/commands the code of the file until where you have to start completion: package commands import ( "context" "os" "path/filepath" "runtime" "strings" "github.com/l
func (h *helmv3) InstallPath(toolHomeFolder string) (string, error) { home, err := homedir.Dir() if err != nil { return "", err } installPath := filepath.Join(home, toolHomeFolder, "bin", h.Name()) if runtime.GOOS == "windows" { installPath += ".exe" } return installPath, nil }
466,695
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: caching_sha2.go path of file: ./repos/tidb/pkg/parser/auth the code of the file until where you have to start completion: // Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless requi
func CheckHashingPassword(pwhash []byte, password string, hash string) (bool, error) { pwhashParts := bytes.Split(pwhash, []byte("$")) if len(pwhashParts) != 4 { return false, errors.New("failed to decode hash parts") } hashType := string(pwhashParts[1]) if hashType != "A" { return false, errors.New("digest type is incompatible") } iterations, err := strconv.ParseInt(string(pwhashParts[2]), 16, 64) if err != nil { return false, errors.New("failed to decode iterations") } iterations = iterations * ITERATION_MULTIPLIER salt := pwhashParts[3][:SALT_LENGTH] var newHash string switch hash { case mysql.AuthCachingSha2Password: newHash = hashCrypt(password, salt, int(iterations), Sha256Hash) case mysql.AuthTiDBSM3Password: newHash = hashCrypt(password, salt, int(iterations), Sm3Hash) } return bytes.Equal(pwhash, []byte(newHash)), nil }
581,296
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: send_node.rb path of file: ./repos/solargraph/lib/solargraph/parser/legacy/node_processors the code of the file until where you have to start completion: # frozen_string_literal: true module Solargraph module Parser module Legacy module NodeProcessors class SendNode < Parser::NodeProcessor::Base include Legacy::NodeMethods def process if node.children[0].nil? if [:private, :public, :protected].include?(node.children[1]) process_visibility elsif node.children[1] == :module_function process_module_function elsif [:attr_reader, :attr_writer, :attr_accessor].include?(node.children[1]) process_attribute elsif node.children[1] == :include process_include elsif node.children[1] == :extend process_extend elsif node.children[1] == :prepend process_prepend elsif node.children[1] == :require process_require elsif node.children[1] == :autoload process_autoload elsif node.children[1] == :private_constant process_private_constant
def process_module_function if node.children[2].nil? # @todo Smelly instance variable access region.instance_variable_set(:@visibility, :module_function) elsif node.children[2].type == :sym || node.children[2].type == :str node.children[2..-1].each do |x| cn = x.children[0].to_s ref = pins.select{ |p| p.is_a?(Pin::Method) && p.namespace == region.closure.full_context.namespace && p.name == cn }.first unless ref.nil? pins.delete ref mm = Solargraph::Pin::Method.new( location: ref.location, closure: ref.closure, name: ref.name, parameters: ref.parameters, comments: ref.comments, scope: :class, visibility: :public, node: ref.node ) cm = Solargraph::Pin::Method.new( location: ref.location, closure: ref.closure, name: ref.name, parameters: ref.parameters, comments: ref.comments, scope: :instance, visibility: :private, node: ref.node) pins.push mm, cm pins.select{|pin| pin.is_a?(Pin::InstanceVariable) && pin.closure.path == ref.path}.each do |ivar| pins.delete ivar pins.push Solargraph::Pin::InstanceVariable.new( location: ivar.location, closure: cm, name: ivar.name, comments: ivar.comments, assignment: ivar.assignment ) pins.push Solargraph::Pin::InstanceVariable.new( location: ivar.location, closure: mm, name: ivar.name, comments: ivar.comments, assignment: ivar.assignment ) end end end
678,192
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: flatten.go path of file: ./repos/agones/vendor/k8s.io/gengo/types the code of the file until where you have to start completion: /* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use t
func FlattenMembers(m []Member) []Member { embedded := []Member{} normal := []Member{} type nameInfo struct { top bool i int } names := map[string]nameInfo{} for i := range m { if m[i].Embedded && m[i].Type.Kind == Struct { embedded = append(embedded, m[i]) } else { normal = append(normal, m[i]) names[m[i].Name] = nameInfo{true, len(normal) - 1} } } for i := range embedded { for _, e := range FlattenMembers(embedded[i].Type.Members) { if info, found := names[e.Name]; found { if info.top { continue } if n := normal[info.i]; n.Name == e.Name && n.Type == e.Type { continue } panic("conflicting members") } normal = append(normal, e) names[e.Name] = nameInfo{false, len(normal) - 1} } } return normal }
445,493
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: admin.rs path of file: ./repos/holochain-rust/crates/conductor_lib/src/conductor the code of the file until where you have to start completion: use crate::{ conductor::{base::
pub fn instance1() -> String { r#"[[instances]] agent = 'test-agent-1' dna = 'test-dna' id = 'test-instance-1' [instances.storage] type = 'memory'"# .to_string() }
150,844
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: transaction_event_aggregator.rb path of file: ./repos/newrelic-ruby-agent/lib/new_relic/agent the code of the file until where you have to start completion: # -*- ruby -*- # This file is distributed under New Relic's lic
def record_sampling_rate(metadata) # THREAD_LOCAL_ACCESS NewRelic::Agent.logger.debug('Sampled %d / %d (%.1f %%) requests this cycle, %d / %d (%.1f %%) since startup' % [ metadata[:captured], metadata[:seen], (metadata[:captured].to_f / metadata[:seen] * 100.0), metadata[:captured_lifetime], metadata[:seen_lifetime], (metadata[:captured_lifetime].to_f / metadata[:seen_lifetime] * 100.0) ]) engine = NewRelic::Agent.instance.stats_engine engine.tl_record_supportability_metric_count('TransactionEventAggregator/requests', metadata[:seen]) engine.tl_record_supportability_metric_count('TransactionEventAggregator/samples', metadata[:captured]) end
238,781
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: MOEADEGO.m path of file: ./repos/PlatEMO/PlatEMO/Algorithms/Multi-objective optimization/MOEA-D-EGO the code of the file until where you have to start completion: classdef MOEADEGO < ALGORITHM % <multi> <real/integer> <expensive> % MOEA/D with efficient global optimization % Ke --- 5 --- The number of function evaluations at each generation % delta --- 0.9 --- The probability of choosing parents locally % nr --- 2 --- Maximum number of solutions replaced by each offspring % L1 --- 80 --- The maximal number of points used for building a local model % L2 --- 20 --- The maximal number of points used for building a local model %------------------------------- Reference -------------------------------- % Q. Zhang, W. Liu, E. Tsang, and B. Virginas, Expensive multiobjective % optimization by MOEA/D with Gaussian process model, IEEE Transactions on % Evolutionary Computation, 2010, 14(3): 456-474. %------------------------------- Copyright -------------------------------- % Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for % research purposes. All publications which use this platform or any code % in th
function evaluations at each generation % delta --- 0.9 --- The probability of choosing parents locally % nr --- 2 --- Maximum number of solutions replaced by each offspring % L1 --- 80 --- The maximal number of points used for building a local model % L2 --- 20 --- The maximal number of points used for building a local model %------------------------------- Reference -------------------------------- % Q. Zhang, W. Liu, E. Tsang, and B. Virginas, Expensive multiobjective % optimization by MOEA/D with Gaussian process model, IEEE Transactions on % Evolutionary Computation, 2010, 14(3): 456-474. %------------------------------- Copyright -------------------------------- % Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for % research purposes. All publications which use this platform or any code % in the platform should acknowledge the use of "PlatEMO" and reference "Ye % Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform % for evolutionary multi-objective optimization [educational forum], IEEE % Computational Intelligence Magazine, 2017, 12(4): 73-87". %-------------------------------------------------------------------------- % This function is written by Cheng He methods function main(Algorithm,Problem) %% Parameter setting [Ke,delta,nr,L1,L2] = Algorithm.ParameterSet(5,0.9,2,80,20); %% Generate random population NI = 11*Problem.D-1; P = UniformPoint(NI,Problem.D,'Latin'); Population = Problem.Evaluation(repmat(Problem.upper-Problem.lower,NI,1).*P+repmat(Problem.lower,NI,1)); L1 = min(L1,length(Population)); %% Optimization while Algorithm.NotTerminated(Population) PopDec = EGOSelect(Problem,Population,L1,L2,Ke,delta,nr); Offspring = Problem.Evaluation(PopDec); Population = [Population,Offspring]; end
323,034
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: rct_decorators.go path of file: ./repos/evcc/meter the code of the file until where you have to start completion: package meter // Code generated by github.com/evcc-io/evcc/cmd/tools/decorate.go. DO NOT EDIT. import ( "github.com/evcc-io/evcc/api" ) func decorateRCT(base *RCT, meterEnergy func() (float64, error), battery func() (float64, error), batteryCapacity func() float64) api.Meter { switch { case battery == nil && batteryCapacity == nil && meterEnergy == nil: return base case battery == nil && batteryCapacity == nil && meterEnergy != nil: return &struct { *RCT api.MeterEnergy }{ RCT: base, MeterEnergy: &decorateRCTMeterEnergyImpl{ meterEnergy: meterEnergy, }, } case battery != nil && batteryCapacity == nil && meterEnergy == nil: return &struct { *RCT api.Battery }{ RCT: base, Battery: &decorateRCTBatteryImpl{ battery: battery, }, } case battery != nil && batteryCapacity == nil && meterEnergy != nil: return &struct { *RCT api.Battery api.MeterEnergy }{ RCT: base, Battery: &decorateRCTBatteryImpl{ battery: battery, }, MeterEnergy: &decorateRCTMeterEnergyImpl{ meterEnergy: meterEnergy, }, } case battery == nil && batteryCapacity != nil && meterEnergy == nil: return &struct { *RCT api.BatteryCapacity }{ RCT: base, BatteryCapacity: &decorateRCTBatteryCapacityImpl{ batteryCapacity: batteryCapacity, }, } case battery == nil && batteryCapacity != nil && meterEnergy != nil: return &struct { *RCT api.BatteryCapacity api.MeterEnergy }{ RCT: base, BatteryCapacity: &decorateRCTBatteryCapacityImpl{ batteryCapacity: batteryCapacity, }, MeterEnergy: &decorateRCTMeterEnergyImpl{ meterEnergy: meterEnergy, }, } case battery != nil && batteryCapacity != nil && meterEnergy == nil: return &struct { *RCT api.Battery api.BatteryCapacity }{ RCT: base, Battery: &decorateRCTBatteryImpl{ battery: battery, }, BatteryCapacity: &decorateRCTBatteryCapacityImpl{ ba
func decorateRCT(base *RCT, meterEnergy func() (float64, error), battery func() (float64, error), batteryCapacity func() float64) api.Meter { switch { case battery == nil && batteryCapacity == nil && meterEnergy == nil: return base case battery == nil && batteryCapacity == nil && meterEnergy != nil: return &struct { *RCT api.MeterEnergy }{ RCT: base, MeterEnergy: &decorateRCTMeterEnergyImpl{ meterEnergy: meterEnergy, }, } case battery != nil && batteryCapacity == nil && meterEnergy == nil: return &struct { *RCT api.Battery }{ RCT: base, Battery: &decorateRCTBatteryImpl{ battery: battery, }, } case battery != nil && batteryCapacity == nil && meterEnergy != nil: return &struct { *RCT api.Battery api.MeterEnergy }{ RCT: base, Battery: &decorateRCTBatteryImpl{ battery: battery, }, MeterEnergy: &decorateRCTMeterEnergyImpl{ meterEnergy: meterEnergy, }, } case battery == nil && batteryCapacity != nil && meterEnergy == nil: return &struct { *RCT api.BatteryCapacity }{ RCT: base, BatteryCapacity: &decorateRCTBatteryCapacityImpl{ batteryCapacity: batteryCapacity, }, } case battery == nil && batteryCapacity != nil && meterEnergy != nil: return &struct { *RCT api.BatteryCapacity api.MeterEnergy }{ RCT: base, BatteryCapacity: &decorateRCTBatteryCapacityImpl{ batteryCapacity: batteryCapacity, }, MeterEnergy: &decorateRCTMeterEnergyImpl{ meterEnergy: meterEnergy, }, } case battery != nil && batteryCapacity != nil && meterEnergy == nil: return &struct { *RCT api.Battery api.BatteryCapacity }{ RCT: base, Battery: &decorateRCTBatteryImpl{ battery: battery, }, BatteryCapacity: &decorateRCTBatteryCapacityImpl{ batteryCapacity: batteryCapacity, }, } case battery != nil && batteryCapacity != nil && meterEnergy != nil: return &struct { *RCT api.Battery api.BatteryCapacity api.MeterEnergy }{ RCT: base, Battery: &decorateRCTBatteryImpl{ battery: battery, }, BatteryCapacity: &decorateRCTBatteryCapacityImpl{ batteryCapacity: batteryCapacity, }, MeterEnergy: &decorateRCTMeterEnergyImpl{ meterEnergy: meterEnergy, }, } } return nil }
289,843
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: repository_storage_moves.rb path of file: ./repos/gitlabhq/qa/qa/runtime/api the code of the file until where you have to start completion: # frozen_string_literal: true module QA module Runtime module API module Repos
def find_any(resource) Logger.debug('Getting repository storage moves') Support::Waiter.wait_until do get(Request.new(api_client, "/#{resource_name(resource)}_repository_storage_moves", per_page: '100').url) do |page| break true if page.any? { |item| yield item } end end end
299,048
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: bad_borrow.rs path of file: ./repos/creusot/creusot/tests/should_fail the code of the file until where you have to start completion: fn bad_borrow() {
fn bad_borrow() { let mut x = 0; let a = &mut x; let b = &mut x; *a += *b; }
640,865
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sqlite3_vtable.go path of file: ./repos/cloud-torrent/vendor/github.com/mattn/go-sqlite3 the code of the file until where you have to start completion: // Copyright (C) 2014 Yasuhiro Matsumoto <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in
func goVNext(pCursor unsafe.Pointer) *C.char { vtc := lookupHandle(uintptr(pCursor)).(*sqliteVTabCursor) err := vtc.vTabCursor.Next() if err != nil { return mPrintf("%s", err.Error()) } return nil }
610,122
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: perf.pb.go path of file: ./repos/sharingan/grpc-server/v1.33.2/test/codec_perf the code of the file until where you have to start completion: // Copyright 2017 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); /
func file_test_codec_perf_perf_proto_init() { if File_test_codec_perf_perf_proto != nil { return } if !protoimpl.UnsafeEnabled { file_test_codec_perf_perf_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Buffer); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_test_codec_perf_perf_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_test_codec_perf_perf_proto_goTypes, DependencyIndexes: file_test_codec_perf_perf_proto_depIdxs, MessageInfos: file_test_codec_perf_perf_proto_msgTypes, }.Build() File_test_codec_perf_perf_proto = out.File file_test_codec_perf_perf_proto_rawDesc = nil file_test_codec_perf_perf_proto_goTypes = nil file_test_codec_perf_perf_proto_depIdxs = nil }
87,453
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: gogo.pb.go path of file: ./repos/learning/golang/practice/go-crontab/gopath/src/github.com/coreos/etcd/vendor/github.com/gogo/protobuf/gogoproto the code of the file until where you have to start completion: // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: gogo.proto /* Package gogoproto is a generated protocol buffer package. It is generated from these files: gogo.proto It has these top-level messages: */ package gogoproto import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package var E_GoprotoEnumPrefix = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62001, Name: "gogoproto.goproto_enum_prefix", Tag: "varint,62001,opt,name=goproto_enum_prefix,json=goprotoEnumPrefix", Filename: "gogo.proto", } var E_GoprotoEnumStringer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62021, Name: "gogoproto.goproto_enum_stringer", Tag: "varint,62021,opt,name=goproto_enum_stringer,json=goprotoEnumStringer", Filename: "gogo.proto", } var E_EnumStringer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62022, Name: "gogoproto.enum_stringer", Tag: "varint,62022,opt,name=enum_stringer,json=enumStringer", Filename: "gogo.proto", } var E_EnumCustomname = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*string)(nil), Field: 62023, Name: "gogoproto.enum_customname", Tag: "bytes,62023,opt,name=enum_customname,json=enumCustomname", Filename: "gogo.proto", } var E_Enumdecl = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62024, Name: "gogoproto.enumdecl", Tag: "varint,62024,opt,name=enumdecl", Filename: "gogo.proto", } var E_EnumvalueCustomname = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumValueOptions)(nil)
func init() { proto.RegisterExtension(E_GoprotoEnumPrefix) proto.RegisterExtension(E_GoprotoEnumStringer) proto.RegisterExtension(E_EnumStringer) proto.RegisterExtension(E_EnumCustomname) proto.RegisterExtension(E_Enumdecl) proto.RegisterExtension(E_EnumvalueCustomname) proto.RegisterExtension(E_GoprotoGettersAll) proto.RegisterExtension(E_GoprotoEnumPrefixAll) proto.RegisterExtension(E_GoprotoStringerAll) proto.RegisterExtension(E_VerboseEqualAll) proto.RegisterExtension(E_FaceAll) proto.RegisterExtension(E_GostringAll) proto.RegisterExtension(E_PopulateAll) proto.RegisterExtension(E_StringerAll) proto.RegisterExtension(E_OnlyoneAll) proto.RegisterExtension(E_EqualAll) proto.RegisterExtension(E_DescriptionAll) proto.RegisterExtension(E_TestgenAll) proto.RegisterExtension(E_BenchgenAll) proto.RegisterExtension(E_MarshalerAll) proto.RegisterExtension(E_UnmarshalerAll) proto.RegisterExtension(E_StableMarshalerAll) proto.RegisterExtension(E_SizerAll) proto.RegisterExtension(E_GoprotoEnumStringerAll) proto.RegisterExtension(E_EnumStringerAll) proto.RegisterExtension(E_UnsafeMarshalerAll) proto.RegisterExtension(E_UnsafeUnmarshalerAll) proto.RegisterExtension(E_GoprotoExtensionsMapAll) proto.RegisterExtension(E_GoprotoUnrecognizedAll) proto.RegisterExtension(E_GogoprotoImport) proto.RegisterExtension(E_ProtosizerAll) proto.RegisterExtension(E_CompareAll) proto.RegisterExtension(E_TypedeclAll) proto.RegisterExtension(E_EnumdeclAll) proto.RegisterExtension(E_GoprotoRegistration) proto.RegisterExtension(E_GoprotoGetters) proto.RegisterExtension(E_GoprotoStringer) proto.RegisterExtension(E_VerboseEqual) proto.RegisterExtension(E_Face) proto.RegisterExtension(E_Gostring) proto.RegisterExtension(E_Populate) proto.RegisterExtension(E_Stringer) proto.RegisterExtension(E_Onlyone) proto.RegisterExtension(E_Equal) proto.RegisterExtension(E_Description) proto.RegisterExtension(E_Testgen) proto.RegisterExtension(E_Benchgen) proto.RegisterExtension(E_Marshaler) proto.RegisterExtension(E_Unmarshaler) proto.RegisterExtension(E_StableMarshaler) proto.RegisterExtension(E_Sizer) proto.RegisterExtension(E_UnsafeMarshaler) proto.RegisterExtension(E_UnsafeUnmarshaler) proto.RegisterExtension(E_GoprotoExtensionsMap) proto.RegisterExtension(E_GoprotoUnrecognized) proto.RegisterExtension(E_Protosizer) proto.RegisterExtension(E_Compare) proto.RegisterExtension(E_Typedecl) proto.RegisterExtension(E_Nullable) proto.RegisterExtension(E_Embed) proto.RegisterExtension(E_Customtype) proto.RegisterExtension(E_Customname) proto.RegisterExtension(E_Jsontag) proto.RegisterExtension(E_Moretags) proto.RegisterExtension(E_Casttype) proto.RegisterExtension(E_Castkey) proto.RegisterExtension(E_Castvalue) proto.RegisterExtension(E_Stdtime) proto.RegisterExtension(E_Stdduration) }
555,805
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 20150515010202_create_activities.rb path of file: ./repos/phishing-frenzy/db/migrate the code of the file until where you have to start completion: # Migration responsible for creating a table with
def self.up create_table :activities do |t| t.belongs_to :trackable, :polymorphic => true t.belongs_to :owner, :polymorphic => true t.string :key t.text :parameters t.belongs_to :recipient, :polymorphic => true t.timestamps end add_index :activities, [:trackable_id, :trackable_type] add_index :activities, [:owner_id, :owner_type] add_index :activities, [:recipient_id, :recipient_type] end
183,732
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: a.pb.go path of file: ./repos/protobuf-go/cmd/protoc-gen-go/testdata/import_public the code of the file until where you have to start completion: // Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by protoc-gen-go. DO NOT EDIT. // source: cmd/protoc-gen-go/testdata/import_public/a.proto package import_public import ( sub "google.golang.org/protobuf/cmd/protoc-gen-go/testdata/import_public/sub" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) // Symbols defined in public import of cmd/protoc-gen-go/testdata/import_public/sub/a.proto. type E = sub.E const E_ZERO = sub.E_ZERO var E_name = sub.E_name var E_value = sub.E_value type M_Subenum = sub.M_Subenum const M_M_ZERO = sub.M_M_ZERO var M_Subenum_name = sub.M_Subenum_name var M_Subenum_value = sub.M_Subenum_value type M_Submessage_Submessage_Subenum = sub.M_Submessage_Submessage_Subenum const M_Submessage_M_SUBMESSAGE_ZERO = sub.M_Submessage_M_SUBMESSAGE_ZERO var M_Submessage_Submessage_Subenum_name = sub.M_Submessage_Submessage_Subenum_name var M_Submessage_Submessage_Subenum_value = sub.M_Submess
func file_cmd_protoc_gen_go_testdata_import_public_a_proto_init() { if File_cmd_protoc_gen_go_testdata_import_public_a_proto != nil { return } file_cmd_protoc_gen_go_testdata_import_public_b_proto_init() if !protoimpl.UnsafeEnabled { file_cmd_protoc_gen_go_testdata_import_public_a_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Public); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_cmd_protoc_gen_go_testdata_import_public_a_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_cmd_protoc_gen_go_testdata_import_public_a_proto_goTypes, DependencyIndexes: file_cmd_protoc_gen_go_testdata_import_public_a_proto_depIdxs, MessageInfos: file_cmd_protoc_gen_go_testdata_import_public_a_proto_msgTypes, }.Build() File_cmd_protoc_gen_go_testdata_import_public_a_proto = out.File file_cmd_protoc_gen_go_testdata_import_public_a_proto_rawDesc = nil file_cmd_protoc_gen_go_testdata_import_public_a_proto_goTypes = nil file_cmd_protoc_gen_go_testdata_import_public_a_proto_depIdxs = nil }
56,424
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: builders.rs path of file: ./repos/aws-sdk-rust/sdk/cloudtrail/src/operation/get_event_data_store the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
819,513
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: services.go path of file: ./repos/openreplay/backend/internal/http/services the code of the file until where you have to start completion: package services import ( "log" "openreplay/backend/internal/config/http" "openreplay/backend/internal/http/geoip" "openreplay/backend/internal/http/uaparser" "openreplay/backend/pkg/conditions" "openreplay/backend/pkg/db/postgres/pool" "openreplay/backend/pkg/db/redis" "openreplay/backend/pkg/featureflags" "openreplay/backend/pk
func New(cfg *http.Config, producer types.Producer, pgconn pool.Pool, redis *redis.Client) (*ServicesBuilder, error) { projs := projects.New(pgconn, redis) // ObjectStorage client to generate pre-signed upload urls objStore, err := store.NewStore(&cfg.ObjectsConfig) if err != nil { log.Fatalf("can't init object storage: %s", err) } return &ServicesBuilder{ Projects: projs, Sessions: sessions.New(pgconn, projs, redis), FeatureFlags: featureflags.New(pgconn), Producer: producer, Tokenizer: token.NewTokenizer(cfg.TokenSecret), UaParser: uaparser.NewUAParser(cfg.UAParserFile), GeoIP: geoip.New(cfg.MaxMinDBFile), Flaker: flakeid.NewFlaker(cfg.WorkerID), ObjStorage: objStore, UXTesting: uxtesting.New(pgconn), Tags: tags.New(pgconn), Conditions: conditions.New(pgconn), }, nil }
577,999
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: efs.go path of file: ./repos/cloudfox/aws/sdk the code of the file until where you have to start completion: package sdk import ( "context" "encoding/gob" "fmt" "github.com/BishopFox/cloudfox/internal" "github.com/BishopFox/cloudfox/internal/aws/policy" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/efs" efsTypes "github.com/aws/aws-sdk-go-v2/service/efs/types" "github.com/patrickmn/go-cache" ) type AWSEFSClientInterface interface { DescribeFileSystems(ctx context.Context, params *efs.DescribeFileSystemsInput, optFns ...func(*efs.Options)) (*efs.DescribeFileSystemsOutput, error) DescribeMountTargets(ctx context.Context, params *efs.DescribeMountTargetsInput, optFns ...func(*efs.Options)) (*efs.DescribeMountTargetsOutput, error) DescribeAccessP
func CachedDescribeFileSystems(EFSClient AWSEFSClientInterface, accountID string, r string) ([]efsTypes.FileSystemDescription, error) { var PaginationMarker *string var filesystems []efsTypes.FileSystemDescription var err error cacheKey := fmt.Sprintf("%s-efs-DescribeFileSystems-%s", accountID, r) cached, found := internal.Cache.Get(cacheKey) if found { return cached.([]efsTypes.FileSystemDescription), nil } for { DescribeFileSystems, err := EFSClient.DescribeFileSystems( context.TODO(), &efs.DescribeFileSystemsInput{ Marker: PaginationMarker, }, func(o *efs.Options) { o.Region = r }, ) if err != nil { sharedLogger.Error(err.Error()) return nil, err } filesystems = append(filesystems, DescribeFileSystems.FileSystems...) // Pagination control. After the last page of output, the for loop exits. if DescribeFileSystems.Marker != nil { PaginationMarker = DescribeFileSystems.Marker } else { PaginationMarker = nil break } } internal.Cache.Set(cacheKey, filesystems, cache.DefaultExpiration) return filesystems, err }
553,606
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: leave_test.go path of file: ./repos/docker-ce/components/cli/cli/command/swarm the code of the file until where you have to start completion: package swarm import ( "io/ioutil" "strings" "testing" "github.com/docker/cli/internal/test" "github.com/pkg/errors" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" ) func TestSwarmLeaveErrors(t *testing.T) { testCases := []struc
func TestSwarmLeaveErrors(t *testing.T) { testCases := []struct { name string args []string swarmLeaveFunc func() error expectedError string }{ { name: "too-many-args", args: []string{"foo"}, expectedError: "accepts no arguments", }, { name: "leave-failed", swarmLeaveFunc: func() error { return errors.Errorf("error leaving the swarm") }, expectedError: "error leaving the swarm", }, } for _, tc := range testCases { cmd := newLeaveCommand( test.NewFakeCli(&fakeClient{ swarmLeaveFunc: tc.swarmLeaveFunc, })) cmd.SetArgs(tc.args) cmd.SetOut(ioutil.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } }
567,893
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_level.rb path of file: ./repos/gitlabhq/tooling/quality the code of the file until where you have to start completion: # frozen_string_literal: true module Quality class TestLevel
def suffix(level) case level when :frontend_fixture ".rb" else "_spec.rb" end
298,679
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: builders.rs path of file: ./repos/aws-sdk-rust/sdk/glue/src/operation/delete_table the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
795,742
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: client.rs path of file: ./repos/aws-sdk-rust/sdk/sso/src the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[derive(Debug)] pub(crate) struct Handle { pub(crate) conf: crate::Config, #[allow(dead_code)] // unused when a service does not provide any operations pub(crate) runtime_plugins: ::aws_smithy_ru
/// # async fn wrapper() -> ::std::result::Result<(), aws_sdk_sso::Error> { /// # let client: aws_sdk_sso::Client = unimplemented!(); /// use ::http::header::{HeaderName, HeaderValue}; /// /// let result = client.get_role_credentials() /// .customize() /// .mutate_request(|req| { /// // Add `x-example-header` with value /// req.headers_mut() /// .insert( /// HeaderName::from_static("x-example-header"), /// HeaderValue::from_static("1"), /// ); /// }) /// .send() /// .await; /// # }
802,069
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: list_bulk_deployments.rs path of file: ./repos/aws-sdk-rust/sdk/greengrass/src/operation the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `ListBulkDeployments`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct ListBulkDeployments; impl ListBulkDeployments { /// Creates a new `ListBulkDeployments` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins, input: crate::operation::list_bulk_deployments::ListBulkDeploymentsInput, ) -> ::std::result::Result< crate::operation::list_bulk_deployments::ListBulkDeploymentsOutput, ::a
fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> { let mut cfg = ::aws_smithy_types::config_bag::Layer::new("ListBulkDeployments"); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new( ListBulkDeploymentsRequestSerializer, )); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new( ListBulkDeploymentsResponseDeserializer, )); cfg.store_put(::aws_smithy_runtime_api::client::auth::AuthSchemeOptionResolverParams::new( ::aws_smithy_runtime_api::client::auth::static_resolver::StaticAuthSchemeOptionResolverParams::new(), )); cfg.store_put(::aws_smithy_runtime_api::client::orchestrator::Metadata::new( "ListBulkDeployments", "greengrass", )); let mut signing_options = ::aws_runtime::auth::SigningOptions::default(); signing_options.double_uri_encode = true; signing_options.content_sha256_header = false; signing_options.normalize_uri_path = true; signing_options.payload_override = None; cfg.store_put(::aws_runtime::auth::SigV4OperationSigningConfig { signing_options, ..::std::default::Default::default() }); ::std::option::Option::Some(cfg.freeze()) }
819,607
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: runtime.go path of file: ./repos/lotus/chain/vm the code of the file until where you have to start completion: package vm import ( "bytes" "context" "encoding/binary" "fmt" "os" "time" "github.com/ipfs/go-cid" ipldcbor "github.com/ipfs/go-ipld-cbor" "go.opencens
func (rt *Runtime) StateTransaction(obj cbor.Er, f func()) { if obj == nil { rt.Abortf(exitcode.SysErrorIllegalActor, "Must not pass nil to Transaction()") } act, err := rt.state.GetActor(rt.Receiver()) if err != nil { rt.Abortf(exitcode.SysErrorIllegalActor, "failed to get actor for Transaction: %s", err) } baseState := act.Head rt.StoreGet(baseState, obj) rt.allowInternal = false f() rt.allowInternal = true c := rt.StorePut(obj) err = rt.stateCommit(baseState, c) if err != nil { panic(fmt.Errorf("failed to commit state after transaction: %w", err)) } }
706,796
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: dbBase.m path of file: ./repos/netvlad/datasets the code of the file until where you have to start completion: % Base class for the dataset specification % % To make your own dataset (see dbPitts.m for an easy example): % 1. Inherit from dbBase % 2. In the constructor, set a short identifier of the dataset in db.name % 3. Save a matlab structure call
function negIDs= sampleNegs(db, utm, n) negIDs= []; while length(negIDs) < n negs= randsample(db.numImages, round(n*1.1)); isNeg= ~db.cp.isPos(utm, negs); nNewNeg= sum(isNeg); if nNewNeg>0 negIDs= unique([negIDs; negs(isNeg)]); end
408,639
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_ReplicateSecretToRegions.go path of file: ./repos/aws-sdk-go-v2/service/secretsmanager the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package secretsmanager import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
func newServiceMetadataMiddleware_opReplicateSecretToRegions(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "ReplicateSecretToRegions", } }
219,654
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: okcoin_test.go path of file: ./repos/gocryptotrader/exchanges/okcoin the code of the file until where you have to start completion: package okcoin import ( "context" "errors" "l
func TestGetTicker(t *testing.T) { t.Parallel() _, err := o.GetTicker(context.Background(), "USDT-USD") if err != nil { t.Error(err) } }
57,827
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: inventory_exchanger.rb path of file: ./repos/ekylibre/app/exchangers/synest the code of the file until where you have to start completion: # frozen_string_literal: true module Synest class InventoryExchanger < ActiveExchanger::Base category :stocks vendor :synest # Create or updates Synel Inventories def import male_adult_cow = ProductNatureVariant.import_from_nomenclature(:male_adult_cow) place = BuildingDivision.last # find_by_work_number("B07_D2") owner = Entity.where(of_company: false).reorder(:id).first rows = CSV.read(file, encoding: 'CP1252', col_sep: ';', headers: true) w.count = rows.size # FILE DESCRIPTION # COPAIP - 0 - Country # NUNATI - 1 - identification number # NUTRAV - 2 - work number # NOBOVI - 3 - Name # DANAIS - 4 - born_on # TYRASU - 5 - variety french_race_code # SEXBOV - 6 - sex # CAUSEN - 7 - incoming_cause # DATEEN - 8 - incoming_on # CAUSSO - 9 - outgoing_cause # DATESO - 10 - outgoing_on # COPAME - 15 - mother country # NUMERE - 16 - mother_identification_number # NOMERE - 17 - mother_name # TRAMER - 18 - mother french_race_code # COPAME - 19 - father country # NUMERE - 20 - father_identification_number # NOMERE - 21 - father_name # TRAMER - 22 - father french_race_code # find animals credentials in preferences identifier = Identifier.find_by(nature: :cattling_root_number) cattling_root_number = identifier ? identifier.value : '??????????' parents = { mother: {}, father: {} } rows.each do |row| born_on = (row[4].blank? ? nil : Date.parse(row[4])) incoming_on = (row[8].blank? ? nil : Date.parse(row[8])) outgoing_on = (row[10].blank? ? nil : Date.parse(row[10])) r = OpenStruct.new( work_number: row[2], identification_number: (row[1] ? row[1].to_s : nil), name: (row[3].blank? ? FFaker::Name.first_name + ' (MN)' : row[3].capitalize), mother_variety_code: (row[18].blank? ? nil : row[18]), father_variety_code: (row[22].blank? ? nil : row[22]), sex: (row[6].blank? ? nil : (row[6] == 'F' ? :female : :male)), born_on: born_on, born_at: (born_on ? born_on.to_datetime + 10.hours : nil), incoming_cause: row[7], incoming_on: incoming_on, incoming_at: (incoming_on ? incoming_on.to_datetime + 10.hours : nil), mother_identification_number: row[16], mother_work_number: (row[16] ? row[16][-4..-1] : nil), mother_name: (row[17].blank? ? FFaker::Name.first_name : row[17].capitalize), father_identification_number: row[20], father_work_number: (row[20] ? row[20][-4..-1] : nil), father_name: (row[21].blank? ? FFaker::Name.first_name : row[21].capitalize), outgoing_cause: row[9], outgoing_on: outgoing_on, outgoing_at: (outgoing_on ? outgoing_on.to_datetime + 10.hours : nil) ) # check if animal is present in DB if a
def import male_adult_cow = ProductNatureVariant.import_from_nomenclature(:male_adult_cow) place = BuildingDivision.last # find_by_work_number("B07_D2") owner = Entity.where(of_company: false).reorder(:id).first rows = CSV.read(file, encoding: 'CP1252', col_sep: ';', headers: true) w.count = rows.size # FILE DESCRIPTION # COPAIP - 0 - Country # NUNATI - 1 - identification number # NUTRAV - 2 - work number # NOBOVI - 3 - Name # DANAIS - 4 - born_on # TYRASU - 5 - variety french_race_code # SEXBOV - 6 - sex # CAUSEN - 7 - incoming_cause # DATEEN - 8 - incoming_on # CAUSSO - 9 - outgoing_cause # DATESO - 10 - outgoing_on # COPAME - 15 - mother country # NUMERE - 16 - mother_identification_number # NOMERE - 17 - mother_name # TRAMER - 18 - mother french_race_code # COPAME - 19 - father country # NUMERE - 20 - father_identification_number # NOMERE - 21 - father_name # TRAMER - 22 - father french_race_code # find animals credentials in preferences identifier = Identifier.find_by(nature: :cattling_root_number) cattling_root_number = identifier ? identifier.value : '??????????' parents = { mother: {}, father: {} } rows.each do |row| born_on = (row[4].blank? ? nil : Date.parse(row[4])) incoming_on = (row[8].blank? ? nil : Date.parse(row[8])) outgoing_on = (row[10].blank? ? nil : Date.parse(row[10])) r = OpenStruct.new( work_number: row[2], identification_number: (row[1] ? row[1].to_s : nil), name: (row[3].blank? ? FFaker::Name.first_name + ' (MN)' : row[3].capitalize), mother_variety_code: (row[18].blank? ? nil : row[18]), father_variety_code: (row[22].blank? ? nil : row[22]), sex: (row[6].blank? ? nil : (row[6] == 'F' ? :female : :male)), born_on: born_on, born_at: (born_on ? born_on.to_datetime + 10.hours : nil), incoming_cause: row[7], incoming_on: incoming_on, incoming_at: (incoming_on ? incoming_on.to_datetime + 10.hours : nil), mother_identification_number: row[16], mother_work_number: (row[16] ? row[16][-4..-1] : nil), mother_name: (row[17].blank? ? FFaker::Name.first_name : row[17].capitalize), father_identification_number: row[20], father_work_number: (row[20] ? row[20][-4..-1] : nil), father_name: (row[21].blank? ? FFaker::Name.first_name : row[21].capitalize), outgoing_cause: row[9], outgoing_on: outgoing_on, outgoing_at: (outgoing_on ? outgoing_on.to_datetime + 10.hours : nil) ) # check if animal is present in DB if animal = Animal.find_by(identification_number: r.identification_number) animal.initial_dead_at = r.outgoing_at animal.save! else group = nil # find a bos variety from corabo field in file item = Onoma::Variety.find_by(french_race_code: r.corabo) variety = (item ? item.name : :bos_taurus) variant = ProductNatureVariant.import_from_nomenclature(r.sex == :male ? :male_adult_cow : :female_adult_cow) animal = Animal.create!( variant: variant, name: r.name, variety: variety, identification_number: r.identification_number, work_number: r.work_number, initial_born_at: r.born_at, initial_dead_at: r.outgoing_at, initial_owner: owner, initial_population: 1.0, # initial_container: group.record.default_storage, default_storage: group ? group.record.default_storage : nil ) end if group animal.memberships.create!(group: group.record, started_at: arrived_on, nature: :interior) animal.memberships.create!(started_at: departed_on, nature: :exterior) if r.departed_on end
629,428
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_GetStream.go path of file: ./repos/aws-sdk-go-v2/service/ivs the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package ivs import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-
func newServiceMetadataMiddleware_opGetStream(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "GetStream", } }
235,571
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: get_blueprints.rs path of file: ./repos/aws-sdk-rust/sdk/lightsail/src/operation the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetBlueprints`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct GetBlueprints; impl GetBlueprints { /// Creates a new `Get
fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> { let mut cfg = ::aws_smithy_types::config_bag::Layer::new("GetBlueprints"); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new( GetBlueprintsRequestSerializer, )); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new( GetBlueprintsResponseDeserializer, )); cfg.store_put(::aws_smithy_runtime_api::client::auth::AuthSchemeOptionResolverParams::new( ::aws_smithy_runtime_api::client::auth::static_resolver::StaticAuthSchemeOptionResolverParams::new(), )); cfg.store_put(::aws_smithy_runtime_api::client::orchestrator::Metadata::new( "GetBlueprints", "lightsail", )); let mut signing_options = ::aws_runtime::auth::SigningOptions::default(); signing_options.double_uri_encode = true; signing_options.content_sha256_header = false; signing_options.normalize_uri_path = true; signing_options.payload_override = None; cfg.store_put(::aws_runtime::auth::SigV4OperationSigningConfig { signing_options, ..::std::default::Default::default() }); ::std::option::Option::Some(cfg.freeze()) }
814,271
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tmp.rb path of file: ./repos/truffleruby/spec/mspec/lib/mspec/helpers the code of the file until where you have to start completion: # Creates a temporary directory in the current working directory # for temporary files c
def tmp(name, uniquify = true) mkdir_p SPEC_TEMP_DIR unless Dir.exist? SPEC_TEMP_DIR if uniquify and !name.empty? slash = name.rindex "/" index = slash ? slash + 1 : 0 name.insert index, "#{SPEC_TEMP_UNIQUIFIER.succ!}-" end
176,813
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: field.go path of file: ./repos/protoreflect/desc/protoparse/ast the code of the file until where you have to start completion: package ast import "fmt" // FieldDeclNode is a node in the AST that defines a field. This includes // normal message fields as well as extensions. There are multiple types // of AST nodes
func (n *FieldNode) FieldLabel() Node { // proto3 fields and fields inside one-ofs will not have a label and we need // this check in order to return a nil node -- otherwise we'd return a // non-nil node that has a nil pointer value in it :/ if n.Label.KeywordNode == nil { return nil } return n.Label.KeywordNode }
47,865
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: lens.m path of file: ./repos/gkaModelEye/model/eye/species/+human the code of the file until where you have to start completion: function lens = lens( eye ) % Returns the lens sub-field of an eye model structure % % Syntax: % lens = human.lens( eye )
function lens = lens( eye ) % Returns the lens sub-field of an eye model structure % % Syntax: % lens = human.lens( eye ) % % Description: % A model of the crystalline lens is generated, expressed as a set of % quadric surfaces. The anterior and posterior surfaces of the lens are % modeled as one-half of a two-sheeted hyperboloid. % % The lens model begins with published values, which are subsequently % adjusted to allow for relatively equal accommodation across the retinal % surface in the emmetropic eye. % % The starting point for the radii of the surfaces, and their depend
190,360
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: cli.rs path of file: ./repos/command-line-rust/10_commr/tests the code of the file until where you have to start completion: use assert_cmd::Command; use predicates::prelude::*; use rand::
fn dies_no_args() -> TestResult { Command::cargo_bin(PRG)? .assert() .failure() .stderr(predicate::str::contains("USAGE")); Ok(()) }
648,087
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: output_selection.rs path of file: ./repos/ethers-rs/ethers-solc/src/artifacts the code of the file until where you have to start completion: //! bindings for standard json output selection
pub fn complete_output_selection() -> Self { BTreeMap::from([( "*".to_string(), BTreeMap::from([ ("*".to_string(), vec!["*".to_string()]), ("".to_string(), vec!["*".to_string()]), ]), )]) .into() }
78,859
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: log.go path of file: ./repos/rancher/pkg/clusterprovisioninglogger the code of the file until where you have to start completion: package clusterprovisioninglogger import ( "bytes"
func (p *logger) saveMessage() { p.bufferLock.Lock() defer p.bufferLock.Unlock() log := p.buffer.String() if log == "" { return } cm, err := p.ConfigMaps.GetNamespaced(p.Cluster.Name, configMapName, v12.GetOptions{}) if apierrors.IsNotFound(err) { _, err := p.ConfigMaps.Create(&corev1.ConfigMap{ ObjectMeta: v12.ObjectMeta{ Name: configMapName, Namespace: p.Cluster.Name, }, Data: map[string]string{ "log": log, }, }) logrus.Errorf("Failed to save provisioning log for %s: %v", configMapName, err) } else if err != nil { logrus.Errorf("Failed to get provisioning log for %s: %v", configMapName, err) } else if log != cm.Data["log"] { if cm.Data == nil { cm.Data = map[string]string{} } cm.Data["log"] = log _, err := p.ConfigMaps.Update(cm) if err != nil { logrus.Errorf("Failed to update provisioning log for %s: %v", configMapName, err) } } }
680,944
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: MedianIgnoringZeros.m path of file: ./repos/CBIG/external_packages/SD/SDv1.5.1-svn593/AnalysisTools the code of the file until where you have to start completion: % Contact [email protected] or [email protected] for bugs or questions % %=====
function medVec = MedianIgnoringZeros(statMat, dim) % MedianIgnoringZeros(statMat, dim) % Takes in a matrix and takes median along dimension dim. % ignores zeros... if(dim == 1) statMat = statMat'; end
618,247
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_CreateLBCookieStickinessPolicy.go path of file: ./repos/aws-sdk-go-v2/service/elasticloadbalancing the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package elasticloadbalancing import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http"
func (c *Client) CreateLBCookieStickinessPolicy(ctx context.Context, params *CreateLBCookieStickinessPolicyInput, optFns ...func(*Options)) (*CreateLBCookieStickinessPolicyOutput, error) { if params == nil { params = &CreateLBCookieStickinessPolicyInput{} } result, metadata, err := c.invokeOperation(ctx, "CreateLBCookieStickinessPolicy", params, optFns, c.addOperationCreateLBCookieStickinessPolicyMiddlewares) if err != nil { return nil, err } out := result.(*CreateLBCookieStickinessPolicyOutput) out.ResultMetadata = metadata return out, nil }
216,661
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: name_table_test.go path of file: ./repos/istio/pkg/dns/server the code of the file until where you have to start completion: // Copyright Istio 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 cop
func makeInstances(proxy *model.Proxy, svc *model.Service, servicePort int, targetPort int) []*model.IstioEndpoint { ret := make([]*model.IstioEndpoint, 0) for _, p := range svc.Ports { if p.Port != servicePort { continue } ret = append(ret, &model.IstioEndpoint{ Address: proxy.IPAddresses[0], ServicePortName: p.Name, EndpointPort: uint32(targetPort), }) } return ret }
593,212
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: server_test.go path of file: ./repos/jupiter/pkg/server/xfasthttp the code of the file until where you have to start completion: // Copyright 2022 Douyu // // Licensed under the Apache
func Test_Server(t *testing.T) { c := DefaultConfig() c.Port = 0 s := c.MustBuild() go func() { s.Serve() }() time.Sleep(time.Second) assert.True(t, s.Healthz()) assert.NotNil(t, s.Info()) s.Stop() }
598,041
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: shell.go path of file: ./repos/rancher/pkg/api/steve/clusters the code of the file until where you have to start completion: package clusters import ( "context" "net/http" "net/http/httputil" "strings" "time" "github.com/rancher/rancher/pkg/settings" "github.com/rancher/steve/pkg/podimpersonation" "github.com/rancher/steve/pkg/stores/proxy" "githu
func (s *shell) proxyRequest(rw http.ResponseWriter, req *http.Request, pod *v1.Pod, client kubernetes.Interface) { attachURL := client.CoreV1().RESTClient(). Get(). Namespace(pod.Namespace). Resource("pods"). Name(pod.Name). SubResource("exec"). VersionedParams(&v1.PodExecOptions{ Stdin: true, Stdout: true, Stderr: true, TTY: true, Container: "shell", Command: []string{"welcome"}, }, scheme.ParameterCodec).URL() httpClient := client.CoreV1().RESTClient().(*rest.RESTClient).Client p := httputil.ReverseProxy{ Director: func(req *http.Request) { req.URL = attachURL req.Host = attachURL.Host for key := range req.Header { if strings.HasPrefix(key, "Impersonate-Extra-") { delete(req.Header, key) } } delete(req.Header, "Impersonate-Group") delete(req.Header, "Impersonate-User") delete(req.Header, "Authorization") delete(req.Header, "Cookie") }, Transport: httpClient.Transport, FlushInterval: time.Millisecond * 100, } p.ServeHTTP(rw, req) }
681,270
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: DAISY.m path of file: ./repos/mexopencv/opencv_contrib/+cv the code of the file until where you have to start completion: classdef DAISY < handle %DAISY Class implementing DAISY descriptor % % As described in [Tola10]. % % ## References % [Tola10]: % > E. Tola, V
function dtype = descriptorType(this) %DESCRIPTORTYPE Returns the descriptor type % % dtype = obj.descriptorType() % % ## Output % * __dtype__ Descriptor type, one of numeric MATLAB class names. % % Always `single` for DAISY. % % See also: cv.DAISY.descriptorSize, cv.DAISY.compute % dtype = DAISY_(this.id, 'descriptorType'); end
435,750
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: builders.rs path of file: ./repos/aws-sdk-rust/sdk/quicksight/src/operation/describe_refresh_schedule the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
762,475
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: endpoint.go path of file: ./repos/kubernetes/pkg/kubelet/cm/devicemanager the code of the file until where you have to start completion: /* Copyright 2017 The Kubernetes 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 i
func (e *endpointImpl) getPreferredAllocation(available, mustInclude []string, size int) (*pluginapi.PreferredAllocationResponse, error) { if e.isStopped() { return nil, fmt.Errorf(errEndpointStopped, e) } return e.api.GetPreferredAllocation(context.Background(), &pluginapi.PreferredAllocationRequest{ ContainerRequests: []*pluginapi.ContainerPreferredAllocationRequest{ { AvailableDeviceIDs: available, MustIncludeDeviceIDs: mustInclude, AllocationSize: int32(size), }, }, }) }
360,370
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: match_platform.rb path of file: ./repos/truffleruby/lib/mri/bundler the code of the file until where you have to start completion: # frozen_string_literal: true require_relative "gem_helpers" module Bundler module MatchPlatform include GemHelpers def match_platform(p) MatchPlatform.platforms_match?(platform, p) end def self.p
def self.platforms_match?(gemspec_platform, local_platform) return true if gemspec_platform.nil? return true if Gem::Platform::RUBY == gemspec_platform return true if local_platform == gemspec_platform gemspec_platform = Gem::Platform.new(gemspec_platform) return true if gemspec_platform === local_platform false end
176,558
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 20130522193615_rename_search_tables.rb path of file: ./repos/discourse/db/migrate the code of the file until where you have to start completion: # frozen_string_literal: true class RenameSearchTables < ActiveRecord::Migration[4.2] def up rename_table :users_search, :user_search_data rename_column :us
def down rename_table :user_search_data, :users_search rename_column :users_search, :user_id, :id rename_table :category_search_data, :categories_search rename_column :categories_search, :category_id, :id rename_table :post_search_data, :posts_search rename_column :posts_search, :post_id, :id end
615,901
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: context.rs path of file: ./repos/c2rust/c2rust-refactor/src the code of the file until where you have to start completion: use std::collections::{HashMap, HashSet}; use std::ops::Deref; use rustc::hir::def::{DefKind, Namespace, Res}; use rustc
pub fn try_resolve_ty(&self, t: &ast::Ty) -> Option<DefId> { if let Some(def) = self.try_resolve_ty_hir(t) { return def.opt_def_id(); } if self.has_ty_ctxt() { if let ast::TyKind::Path(..) = t.kind { if let Some(def) = self.try_resolve_node_type_dep(t.id) { return def.opt_def_id(); } } } None }
34,923
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: logging.rb path of file: ./repos/metasploit-framework/lib/msf/base the code of the file until where you have to start completion: # -*- coding: binary -*- require 'rex' module Msf # This module provides an initialization interface for logging. class Logging #Is logging initialized #@private @@initialized = false #Is session logging enabled #@private @@session_logging =
def self.start_session_log(session) if (log_source_registered?(session.log_source) == false) f = Rex::Logging::Sinks::TimestampColorlessFlatfile.new( Msf::Config.session_log_directory + File::SEPARATOR + "#{session.log_file_name}.log") register_log_source(session.log_source, f) rlog("\n[*] Logging started: #{Time.now}\n\n", session.log_source) end
738,906
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: record.go path of file: ./repos/minio/internal/s3select/csv the code of the file until where you have to start completion: // Copyright (c) 2015-2021 MinIO, Inc. // // This file is part of MinIO Object Storage stack // // This program is free software: you can redistribute it and/or modify // it under th
func (r *Record) WriteJSON(writer io.Writer) error { var kvs jstream.KVS = make([]jstream.KV, 0, len(r.columnNames)) for i, cn := range r.columnNames { if i < len(r.csvRecord) { kvs = append(kvs, jstream.KV{Key: cn, Value: r.csvRecord[i]}) } } return json.NewEncoder(writer).Encode(kvs) }
7,534
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: watcher.rs path of file: ./repos/gitui/src the code of the file until where you have to start completion: use anyhow::Result; use crossbeam_channel::{unbounded, Sender}; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; use notify_debouncer_mini::{new_debouncer, DebounceEventResult}; use scopetime::scope_time; use std::{path::Path, thread, time::Duration}; pub struct RepoWatcher { receiver: crossbeam_channel::Re
pub fn new(workdir: &str) -> Self { log::trace!( "recommended watcher: {:?}", RecommendedWatcher::kind() ); let (tx, rx) = std::sync::mpsc::channel(); let workdir = workdir.to_string(); thread::spawn(move || { let timeout = Duration::from_secs(2); create_watcher(timeout, tx, &workdir); }); let (out_tx, out_rx) = unbounded(); thread::spawn(move || { if let Err(e) = Self::forwarder(&rx, &out_tx) { //maybe we need to restart the forwarder now? log::error!("notify receive error: {}", e); } }); Self { receiver: out_rx } }
97,568
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: lib.go path of file: ./repos/poseidon/builder/docformat/src/github.com/golang/protobuf/proto the code of the file until where you have to start completion: // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors.
func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data) if err != nil { return err } *x = FOO(value) return nil }
732,929
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: uuid.rb path of file: ./repos/metasploit-framework/lib/msf/core/payload the code of the file until where you have to start completion: # -*- codin
def to_h { puid: self.puid, arch: self.arch, platform: self.platform, timestamp: self.timestamp, xor1: self.xor1, xor2: self.xor2 } end
738,775
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: syscall_unix.go path of file: ./repos/devspace/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris package unix import ( "bytes" "sort" "sync" "syscall" "unsafe" ) var ( Stdin = 0 Stdout = 1 Stderr = 2 ) // Do the interface allocations only once for comm
func RecvmsgBuffers(fd int, buffers [][]byte, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { iov := make([]Iovec, len(buffers)) for i := range buffers { if len(buffers[i]) > 0 { iov[i].Base = &buffers[i][0] iov[i].SetLen(len(buffers[i])) } else { iov[i].Base = (*byte)(unsafe.Pointer(&_zero)) } } var rsa RawSockaddrAny n, oobn, recvflags, err = recvmsgRaw(fd, iov, oob, flags, &rsa) if err == nil && rsa.Addr.Family != AF_UNSPEC { from, err = anyToSockaddr(fd, &rsa) } return }
469,223
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _deployment_status.rs path of file: ./repos/aws-sdk-rust/sdk/apigatewayv2/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NO
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self { DeploymentStatus::Deployed => write!(f, "DEPLOYED"), DeploymentStatus::Failed => write!(f, "FAILED"), DeploymentStatus::Pending => write!(f, "PENDING"), DeploymentStatus::Unknown(value) => write!(f, "{}", value), } }
780,574
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: customers_controller.rb path of file: ./repos/openfoodnetwork/app/controllers/api/v0 the code of the file until where you have to start completion: # frozen_string_literal: true module Api module V0 class CustomersController < Api::V0::BaseCont
def update @customer = Customer.find(params[:id]) authorize! :update, @customer client_secret = RecurringPayments.setup_for(@customer) if params[:customer][:allow_charges] if @customer.update(customer_params) add_recurring_payment_info(client_secret) render json: @customer, serializer: CustomerSerializer, status: :ok else invalid_resource!(@customer) end
303,568
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: listen.rs path of file: ./repos/linkerd2-proxy/linkerd/proxy/transport/src the code of the file until where you have to start completion: use crate::{addrs::*, Keepalive}; use futures::prelude::*; use linkerd_error::Result; use linkerd_io as io; use linkerd_stack::Param; use std::{fmt, pin::Pin}; use thiserror::Error; use tokio::net::TcpStream; use tokio_stream::wrappers::TcpListenerStream; /// Binds a listener, producing a stream of incoming connections. /// /// Typically, this represents binding a TCP socket. However, it may also be an /// st
fn bind(self, params: &T) -> Result<Bound<Self::Incoming>> { let listen = { let ListenAddr(addr) = params.param(); let l = std::net::TcpListener::bind(addr)?; // Ensure that O_NONBLOCK is set on the socket before using it with Tokio. l.set_nonblocking(true)?; tokio::net::TcpListener::from_std(l).expect("listener must be valid") }; let server = Local(ServerAddr(listen.local_addr()?)); let Keepalive(keepalive) = params.param(); let accept = TcpListenerStream::new(listen).map(move |res| { let tcp = res.map_err(AcceptError)?; super::set_nodelay_or_warn(&tcp); let tcp = super::set_keepalive_or_warn(tcp, keepalive).map_err(KeepaliveError)?; let client = Remote(ClientAddr(tcp.peer_addr().map_err(PeerAddrError)?)); Ok((Addrs { server, client }, tcp)) }); Ok((server, Box::pin(accept))) }
524,417
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: engine_key.go path of file: ./repos/cockroach/pkg/storage the code of the file until where you have to start completion: // Copyright 2020 The Cockroach Authors. // // Use of this software is gover
func DecodeEngineKey(b []byte) (key EngineKey, ok bool) { if len(b) == 0 { return EngineKey{}, false } // Last byte is the version length + 1 when there is a version, // else it is 0. versionLen := int(b[len(b)-1]) // keyPartEnd points to the sentinel byte. keyPartEnd := len(b) - 1 - versionLen if keyPartEnd < 0 || b[keyPartEnd] != 0x00 { return EngineKey{}, false } // Key excludes the sentinel byte. key.Key = b[:keyPartEnd] if versionLen > 0 { // Version consists of the bytes after the sentinel and before the length. key.Version = b[keyPartEnd+1 : len(b)-1] } return key, true }
702,190
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: elastic_test.go path of file: ./repos/gnomock/internal/gnomockd the code of the file until where you have to start completion: package gnomockd_test import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "os" "testing" "github.com/elastic/go-elasticsearch/v8" "github.com/orlangure/gnomock" "github.com/orlangure/gnomock/internal/gnomockd" _ "github.com/orlangure/gnomock/preset/elastic" "github.com/stretchr/testify/require" ) func TestElastic(t *testing.T) { t.Parallel() h := gnomockd.Handler() bs, err := os.ReadFile("./testdata/elastic.json") require.NoError(t, err) buf := bytes.NewBuffer(bs) w, r
func TestElastic(t *testing.T) { t.Parallel() h := gnomockd.Handler() bs, err := os.ReadFile("./testdata/elastic.json") require.NoError(t, err) buf := bytes.NewBuffer(bs) w, r := httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/start/elastic", buf) h.ServeHTTP(w, r) res := w.Result() defer func() { require.NoError(t, res.Body.Close()) }() body, err := io.ReadAll(res.Body) require.NoError(t, err) require.Equalf(t, http.StatusOK, res.StatusCode, string(body)) var c *gnomock.Container require.NoError(t, json.Unmarshal(body, &c)) cfg := elasticsearch.Config{ Addresses: []string{fmt.Sprintf("http://%s", c.DefaultAddress())}, DisableRetry: true, } client, err := elasticsearch.NewClient(cfg) require.NoError(t, err) searchResult, err := client.Search( client.Search.WithIndex("titles"), client.Search.WithQuery("gnomock"), ) require.NoError(t, err) require.False(t, searchResult.IsError(), searchResult.String()) var out struct { Hits struct { Total struct { Value int `json:"value"` } `json:"total"` } `json:"hits"` } require.NoError(t, json.NewDecoder(searchResult.Body).Decode(&out)) require.NoError(t, searchResult.Body.Close()) require.Equal(t, 1, out.Hits.Total.Value) bs, err = json.Marshal(c) require.NoError(t, err) buf = bytes.NewBuffer(bs) w, r = httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/stop", buf) h.ServeHTTP(w, r) res = w.Result() require.Equal(t, http.StatusOK, res.StatusCode) }
341,302
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: object_filter.rb path of file: ./repos/active_interaction/lib/active_interaction/filters the code of the file until where you have to start completion: # frozen_string_literal:
def converter(value) return value unless (converter = options[:converter]) case converter when Proc converter.call(value) when Symbol klass.public_send(converter, value) else raise InvalidConverterError, "#{converter.inspect} is not a valid converter" end
438,367
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: file_results.rs path of file: ./repos/ruffle/scanner/src the code of the file until where you have to start completion: //! File results type. //! //! The `FileResults` type in this module is used to report results of a scan. use serde::de::{Error as DesError, Unexpected, Visitor}; use serde::ser::Error as SerError; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::fmt::Write; #[derive(Serialize, Deserialize, Debug,
pub fn new(name: &str) -> Self { FileResults { name: name.to_string(), hash: vec![], progress: Step::Start, testing_time: 0, compressed_len: None, uncompressed_len: None, error: None, compression: None, version: None, stage_size: None, frame_rate: None, num_frames: None, use_direct_blit: None, use_gpu: None, use_network_sandbox: None, vm_type: None, } }
109,150
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: json_schema_test.go path of file: ./repos/confluent-kafka-go/schemaregistry/serde/jsonschema the code of the file until where you have to start completion: /** * Copyright 2022 Confluent Inc. * * Licensed under the Apache License, Version 2.0 (the "License"
func TestFailingJSONSchemaValidationWithSimple(t *testing.T) { serde.MaybeFail = serde.InitFailFunc(t) var err error conf := schemaregistry.NewConfig("mock://") client, err := schemaregistry.NewClient(conf) serde.MaybeFail("Schema Registry configuration", err) serConfig := NewSerializerConfig() serConfig.EnableValidation = true // We don't want to risk registering one instead of using the already registered one serConfig.AutoRegisterSchemas = false serConfig.UseLatestVersion = true ser, err := NewSerializer(client, serde.ValueSerde, serConfig) serde.MaybeFail("Serializer configuration", err) obj := JSONDemoSchema{} jschema := jsonschema.Reflect(obj) raw, err := json.Marshal(jschema) serde.MaybeFail("Schema marshalling", err) info := schemaregistry.SchemaInfo{ Schema: string(raw), SchemaType: "JSON", } id, err := client.Register("topic1-value", info, false) serde.MaybeFail("Schema registration", err) if id <= 0 { t.Errorf("Expected valid schema id, found %d", id) } _, err = ser.Serialize("topic1", &obj) if err != nil { t.Errorf("Expected no validation error, found %s", err) } diffObj := DifferentJSONDemoSchema{} _, err = ser.Serialize("topic1", &diffObj) if err == nil || !strings.Contains(err.Error(), "jsonschema") { t.Errorf("Expected validation error, found %s", err) } }
407,290
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: encoding_test.go path of file: ./repos/kin-openapi/openapi3 the code of the file until where you have to start completion: package openapi3 import ( "context" "encoding/json" "testing" "github.com/stretchr/testify/require" ) func TestEncodingJSON(t *testing.T) { t.Log("Marshal *openapi3.Encoding to JSON") data, err := json.Marshal(encoding()) require.NoError(t, err) require.NotEmpty(t, data) t.Log("Unmarshal *openapi3.Encoding from JSON") docA := &Encoding{} err = json.Unmarshal(encodingJSON, &docA) require.NoError(t, err) require.NotEmpty(t, docA) t.Log("Validate *openapi3.Encoding") err = docA.Validate(context.Background()) require.NoError(t, err) t.Log("Ensure representations match") dataA, err := json.Marshal(docA) require.NoError(t, err) require.JSONEq(t, string(data), string(encodingJSON)) require.JSONEq(t, string(data), string(dataA)) } var encodingJSON = []byte(` { "contentType": "application/json", "headers": { "someHeader": {} }, "st
func TestEncodingSerializationMethod(t *testing.T) { testCases := []struct { name string enc *Encoding want *SerializationMethod }{ { name: "default", want: &SerializationMethod{Style: SerializationForm, Explode: true}, }, { name: "encoding with style", enc: &Encoding{Style: SerializationSpaceDelimited}, want: &SerializationMethod{Style: SerializationSpaceDelimited, Explode: true}, }, { name: "encoding with explode", enc: &Encoding{Explode: BoolPtr(true)}, want: &SerializationMethod{Style: SerializationForm, Explode: true}, }, { name: "encoding with no explode", enc: &Encoding{Explode: BoolPtr(false)}, want: &SerializationMethod{Style: SerializationForm, Explode: false}, }, { name: "encoding with style and explode ", enc: &Encoding{Style: SerializationSpaceDelimited, Explode: BoolPtr(false)}, want: &SerializationMethod{Style: SerializationSpaceDelimited, Explode: false}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { got := tc.enc.SerializationMethod() require.EqualValues(t, got, tc.want, "got %#v, want %#v", got, tc.want) }) } }
463,951
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: BulkEntryCmass1.m path of file: ./repos/NASTRAN_CoFE/nastran_cofe/nastran_input_processors the code of the file until where you have to start completion: % Class for CMASS1 entries % Anthony Ricciar
function obj = BulkEntryCmass1(entryFields) % Construct using entry field data input as cell array of char obj.eid = castInputField('CMASS1','EID',entryFields{2},'uint32',NaN,1); obj.pid = castInputField('CMASS1','PID',entryFields{3},'uint32',NaN,1); obj.g1 = castInputField('CMASS1','G1',entryFields{4},'uint32',NaN,1); obj.c1 = castInputField('CMASS1','C1',entryFields{5},'uint8',NaN,1,6); obj.g2 = castInputField('CMASS1','G2',entryFields{6},'uint32',[],1); obj.c2 = castInputField('CMASS1','C2',entryFields{7},'uint8',[],1,6); end
628,117
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: blockwriter.go path of file: ./repos/tidb-operator/tests/pkg/blockwriter the code of the file until where you have to start completion: // Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package blockwriter import ( "context" "database/sql" "fmt" "math/rand" "strings" "sync" "sync/atomic" "time" "k8s.io/apimachinery/pkg/util/wait" "github.com/pingcap/tidb-operator/tests/pkg/util" "github.com/pingcap/tidb-operator/tests/third_party/k8s/log" ) const ( queryChanSize int = 100 ) // BlockWriterCase is
func (c *BlockWriterCase) initialize(db *sql.DB) error { log.Logf("[%s] [%s] start to init...", c, c.ClusterName) defer func() { atomic.StoreUint32(&c.isInit, 1) log.Logf("[%s] [%s] init end...", c, c.ClusterName) }() for i := 0; i < c.cfg.TableNum; i++ { var s string if i > 0 { s = fmt.Sprintf("%d", i) } tmt := fmt.Sprintf("CREATE TABLE IF NOT EXISTS block_writer%s %s", s, ` ( id BIGINT NOT NULL AUTO_INCREMENT, raw_bytes BLOB NOT NULL, PRIMARY KEY (id) )`) err := wait.PollImmediate(5*time.Second, 30*time.Second, func() (bool, error) { _, err := db.Exec(tmt) if err != nil { log.Logf("[%s] exec sql [%s] failed, err: %v, retry...", c, tmt, err) return false, nil } return true, nil }) if err != nil { log.Logf("ERROR: [%s] exec sql [%s] failed, err: %v", c, tmt, err) return err } } return nil }
340,360
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: snapshot_test.go path of file: ./repos/aws-sdk-go-v2/service/networkfirewall the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. //go:build snapshot package networkfirewall import ( "context" "errors" "fmt" "github.com/aws/smithy-go/middleware" "io" "io/fs" "os" "testing" ) const ssprefix = "snapshot" type snapshotOK struct{} func (snapshotOK) Error() string
func TestUpdateSnapshot_CreateFirewallPolicy(t *testing.T) { svc := New(Options{}) _, err := svc.CreateFirewallPolicy(context.Background(), nil, func(o *Options) { o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { return updateSnapshot(stack, "CreateFirewallPolicy") }) }) if _, ok := err.(snapshotOK); !ok && err != nil { t.Fatal(err) } }
232,399
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: builders.rs path of file: ./repos/aws-sdk-rust/sdk/resiliencehub/src/operation/list_app_component_compliances the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::list_app_
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
817,603
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _webhook_filter.rs path of file: ./repos/aws-sdk-rust/sdk/codebuild/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>A filter used to determine which webhooks trigger a build.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct WebhookFilter { /// <p>The type of webhook filter. There are six webhook filter types: <code>E
pub fn build(self) -> ::std::result::Result<crate::types::WebhookFilter, ::aws_smithy_types::error::operation::BuildError> { ::std::result::Result::Ok(crate::types::WebhookFilter { r#type: self.r#type.ok_or_else(|| { ::aws_smithy_types::error::operation::BuildError::missing_field( "r#type", "r#type was not specified but it is required when building WebhookFilter", ) })?, pattern: self.pattern.ok_or_else(|| { ::aws_smithy_types::error::operation::BuildError::missing_field( "pattern", "pattern was not specified but it is required when building WebhookFilter", ) })?, exclude_matched_pattern: self.exclude_matched_pattern, }) }
816,738
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: instance.rs path of file: ./repos/burn/crates/burn-core/src/nn/norm the code of the file until where you have to start completion: use crate as burn; use crate::config::Config; us
fn to_group_norm(&self) -> GroupNormConfig { GroupNormConfig { // Group norm is equivalent to instance norm, when the number of groups is // equal to the number of channels. num_groups: self.num_channels, num_channels: self.num_channels, epsilon: self.epsilon, affine: self.affine, } }
4,294
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.go path of file: ./repos/nutsdb/examples/sortedSet the code of the file until where you have to start completion: package main import ( "fmt" "io/ioutil" "log" "os" "github.com/nutsdb/nutsdb" ) var ( db *nutsdb.DB err error ) func init() { fileDir := "/tmp/nutsdb_example" files, _ := ioutil.ReadDir(fileDir) for _, f := range files { name := f.Name() if name != "" { err := os.RemoveAll(fileDir + "/" + name) if err != nil { panic(err) } } } db, _ = nutsdb.Open( nutsdb.DefaultOptions, nutsdb.WithDir(fileDir), nutsdb.WithSegmentSize(1024*1024), // 1MB )
func testZRank() { if err := db.View( func(tx *nutsdb.Tx) error { bucket := "myZSet1" key := []byte("key1") rank, err := tx.ZRank(bucket, key, []byte("val1")) if err != nil { return err } fmt.Println("val1 ZRank :", rank) return nil }); err != nil { log.Fatal(err) } if err := db.View( func(tx *nutsdb.Tx) error { bucket := "myZSet1" key := []byte("key1") rank, err := tx.ZRank(bucket, key, []byte("val2")) if err != nil { return err } fmt.Println("val2 ZRank :", rank) return nil }); err != nil { log.Fatal(err) } if err := db.View( func(tx *nutsdb.Tx) error { bucket := "myZSet1" key := []byte("key1") rank, err := tx.ZRank(bucket, key, []byte("val3")) if err != nil { return err } fmt.Println("val3 ZRank :", rank) return nil }); err != nil { log.Fatal(err) } }
86,325
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tl_dialog_peer_gen.go path of file: ./repos/td/tg the code of the file until where you have to start completion: // Code generated by gotdgen, DO NOT EDIT. package tg
func (d *DialogPeer) EncodeBare(b *bin.Buffer) error { if d == nil { return fmt.Errorf("can't encode dialogPeer#e56dbf05 as nil") } if d.Peer == nil { return fmt.Errorf("unable to encode dialogPeer#e56dbf05: field peer is nil") } if err := d.Peer.Encode(b); err != nil { return fmt.Errorf("unable to encode dialogPeer#e56dbf05: field peer: %w", err) } return nil }
481,558
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: flags.go path of file: ./repos/kubeedge/vendor/k8s.io/kubernetes/pkg/kubelet/config the code of the file until where you have to start completion: /* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version
func (s *ContainerRuntimeOptions) AddFlags(fs *pflag.FlagSet) { // General settings. fs.StringVar(&s.RuntimeCgroups, "runtime-cgroups", s.RuntimeCgroups, "Optional absolute name of cgroups to create and run the runtime in.") fs.StringVar(&s.PodSandboxImage, "pod-infra-container-image", s.PodSandboxImage, fmt.Sprintf("Specified image will not be pruned by the image garbage collector. CRI implementations have their own configuration to set this image.")) fs.MarkDeprecated("pod-infra-container-image", "will be removed in a future release. Image garbage collector will get sandbox image information from CRI.") // Image credential provider settings. fs.StringVar(&s.ImageCredentialProviderConfigFile, "image-credential-provider-config", s.ImageCredentialProviderConfigFile, "The path to the credential provider plugin config file.") fs.StringVar(&s.ImageCredentialProviderBinDir, "image-credential-provider-bin-dir", s.ImageCredentialProviderBinDir, "The path to the directory where credential provider plugin binaries are located.") }
417,679
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: hmmViterbi.m path of file: ./repos/PRMLT/chapter13/HMM the code of the file until where you have to start completion: function [z, llh] = hmmViterbi(model, x) % Viterbi algorithm (calculated in log scale to improve numerical stability). % Input: % x: 1 x n integer vector which is the sequence of observations % model: model structure which contains % model.s: k x 1 start probability vector % model.A: k x k transition matrix % model.E: k x d emission matrix % Output: % z: 1 x n latent state % llh: loglikelihood % Written by Mo Chen ([email protected]). n = size(x,2); X = sparse(x,1:n,1); s = log(model.s); A = log(model.A); M = log(model.E*X); k = numel(s); Z = zeros(k,n); Z(:,1) = 1:k; v = s(:)+M(:,1);
function [z, llh] = hmmViterbi(model, x) % Viterbi algorithm (calculated in log scale to improve numerical stability). % Input: % x: 1 x n integer vector which is the sequence of observations % model: model structure which contains % model.s: k x 1 start probability vector % model.A: k x k transition matrix % model.E: k x d emission matrix % Output: % z: 1 x n latent state % llh: loglikelihood % Written by Mo Chen ([email protected]). n = size(x,2); X = sparse(x,1:n,1); s = log(model.s); A = log(model.A); M = log(model.E*X); k = numel(s); Z = zeros(k,n); Z(:,1) = 1:k; v = s(:)+M(:,1); for t = 2:n [v,idx] = max(bsxfun(@plus,A,v),[],1); % 13.68 v = v(:)+M(:,t); Z = Z(idx,:); Z(:,t) = 1:k; end
321,672
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: environment.go path of file: ./repos/vault/sdk/helper/testcluster/docker the code of the file until where you have to start completion: // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 package docker import ( "bufio" "bytes" "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "cr
func (n *DockerClusterNode) newAPIClient() (*api.Client, error) { config, err := n.apiConfig() if err != nil { return nil, err } client, err := api.NewClient(config) if err != nil { return nil, err } client.SetToken(n.Cluster.GetRootToken()) return client, nil }
314,261
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: preview.go path of file: ./repos/porter/internal/integrations/ci/actions the code of the file until where you have to start completion: package actions import ( "context" "fmt" "net/http" "strings" "github.com/google/go-github/v41/github" "gopkg.in/yaml.v2" ) type EnvOpts struct { Client *github.Client ServerURL string PorterToken string GitRepoOwner, GitRepoName string EnvironmentName string InstanceName string ProjectID, ClusterID, GitInstallationID uint } func SetupEnv(opts *EnvOpts) error { // make a best-effort to create a Github environment. this is a non-fatal operation, // as the environments API is not enabled for private repositories that don't have // github enterprise. _, resp, err := opts.Client.Repositories.GetEnvironment( context.Background(), opts.Git
func getPreviewApplyActionYAML(opts *EnvOpts) ([]byte, error) { gaSteps := []GithubActionYAMLStep{ getCheckoutCodeStep(), getCreatePreviewEnvStep( opts.ServerURL, getPreviewEnvSecretName(opts.ProjectID, opts.ClusterID, opts.InstanceName), opts.ProjectID, opts.ClusterID, opts.GitInstallationID, opts.GitRepoOwner, opts.GitRepoName, "v0.2.1", ), } actionYAML := GithubActionYAML{ On: map[string]interface{}{ "workflow_dispatch": map[string]interface{}{ "inputs": map[string]interface{}{ "pr_number": map[string]interface{}{ "description": "Pull request number", "type": "string", "required": true, }, "pr_title": map[string]interface{}{ "description": "Pull request title", "type": "string", "required": true, }, "pr_branch_from": map[string]interface{}{ "description": "Pull request head branch", "type": "string", "required": true, }, "pr_branch_into": map[string]interface{}{ "description": "Pull request base branch", "type": "string", "required": true, }, }, }, }, Name: "Porter Preview Environment", Jobs: map[string]GithubActionYAMLJob{ "porter-preview": { RunsOn: "ubuntu-latest", Concurrency: map[string]string{ "group": "${{ github.workflow }}-${{ github.event.inputs.pr_number }}", }, Steps: gaSteps, }, }, } return yaml.Marshal(actionYAML) }
521,698
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: matcher_test.go path of file: ./repos/grype/grype/matcher/msrc the code of the file until where you have to start completion: package msrc import ( "fmt" "testing" "github.com/google/uuid" "github.com/stretchr/testify/assert
func (s *mockStore) SearchForVulnerabilities(namespace, name string) ([]grypeDB.Vulnerability, error) { namespaceMap := s.backend[namespace] if namespaceMap == nil { return nil, nil } return namespaceMap[name], nil }
118,135
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: vcs.go path of file: ./repos/glide/repo the code of the file until where you have to start completion: package repo import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "runtime" "sort" "strings" cp "github.com/Masterminds/glide/cache" "github.com/Masterminds/glide/
func findCurrentBranch(repo v.Repo) string { msg.Debug("Attempting to find current branch for %s", repo.Remote()) // Svn and Bzr don't have default branches. if repo.Vcs() == v.Svn || repo.Vcs() == v.Bzr { return "" } if repo.Vcs() == v.Git || repo.Vcs() == v.Hg { ver, err := repo.Current() if err != nil { msg.Debug("Unable to find current branch for %s, error: %s", repo.Remote(), err) return "" } return ver } return "" }
676,366
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: cve.rs path of file: ./repos/kani/tests/cargo-kani/vecdeque-cve/src the code of the file until where you have to start completion: // SPDX-License-Identifier: Apache-2.0 OR MIT // // Modifications Copyright Kani Contributors // See GitHub history for details. //! This is a modified version of rust std collections/vec_deque/mod.rs //! A double-ended queue (deque) implemented with a growable ring buffer. //! //! This queue has *O*(1) amortized inserts and removals from
unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) { let new_capacity = self.cap(); // Move the shortest contiguous section of the ring buffer // T H // [o o o o o o o . ] // T H // A [o o o o o o o . . . . . . . . . ] // H T // [o o . o o o o o ] // T H // B [. . . o o o o o o o . . . . . . ] // H T // [o o o o o . o o ] // H T // C [o o o o o . . . . . . . . . o o ] if self.tail <= self.head { // A // Nop } else if self.head < old_capacity - self.tail { // B unsafe { self.copy_nonoverlapping(old_capacity, 0, self.head); } self.head += old_capacity; debug_assert!(self.head > self.tail); } else { // C let new_tail = new_capacity - (old_capacity - self.tail); unsafe { self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail); } self.tail = new_tail; debug_assert!(self.head < self.tail); } debug_assert!(self.head < self.cap()); debug_assert!(self.tail < self.cap()); debug_assert!(self.cap().count_ones() == 1); }
629,823
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: nig_assign_output_variables.m path of file: ./repos/nelson/modules/nig/functions/private the code of the file until where you have to start completion: %============================================================================= % Copyright (c) 2016-present
function txt = nig_assign_output_variables(NIG_FUNCTION) txt = {' // ASSIGN OUTPUT VARIABLES'; ''}; n = 0; for k = NIG_FUNCTION.VARIABLES(:)' if strcmp(k.MODE, 'output') || strcmp(k.MODE, 'in_out') txt{end
687,899
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _problem_details.rs path of file: ./repos/aws-sdk-rust/sdk/tnb/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Details related to problems with AWS TNB resources.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::
pub fn build(self) -> ::std::result::Result<crate::types::ProblemDetails, ::aws_smithy_types::error::operation::BuildError> { ::std::result::Result::Ok(crate::types::ProblemDetails { detail: self.detail.ok_or_else(|| { ::aws_smithy_types::error::operation::BuildError::missing_field( "detail", "detail was not specified but it is required when building ProblemDetails", ) })?, title: self.title, }) }
807,841
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: rindex.m path of file: ./repos/gift/GroupICAT/icatb/toolbox/icasso122 the code of the file until where you have to start completion: function ri=rindex(dist,partition) %function ri=rindex(dist,partition) % %PURPOSE % %To compute a clustering validity index called R-index to assist in %selecting a proper number of clusters. Input argument %'partition' defines different clustering results, partitions, of %the same data. Clustering result that has a (local) minimum value for %R-index among the compared ones is a "good" one. % %The index is not computed (NaN) if the partition contains a %cluster consisting of only one item. % %INPUT % % dist (NxN matrix) matrix of pairwise dissimilarities between N objects % partition (KxN matrix) K partition vectors of the same N objects (see % explanation for 'partition vector' in function hcluster) % %OUTPUT % % ri (Kx1 vector) ri(k) is the value of R-index for clustering % given in partition(k,:). % %DETAILS % %R-index is a Davies-Bouldin type relative clustering validity %index. The clustering that has the minimum value a
function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %This program is free software; you can redistribute it and/or %modify it under the terms of the GNU General Public License %as published by the Free Software Foundation; either version 2 %of the License, or any later version. % %This program is distributed in the hope that it will be useful, %but WITHOUT ANY WARRANTY; without even the implied warranty of %MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %GNU General Public License for more details. % %You should have received a copy of the GNU General Public License %along with this program; if not, write to the Free Software %Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % ver 1.21 030305 johan N=size(partition,1); % Number of clusters in each partition Ncluster=max(partition'); disp('Computing R-index...'); for k=1:N, if any(hist(partition(k,:),1:Ncluster(k))==1), % contains one-item clusters (index very doubtful) ri(k,1)=NaN; elseif Ncluster(k)==1, % Degenerate partition (all in the same cluster) ri(k,1)=NaN; else % compute cluster statistics s=clusterstat(dist,partition(k,:),1); % Compute R-index: (set diagonal to Inf to exclude self-distance! s.between.avg(eye(size(s.between.avg))==1)=Inf; ri(k,1)=mean(s.internal.avg'./min(s.between.avg)); end
348,054
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: types_windows.go path of file: ./repos/kubeedge/vendor/golang.org/x/sys/windows the code of the file until where you have to start completion: // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE
func (addr *SocketAddress) IP() net.IP { if uintptr(addr.SockaddrLength) >= unsafe.Sizeof(RawSockaddrInet4{}) && addr.Sockaddr.Addr.Family == AF_INET { return (*RawSockaddrInet4)(unsafe.Pointer(addr.Sockaddr)).Addr[:] } else if uintptr(addr.SockaddrLength) >= unsafe.Sizeof(RawSockaddrInet6{}) && addr.Sockaddr.Addr.Family == AF_INET6 { return (*RawSockaddrInet6)(unsafe.Pointer(addr.Sockaddr)).Addr[:] } return nil }
420,765
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: parse_and_typecheck.rs path of file: ./repos/rust-protobuf/protobuf-parse/src/pure the code of the file until where you have to start completion: use std::fmt; use std::fs; use std::io; use std::path::Path; use std::path::PathBuf; use std::str; use indexmap::IndexMap; use protobuf::descriptor::FileDescriptorProto; use protobuf::reflect::FileDescriptor; use crate::parse_and_typecheck::ParsedAndTypechecked; use crate::proto; use crate::proto_path::ProtoPath; use crate::proto_path::ProtoPathBuf; use crate::pure::convert; use crate::pure::model; use crate::FileDescriptorPair; use crate::Parser; #[derive(Debug, thiserror::Error)] enum ParseAndTypeckError { #[error("file `{0}` content is not UTF-8")] FileContentIsNotUtf8(String), #[error("protobuf path `{0}` is not found in import path {1}")] FileNotFoundInImportPath(String, String), #[error("file `{0}` must reside in include path {1}")] FileMustResideInImportPath(String, String), #[error("could not read file `{0}`: {1}")] CouldNotReadFile(String, io::Error), } #[derive(Debug, thise
pub fn parse_and_typecheck(parser: &Parser) -> anyhow::Result<ParsedAndTypechecked> { let mut run = Run { parsed_files: IndexMap::new(), resolver: fs_resolver(&parser.includes), }; let relative_paths = parser .inputs .iter() .map(|input| Ok((path_to_proto_path(input, &parser.includes)?, input))) .collect::<anyhow::Result<Vec<_>>>()?; for (proto_path, path) in &relative_paths { let content = fs::read_to_string(path) .map_err(|e| ParseAndTypeckError::CouldNotReadFile(path.display().to_string(), e))?; run.add_file_content( proto_path, &ResolvedProtoFile { path: path.display().to_string(), content: content.into_bytes(), }, )?; } let file_descriptors: Vec<_> = run .parsed_files .into_iter() .map(|(_, v)| v.descriptor_proto) .collect(); Ok(ParsedAndTypechecked { relative_paths: relative_paths.into_iter().map(|(p, _)| p).collect(), file_descriptors, parser: "pure".to_owned(), }) }
730,951
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: options.go path of file: ./repos/aws-sdk-go-v2/service/medicalimaging the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package medicalimaging import ( "context" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" smithyauth "github.com/aws/smithy-go/auth" "github.com/aws/smithy-go/logging" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/t
func WithSigV4SigningRegion(region string) func(*Options) { fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( out middleware.InitializeOutput, metadata middleware.Metadata, err error, ) { return next.HandleInitialize(awsmiddleware.SetSigningRegion(ctx, region), in) } return func(o *Options) { o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { return s.Initialize.Add( middleware.InitializeMiddlewareFunc("withSigV4SigningRegion", fn), middleware.Before, ) }) } }
219,384
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: history.rb path of file: ./repos/stackneveroverflow/vendor/bundle/ruby/2.3.0/gems/byebug-9.0.6/lib/byebug the code of the file until where you have to start completion: begin require 'readline' rescue LoadError warn <<-EOW Sorry, you can't use byebug without Readline. To solve this, you need to rebuild Ruby with Readline support. If using Ubuntu, try `sudo apt-get install libreadline-dev` and then reinstall your Ruby. EOW raise end module Byebug # # Handles byebug's history of commands. # class History att
def to_s(n_cmds) show_size = n_cmds ? specific_max_size(n_cmds) : default_max_size commands = buffer.last(show_size) last_ids(show_size).zip(commands).map do |l| format('%5d %s', l[0], l[1]) end.join("\n") + "\n" end # # Array of ids of the last n commands. # def last_ids(n) (1 + size - n..size).to_a end # # Max number of commands to be displayed when no size has been specified. # # Never more than Setting[:histsize]. # def default_max_size [Setting[:histsize], self.size].min end # # Max number of commands to be displayed when a size has been specified. # # The only bound here is not showing more items than available. # def specific_max_size(number) [self.size, number].min end # # Whether a specific command should not be stored in history. # # For now, empty lines and consecutive duplicates. # def ignore?(buf) return true if /^\s*$/ =~ buf return false if Readline::HISTORY.empty? buffer[Readline::HISTORY.length - 1] == buf end end
245,301
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: create_user_controller.rb path of file: ./repos/sugar/app/controllers/users_controller the code of the file until where you have to start completion: # frozen_string_literal: true class UsersController < ApplicationContr
def check_for_expired_invite return unless @invite&.expired? session.delete(:invite_token) flash[:notice] = t("invite.expired") redirect_to login_users_url end
668,365
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: get_asset.go path of file: ./repos/golang-samples/media/livestream the code of the file until where you have to start completion: // Copyright 2023 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under
func getAsset(w io.Writer, projectID, location, assetID string) error { // projectID := "my-project-id" // location := "us-central1" // assetID := "my-asset-id" ctx := context.Background() client, err := livestream.NewClient(ctx) if err != nil { return fmt.Errorf("NewClient: %w", err) } defer client.Close() req := &livestreampb.GetAssetRequest{ Name: fmt.Sprintf("projects/%s/locations/%s/assets/%s", projectID, location, assetID), } response, err := client.GetAsset(ctx, req) if err != nil { return fmt.Errorf("GetAsset: %w", err) } fmt.Fprintf(w, "Asset: %v", response.Name) return nil }
536,952
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: image.go path of file: ./repos/stash/pkg/scraper the code of the file until where you have to start completion: package scraper import ( "context" "fmt" "io" "net/http" "strings" "github.com/stashapp/stash/pkg/models" "github.com/stashapp/stash/pkg/utils" ) func setPerformerImage(ctx context.Context, client *http.Client, p *models.ScrapedPerformer, globalConfig GlobalConfig) error { if p.Im
func setMovieFrontImage(ctx context.Context, client *http.Client, m *models.ScrapedMovie, globalConfig GlobalConfig) error { // don't try to get the image if it doesn't appear to be a URL if m.FrontImage == nil || !strings.HasPrefix(*m.FrontImage, "http") { // nothing to do return nil } img, err := getImage(ctx, *m.FrontImage, client, globalConfig) if err != nil { return err } m.FrontImage = img return nil }
487,983