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: return_nil_in_predicate_method_definition_spec.rb path of file: ./repos/rubocop/spec/rubocop/cop/style the code of the file until where you have to start completion: # frozen_string_literal: true RSpec.des
def foo? do_something nil do_something end
734,011
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_CreateRoom.go path of file: ./repos/aws-sdk-go-v2/service/ivschat the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package ivschat import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/service/ivsch
func (c *Client) addOperationCreateRoomMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateRoom{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateRoom{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "CreateRoom"); err != nil { return fmt.Errorf("add protocol finalizers: %v", err) } if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = addClientRequestID(stack); err != nil { return err } if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addComputePayloadSHA256(stack); err != nil { return err } if err = addRetry(stack, options); err != nil { return err } if err = addRawResponseToMetadata(stack); err != nil { return err } if err = addRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateRoom(options.Region), middleware.Before); err != nil { return err } if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } if err = addDisableHTTPSMiddleware(stack, options); err != nil { return err } return nil }
233,577
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_XmlEmptyBlobs_test.go path of file: ./repos/aws-sdk-go-v2/internal/protocoltest/restxml the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package restxml import ( "bytes" "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/smithy-go/middleware" smithyrand "github.com/aws/smithy-go/rand" smithytesting "github.com/aws/smithy-go/testing" smithyhttp "github.com/aws/smithy-go/transport/http" "io/ioutil" "net/http" "testing" ) func TestClient_XmlEmptyBlobs_awsRestxmlDeserialize(t *testing.T) { cases := map[string]struct { StatusCode int Header http.Header BodyMediaType string Body []byte ExpectResult *XmlEmptyBlobsOutput }{ // Empty blobs are deserialized as empty string "XmlEmptyBlobs": { StatusCode: 200, Header: http.Header{ "Content-Type": []string{"application/xml"}, }, BodyMediaType: "application/xml", Body: []byte(`<XmlEmptyBlobsResponse> <data></data> </XmlEmptyBlobsResponse> `), ExpectResult: &XmlEmptyBlobsOutput{ Data: []byte(""), }, }, // Empty self closed blobs are deserialized as empty string "XmlEmptySelfClosedBlobs": { StatusCode: 200, Header: http.Header{ "Content-Type": []string{"application/xml"}, }, BodyMediaType: "application/xml", Body: []byte(`<XmlEmptyBlobsResponse> <data/> </XmlEmptyBlobsResponse> `), ExpectResult: &XmlEmptyBlobsOutput{ Data: []byte(""), }, }, } for name, c := range cases { t.Run(name, func(t *testing.T) { serverURL := "http://localhost:8888/" client := New(Options{ HTTPClient: smithyhttp.ClientDoFunc(func(r *http.Request) (*http.Response, error) { headers := http.Header{} for k, vs := range c.Header { for _, v := range vs { headers.Add(k, v) } } if len(c.BodyMediaType) != 0 && len(headers.Values("Content-Type")) == 0 { headers.Set("Content-Type", c.BodyMediaType) } response := &http.Response{ StatusCode: c.StatusCode, Header: headers, Request: r, } if len(c.Body) != 0 { response.ContentLengt
func TestClient_XmlEmptyBlobs_awsRestxmlDeserialize(t *testing.T) { cases := map[string]struct { StatusCode int Header http.Header BodyMediaType string Body []byte ExpectResult *XmlEmptyBlobsOutput }{ // Empty blobs are deserialized as empty string "XmlEmptyBlobs": { StatusCode: 200, Header: http.Header{ "Content-Type": []string{"application/xml"}, }, BodyMediaType: "application/xml", Body: []byte(`<XmlEmptyBlobsResponse> <data></data> </XmlEmptyBlobsResponse> `), ExpectResult: &XmlEmptyBlobsOutput{ Data: []byte(""), }, }, // Empty self closed blobs are deserialized as empty string "XmlEmptySelfClosedBlobs": { StatusCode: 200, Header: http.Header{ "Content-Type": []string{"application/xml"}, }, BodyMediaType: "application/xml", Body: []byte(`<XmlEmptyBlobsResponse> <data/> </XmlEmptyBlobsResponse> `), ExpectResult: &XmlEmptyBlobsOutput{ Data: []byte(""), }, }, } for name, c := range cases { t.Run(name, func(t *testing.T) { serverURL := "http://localhost:8888/" client := New(Options{ HTTPClient: smithyhttp.ClientDoFunc(func(r *http.Request) (*http.Response, error) { headers := http.Header{} for k, vs := range c.Header { for _, v := range vs { headers.Add(k, v) } } if len(c.BodyMediaType) != 0 && len(headers.Values("Content-Type")) == 0 { headers.Set("Content-Type", c.BodyMediaType) } response := &http.Response{ StatusCode: c.StatusCode, Header: headers, Request: r, } if len(c.Body) != 0 { response.ContentLength = int64(len(c.Body)) response.Body = ioutil.NopCloser(bytes.NewReader(c.Body)) } else { response.Body = http.NoBody } return response, nil }), APIOptions: []func(*middleware.Stack) error{ func(s *middleware.Stack) error { s.Finalize.Clear() s.Initialize.Remove(`OperationInputValidation`) return nil }, }, EndpointResolver: EndpointResolverFunc(func(region string, options EndpointResolverOptions) (e aws.Endpoint, err error) { e.URL = serverURL e.SigningRegion = "us-west-2" return e, err }), IdempotencyTokenProvider: smithyrand.NewUUIDIdempotencyToken(&smithytesting.ByteLoop{}), Region: "us-west-2", }) var params XmlEmptyBlobsInput result, err := client.XmlEmptyBlobs(context.Background(), &params) if err != nil { t.Fatalf("expect nil err, got %v", err) } if result == nil { t.Fatalf("expect not nil result") } if err := smithytesting.CompareValues(c.ExpectResult, result); err != nil { t.Errorf("expect c.ExpectResult value match:\n%v", err) } }) } }
215,593
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: logLikelihoodRMELsqnonlin.m path of file: ./repos/PESTO/examples/rafmekerk_signaling the code of the file until where you have to start completion: function [varargout] = logLikelihoodRMELsqnonlin(theta, amiData) % Objective function for examples/rafmekerk_signaling % % logLikelihoodRMELsqnonlin.m provides the residuals, their Jacobian and % an the log-likelihood for the model for the RafMekErk signaling pathway % as defined in rafmekerk_pesto_syms.m % % USAGE: % [res] = logLikelihoodRMELsqnonlin(theta, amiData) % [res, sres] = logLikelihoodRMELsqnonlin(theta, amiData) % [res, ~, llh] = logLikelihoodRMELsqnonlin(theta, amiData) % % Parameters: % theta: Model parameters % amiData: an amidata object for the AMICI solver % % Return values: % varargout: % res: residuals of simulation vs data % sres: Jacobian of the residuals, i.e. partial derivatives of the % residuals w.r.t. to model parameters % llh: Log-Likelihood, only the LogLikelihood will be returned, no % sensitivity analysis is performed %% Model Definition % The ODE model is set up using the AMICI toolbox. To access the AMICI % model setup, see rafmekerk_pesto_syms.m % For a detailed description for the biological model see the referenced
function [varargout] = logLikelihoodRMELsqnonlin(theta, amiData) % Objective function for examples/rafmekerk_signaling % % logLikelihoodRMELsqnonlin.m provides the residuals, their Jacobian and % an the log-likelihood for the model for the RafMekErk signaling pathway % as defined in rafmekerk_pesto_syms.m % % USAGE: % [res] = logLikelihoodRMELsqnonlin(theta, amiData) % [res, sres] = logLikelihoodRMELsqnonlin(theta, amiData) % [res, ~, llh] = logLikelihoodRMELsqnonlin(theta, amiData) % % Parameters: % theta: Model parameters % amiData: an amidata object for the AMICI solver % % Return values: % varargout: % res: residuals of simulation vs data % sres: Jacobian of the residuals, i.e. partial derivatives of the % residuals w.r.t. to model parameters % llh: Log-Likelihood, only the LogLikelihood will be returned, no % sensitivity analysis is performed %% Model Definition % The ODE model is set up using the AMICI toolbox. To access the AMICI % model setup, see rafmekerk_pesto_syms.m % For a detailed description for the biological model see the referenced % paper by Fiedler et al. nPar = 28; nData = 56; % Set options according to function call if (nargout == 2) amiOptions.sensi = 1; else amiOptions.sensi = 0; end
155,945
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: QfTree.m path of file: ./repos/scGEAToolbox/+run/external/mt_UMAP the code of the file until where you have to start completion: % Class for building a dendrogram based on QF dissimilarity measurements % % AUTHORSHIP % Primary Developer: Stephen Meehan <swmeehan@stanford.edu> % Math Lead & Secondary Developer: Connor Meehan <connor.gw.meehan@gmail.com> % Bioinformatics Lead: Wayne Moore <wmoore@stanford.edu> % Provided by the Herzenberg Lab at Stanford University % License: BSD 3 clause % % QF dissimilarity is described in % https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6586874/ % % QF Tree (phenogram) is described in % https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6586874/ classdef QfTree < handle pr
function doFigures(this, h) this.figures.doJavaMenu(h, this.figs1D.values); end function seePbe(this) this.gt.gtt.openPlotEditor(this.gt.tp, this.gid, ... num2str(this.fcsIdxs)); end function fileName = getFileName(this, idx) [~, dsc, ~, ~, key] = this.unpackNode(idx); key = strrep(key, ' OR ', '_'); dsc = char( ... edu.stanford.facs.swing.Basics.RemoveXml( ... dsc)); dsc = strrep(strtrim(dsc), ' ', '_'); dsc = strrep(String.ToSystem(dsc), '"', ''); fileName = [dsc, '-', key]; end
180,632
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: literal_as_condition.rb path of file: ./repos/rubocop/lib/rubocop/cop/lint the code of the file until where you have to start completion: # frozen_string_literal: true module RuboCop module Cop module Lint # Checks for literals used as the conditions or as # operands in and/or expressions serving as the conditions of # if/while/until/case-when/case-in. # # NOTE: Literals in `case-in` condition where the match variabl
def on_case(case_node) if case_node.condition check_case(case_node) else case_node.each_when do |when_node| next unless when_node.conditions.all?(&:literal?) range = when_conditions_range(when_node) message = message(range) add_offense(range, message: message) end end
733,686
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: abs.m path of file: ./repos/d2d/arFramework3/ThirdParty/StrucID/adimat/adjointclasses/taylor2/@tseries2 the code of the file until where you have to start completion: function obj = abs(obj) if isreal(obj.m_series{1}) less0 = obj.m_series{1} < 0;
function obj = abs(obj) if isreal(obj.m_series{1}) less0 = obj.m_series{1} < 0; eq0 = obj.m_series{1} == 0; if any(eq0(:)) warning('adimat:tseries2:abs:argZero', '%s', ... 'abs is not defined at 0'); end
632,636
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: manage_users.rb path of file: ./repos/aws-doc-sdk-examples/ruby/example_code/iam the code of the file until where you have to start completion: # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 require "aws-sdk-iam" requi
def update_user_name(current_name, new_name) @iam_client.update_user(user_name: current_name, new_user_name: new_name) true rescue StandardError => e @logger.error("Error updating user name from '#{current_name}' to '#{new_name}': #{e.message}") false end
535,589
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: qovery_api.rs path of file: ./repos/engine/src/engine_task the code of the file until where you have to start completion: use crate::cloud_provider::service::ServiceType; use crate::io_models::application::GitCredentials; use anyhow::anyhow; use std::
fn service_version(&self, service_type: EngineServiceType) -> anyhow::Result<String> { Ok(self .versions .get(&service_type) .ok_or_else(|| anyhow!("Missing service version for {service_type:?}"))? .clone()) }
90,704
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: notes.rs path of file: ./repos/rust-analyzer/xtask/src/publish the code of the file until where you have to start completion: use anyhow::{anyhow, bail}; use std::{ borrow::Cow, io::{BufRead, Lines}, iter::Peekable, }; const LISTING_DELIMITER: &str = "----"; const IMAGE_BLOCK_PREFIX: &str = "image::"; const VIDEO_BLOCK_PREFIX: &str = "video::"; struct Converter<'a, 'b, R: BufRead> { iter:
fn process_source_code_block(&mut self, level: usize) -> anyhow::Result<()> { if let Some(Ok(line)) = self.iter.next() { if let Some(styles) = line.strip_prefix("[source").and_then(|s| s.strip_suffix(']')) { let mut styles = styles.split(','); if !styles.next().unwrap().is_empty() { bail!("not a source code block"); } let language = styles.next(); return self.process_listing_block(language, level); } } bail!("not a source code block") }
367,633
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: timeutil_test.go path of file: ./repos/rill/runtime/pkg/timeutil the code of the file until where you have to start completion: package timeutil import ( "testing" "time" "github.com/stretchr/testify/require" ) func TestTruncateTime(t *testing.T) { require.Equal(t, parseTestTime(t, "2019-01-07T04:20:07Z"), TruncateTime(parseTestTime(t, "2019-01-07T04:20:07.29Z"), TimeGrainSecond, time.UTC, 1, 1)) require.Equal(t, parseTestTime(t, "2019-01-07T04:20:00Z"), TruncateTime(parseTestTime(t, "2019-01-07T04:20:07Z"), TimeGrainMinute, time.UTC, 1, 1)) require.Equal(t, parseTestTime(t, "2019-01-07T04:00:00Z"), TruncateTime(parseTestTime(t, "2019-01-07T04:20:01Z"), TimeGrainHour, time.UTC, 1, 1)) require.Equal(t, parseTestTime(t, "2019-01-07T00:00:00Z"), TruncateTime(parseTestTime(t, "2019-01-07T04:20:01Z"), TimeGrainDay, time.UTC, 1, 1)) require.Equal(t, parseTestTime(t, "2023-10-09T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-10-10T04:20:01Z"), TimeGrainWeek, time.UTC, 1, 1)) require.Equal(t, parseTestTime(t, "2019-01-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2019-01-07T01:01:01Z"), TimeGrainMonth, time.UTC, 1, 1)) require.Equal(t, parseTestTime(t, "2019-04-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2019-05-07T01:01:01Z"), TimeGrainQuarter, time.UTC, 1, 1)) require.Equal(t, parseTestTime(t, "2019-01-01T00:0
func TestTruncateTime_UTC_first_month(t *testing.T) { tz := time.UTC require.Equal(t, parseTestTime(t, "2023-08-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-10-01T00:20:00Z"), TimeGrainQuarter, tz, 2, 2)) require.Equal(t, parseTestTime(t, "2023-11-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-11-01T00:20:00Z"), TimeGrainQuarter, tz, 2, 5)) require.Equal(t, parseTestTime(t, "2023-09-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-10-01T00:20:00Z"), TimeGrainQuarter, tz, 2, 3)) require.Equal(t, parseTestTime(t, "2023-09-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-11-01T00:20:00Z"), TimeGrainQuarter, tz, 2, 6)) require.Equal(t, parseTestTime(t, "2022-12-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-02-01T00:20:00Z"), TimeGrainQuarter, tz, 2, 3)) require.Equal(t, parseTestTime(t, "2022-12-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-02-01T00:20:00Z"), TimeGrainQuarter, tz, 2, 6)) require.Equal(t, parseTestTime(t, "2023-02-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-10-01T00:20:00Z"), TimeGrainYear, tz, 2, 2)) require.Equal(t, parseTestTime(t, "2023-03-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-10-01T00:20:00Z"), TimeGrainYear, tz, 2, 3)) require.Equal(t, parseTestTime(t, "2023-03-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-03-01T00:20:00Z"), TimeGrainYear, tz, 2, 3)) require.Equal(t, parseTestTime(t, "2022-12-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-10-01T00:20:00Z"), TimeGrainYear, tz, 2, 12)) require.Equal(t, parseTestTime(t, "2023-01-01T00:00:00Z"), TruncateTime(parseTestTime(t, "2023-01-01T00:20:00Z"), TimeGrainYear, tz, 2, 1)) }
75,096
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: hunger_system.rs path of file: ./repos/rustrogueliketutorial/chapter-31-symmetry/src the code of the file until where you have to start completion: use specs::prelude::*; use super::{HungerClock, RunState, HungerState, SufferDamage, gamelog::GameLog}; pub struct HungerSystem {} impl<'a> System<'a> for HungerSystem { #[allow(clippy::type_complexity)] type SystemData = ( Entities<'a>, WriteStorage<'a, HungerClock>, ReadExpect<'a, Entity>, // The player ReadExpect<'a, RunState>, WriteStorage<'a, SufferDamage>, WriteExpect<'a, GameLog> ); fn run(&mut self, data : Self::SystemData) { let (entities, mut hunger_clock, player_entity, runstate, mut infl
fn run(&mut self, data : Self::SystemData) { let (entities, mut hunger_clock, player_entity, runstate, mut inflict_damage, mut log) = data; for (entity, mut clock) in (&entities, &mut hunger_clock).join() { let mut proceed = false; match *runstate { RunState::PlayerTurn => { if entity == *player_entity { proceed = true; } } RunState::MonsterTurn => { if entity != *player_entity { proceed = false; } } _ => proceed = false } if proceed { clock.duration -= 1; if clock.duration < 1 { match clock.state { HungerState::WellFed => { clock.state = HungerState::Normal; clock.duration = 200; if entity == *player_entity { log.entries.push("You are no longer well fed.".to_string()); } } HungerState::Normal => { clock.state = HungerState::Hungry; clock.duration = 200; if entity == *player_entity { log.entries.push("You are hungry.".to_string()); } } HungerState::Hungry => { clock.state = HungerState::Starving; clock.duration = 200; if entity == *player_entity { log.entries.push("You are starving!".to_string()); } } HungerState::Starving => { // Inflict damage from hunger if entity == *player_entity { log.entries.push("Your hunger pangs are getting painful! You suffer 1 hp damage.".to_string()); } SufferDamage::new_damage(&mut inflict_damage, entity, 1); } } } } } }
38,442
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: rbffwd.m path of file: ./repos/pcm/matlab/lib/netlab3_3 the code of the file until where you have to start completion: function [a, z, n2] = rbffwd(net, x) %RBFFWD Forward propagation through RBF network with linear outputs. % % Description % A = RBFFWD(NET, X) takes a network data structure NET and a matrix X % of input vectors and forward propagates the inputs through the % network to generate a matrix A of output vectors. Each row of X % corresponds to one input vector and each row of A contains the % corresponding output vector. The activation function that is used is % determined by NET.ACTFN. % % [A, Z, N2] = RBFFWD(NET, X) also generates a matrix Z of the hidden
function [a, z, n2] = rbffwd(net, x) %RBFFWD Forward propagation through RBF network with linear outputs. % % Description % A = RBFFWD(NET, X) takes a network data structure NET and a matrix X % of input vectors and forward propagates the inputs through the % network to generate a matrix A of output vectors. Each row of X % corresponds to one input vector and each row of A contains the % corresponding output vector. The activation function that is used is % determined by NET.ACTFN. % % [A, Z, N2] = RBFFWD(NET, X) also generates a matrix Z of the hidden % unit activations where each row corresponds to one pattern. These % hidden unit activations represent the design matrix for the RBF. The % matrix N2 is the squared distances between each basis function centre % and each pattern in which each row corresponds to a data point. % % See also % RBF, RBFERR, RBFGRAD, RBFPAK, RBFTRAIN, RBFUNPAK % % Copyright (c) Ian T Nabney (1996-2001) % Check arguments for consistency errstring = consist(net, 'rbf', x); if ~isempty(errstring); error(errstring); end
538,145
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: encode_map.go path of file: ./repos/kubernetes/vendor/github.com/fxamacker/cbor/v2 the code of the file until where you have to start completion: // Copyright (c) Faye Amacker. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. //go:build go1.20 package cbor import ( "reflect" "sync" ) type mapKeyValueEncodeFunc struct { kf, ef encodeFunc kpool, vpool sync.Pool } func (me *mapKeyValueEncodeFunc) encodeKeyValues(e *encoderBuffer, em *encMode, v reflect.Value,
func (me *mapKeyValueEncodeFunc) encodeKeyValues(e *encoderBuffer, em *encMode, v reflect.Value, kvs []keyValue) error { trackKeyValueLength := len(kvs) == v.Len() iterk := me.kpool.Get().(*reflect.Value) defer func() { iterk.SetZero() me.kpool.Put(iterk) }() iterv := me.vpool.Get().(*reflect.Value) defer func() { iterv.SetZero() me.vpool.Put(iterv) }() iter := v.MapRange() for i := 0; iter.Next(); i++ { off := e.Len() iterk.SetIterKey(iter) iterv.SetIterValue(iter) if err := me.kf(e, em, *iterk); err != nil { return err } if trackKeyValueLength { kvs[i].keyLen = e.Len() - off } if err := me.ef(e, em, *iterv); err != nil { return err } if trackKeyValueLength { kvs[i].keyValueLen = e.Len() - off } } return nil }
353,267
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/chime/src/operation/delete_sip_rule 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, } }
803,808
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: enumerator.rb path of file: ./repos/natalie/src the code of the file until where you have to start completion: class Enumerator include Enumerable class Chain < Enumerator def initialize(*enumerables) @current_feed = [] @enumerables = enumerables @enum_block = Pr
def select(&block) raise ArgumentError, 'tried to call lazy select without a block' unless block_given? gather = ->(item) { item.size <= 1 ? item.first : item } Lazy.new(self) do |yielder, *values| item = gather.(values) yielder.yield(*item) if block.call(item) end end
550,580
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: identities.go path of file: ./repos/hugo/resources/page/siteidentities the code of the file until where you have to start completion: // Copyright 2024 The Hugo Authors. All rights reserved.
func FromString(name string) (identity.Identity, bool) { switch name { case "Data": return Data, true } return identity.Anonymous, false }
153,848
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: msg_publisher.rs path of file: ./repos/engine/src the code of the file until where you have to start completion: use crate::events::EngineMsg; use tok
fn send(&self, msg: EngineMsg) { match self.send(msg) { Ok(_) => {} Err(_) => { error!("Unable to send engine msg to msg channel"); } } }
90,548
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: provisioner_test.go path of file: ./repos/juju/worker/provisioner the code of the file until where you have to start completion: // Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package provisioner_test import ( stdcontext "context" "fmt" "strings" "sync" "time" "github.com/juju/collections/set" "github.com/juju/errors" "github.com/juju/loggo" "github.com/juju/names/v5" jc "github.com/juju/testing/checkers" "github.com/juju/utils/v3" "github.com/juju/version/v2" "github.co
func (s *ProvisionerSuite) TestSetUpToStartMachine(c *gc.C) { attrs := map[string]interface{}{ config.CloudInitUserDataKey: validCloudInitUserData, } err := s.Model.UpdateModelConfig(attrs, nil) c.Assert(err, jc.ErrorIsNil) task := s.newProvisionerTask( c, config.HarvestAll, s.Environ, s.provisioner, &mockDistributionGroupFinder{}, mockToolsFinder{}, ) defer workertest.CleanKill(c, task) machine, err := s.addMachine() c.Assert(err, jc.ErrorIsNil) mRes, err := s.provisioner.Machines(machine.MachineTag()) c.Assert(err, gc.IsNil) c.Assert(mRes, gc.HasLen, 1) c.Assert(mRes[0].Err, gc.IsNil) apiMachine := mRes[0].Machine pRes, err := s.provisioner.ProvisioningInfo([]names.MachineTag{machine.MachineTag()}) c.Assert(err, gc.IsNil) c.Assert(pRes.Results, gc.HasLen, 1) v, err := apiMachine.ModelAgentVersion() c.Assert(err, jc.ErrorIsNil) startInstanceParams, err := provisioner.SetupToStartMachine(task, apiMachine, v, pRes.Results[0]) c.Assert(err, jc.ErrorIsNil) cloudInitUserData := startInstanceParams.InstanceConfig.CloudInitUserData c.Assert(cloudInitUserData, gc.DeepEquals, map[string]interface{}{ "packages": []interface{}{"python-keystoneclient", "python-glanceclient"}, "preruncmd": []interface{}{"mkdir /tmp/preruncmd", "mkdir /tmp/preruncmd2"}, "postruncmd": []interface{}{"mkdir /tmp/postruncmd", "mkdir /tmp/postruncmd2"}, "package_upgrade": false}, ) }
613,427
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/finspace/src/operation/list_kx_cluster_nodes 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, } }
793,693
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: service_logs.go path of file: ./repos/comply/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" "io" "net/url" "time" "github.com/docker/docker/api/types" timetypes "github.com/docker/docker/api/types/time" "github.com/pkg/errors" ) // ServiceLogs returns the logs generated by a service in an io.ReadCloser. // It's up to the caller to close the stream. func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { query := url.Values{} if options.ShowStdout
func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { query := url.Values{} if options.ShowStdout { query.Set("stdout", "1") } if options.ShowStderr { query.Set("stderr", "1") } if options.Since != "" { ts, err := timetypes.GetTimestamp(options.Since, time.Now()) if err != nil { return nil, errors.Wrap(err, `invalid value for "since"`) } query.Set("since", ts) } if options.Timestamps { query.Set("timestamps", "1") } if options.Details { query.Set("details", "1") } if options.Follow { query.Set("follow", "1") } query.Set("tail", options.Tail) resp, err := cli.get(ctx, "/services/"+serviceID+"/logs", query, nil) if err != nil { return nil, err } return resp.body, nil }
291,456
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: utils.go path of file: ./repos/alist/drivers/baidu_photo the code of the file until where you have to start completion: package baiduphoto import ( "context" "fm
func (d *BaiduPhoto) refreshToken() error { u := "https://openapi.baidu.com/oauth/2.0/token" var resp base.TokenResp var e TokenErrResp _, err := base.RestyClient.R().SetResult(&resp).SetError(&e).SetQueryParams(map[string]string{ "grant_type": "refresh_token", "refresh_token": d.RefreshToken, "client_id": d.ClientID, "client_secret": d.ClientSecret, }).Get(u) if err != nil { return err } if e.ErrorMsg != "" { return &e } if resp.RefreshToken == "" { return errs.EmptyToken } d.AccessToken, d.RefreshToken = resp.AccessToken, resp.RefreshToken op.MustSaveDriverStorage(d) return nil }
199,305
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: candidate_node_yaml.go path of file: ./repos/yq/pkg/yqlib the code of the file until where you have to start completion: package yqlib import ( "fmt" yaml "gopkg.in/yaml.v3" ) func MapYamlStyle(original yaml.Style) Style { switch original { case yaml.TaggedStyle: return TaggedStyle case yaml.DoubleQuotedStyle: return DoubleQuotedStyle case yaml.SingleQuotedStyle: return SingleQuotedStyle case yaml.LiteralStyle: return LiteralStyle case yaml.FoldedStyle: return FoldedStyle case yaml.FlowStyle: return FlowStyle case 0: return 0 } return Style(original) } func MapToYamlStyle(original Style) yaml.Style { switch original { case TaggedStyle: return yaml.TaggedStyle case DoubleQuotedStyle: return yaml.DoubleQuotedStyle case SingleQuotedStyle: return yaml.SingleQuotedStyle case LiteralStyle: return yaml.LiteralStyle case FoldedStyle: return yaml.FoldedStyle case
func (o *CandidateNode) UnmarshalYAML(node *yaml.Node, anchorMap map[string]*CandidateNode) error { log.Debugf("UnmarshalYAML %v", node.Tag) switch node.Kind { case yaml.AliasNode: log.Debug("UnmarshalYAML - alias from yaml: %v", o.Tag) o.Kind = AliasNode o.copyFromYamlNode(node, anchorMap) return nil case yaml.ScalarNode: log.Debugf("UnmarshalYAML - a scalar") o.Kind = ScalarNode o.copyFromYamlNode(node, anchorMap) return nil case yaml.MappingNode: log.Debugf("UnmarshalYAML - a mapping node") o.Kind = MappingNode o.copyFromYamlNode(node, anchorMap) o.Content = make([]*CandidateNode, len(node.Content)) for i := 0; i < len(node.Content); i += 2 { keyNode, err := o.decodeIntoChild(node.Content[i], anchorMap) if err != nil { return err } keyNode.IsMapKey = true valueNode, err := o.decodeIntoChild(node.Content[i+1], anchorMap) if err != nil { return err } valueNode.Key = keyNode o.Content[i] = keyNode o.Content[i+1] = valueNode } log.Debugf("UnmarshalYAML - finished mapping node") return nil case yaml.SequenceNode: log.Debugf("UnmarshalYAML - a sequence: %v", len(node.Content)) o.Kind = SequenceNode o.copyFromYamlNode(node, anchorMap) log.Debugf("node Style: %v", node.Style) log.Debugf("o Style: %v", o.Style) o.Content = make([]*CandidateNode, len(node.Content)) for i := 0; i < len(node.Content); i++ { keyNode := o.CreateChild() keyNode.IsMapKey = true keyNode.Tag = "!!int" keyNode.Kind = ScalarNode keyNode.Value = fmt.Sprintf("%v", i) valueNode, err := o.decodeIntoChild(node.Content[i], anchorMap) if err != nil { return err } valueNode.Key = keyNode o.Content[i] = valueNode } return nil case 0: // not sure when this happens o.copyFromYamlNode(node, anchorMap) log.Debugf("UnmarshalYAML - err.. %v", NodeToString(o)) return nil default: return fmt.Errorf("orderedMap: invalid yaml node") } }
325,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: apply.rs path of file: ./repos/nmstate/rust/src/lib/nm/query_apply the code of the file until where you have to start completion: // SPDX-License-Identifier: Apache-2.0 use std::collections::HashSet; use super::super::{ d
fn check_nm_version(nm_api: &NmApi) { if let Ok(versions) = nm_api.version().map(|ver_str| { ver_str .split('.') .map(|v| v.parse::<i32>().unwrap_or_default()) .collect::<Vec<i32>>() }) { if let (Some(major), Some(minor)) = (versions.first(), versions.get(1)) { if *major < 1 || *minor < 40 { log::warn!( "Unsupported NetworkManager version {major}.{minor}, \ expecting >= 1.40" ); } } } }
647,965
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/chimesdkmeetings/src/operation/delete_meeting 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, } }
767,506
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: selinux_linux.go path of file: ./repos/kubernetes/vendor/github.com/opencontainers/selinux/go-selinux the code of the file until where you have to start completion: package selinux import ( "bufio" "bytes" "crypto/rand" "encoding/binary" "errors" "fmt" "io" "io/fs" "math/big" "os" "os/user" "path/filepath" "strconv" "strings" "sync" "github.com/opencontainers/selinux/pkg/pwalkdir" "golang.org/x/sys/unix" ) const ( min
func copyLevel(src, dest string) (string, error) { if src == "" { return "", nil } if err := SecurityCheckContext(src); err != nil { return "", err } if err := SecurityCheckContext(dest); err != nil { return "", err } scon, err := NewContext(src) if err != nil { return "", err } tcon, err := NewContext(dest) if err != nil { return "", err } mcsDelete(tcon["level"]) _ = mcsAdd(scon["level"]) tcon["level"] = scon["level"] return tcon.Get(), nil }
352,311
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.snapshot.create_repository.go path of file: ./repos/go-elasticsearch/esapi the code of the file until where you have to start completion: // Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regardin
func (f SnapshotCreateRepository) WithOpaqueID(s string) func(*SnapshotCreateRepositoryRequest) { return func(r *SnapshotCreateRepositoryRequest) { if r.Header == nil { r.Header = make(http.Header) } r.Header.Set("X-Opaque-Id", s) } }
672,005
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_ListRecommendations.go path of file: ./repos/aws-sdk-go-v2/service/costoptimizationhub the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package costoptimizationhub import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/service/costoptimizationhub/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Returns a list of recommendations. func (c *Client) ListRecommendations(ctx context.Context
func NewListRecommendationsPaginator(client ListRecommendationsAPIClient, params *ListRecommendationsInput, optFns ...func(*ListRecommendationsPaginatorOptions)) *ListRecommendationsPaginator { if params == nil { params = &ListRecommendationsInput{} } options := ListRecommendationsPaginatorOptions{} if params.MaxResults != nil { options.Limit = *params.MaxResults } for _, fn := range optFns { fn(&options) } return &ListRecommendationsPaginator{ options: options, client: client, params: params, firstPage: true, nextToken: params.NextToken, } }
221,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: am_ge.m path of file: ./repos/d2d/arFramework3/ThirdParty/strike-goldd/STRIKE-GOLDD/MEIGO64/MEIGO/PEtabMEIGO/Sbml2Meigo/symbolic the code of the file until where you have to start completion: function fun = am_ge(varargin) % am_ge is the amici implementation of the n-ary mathml greaterorequal function % this is an n-ary function, for more than 2 input parameters it will check % whether and(varargin{1} >= varargin{2},varargin{2} >= varargin{3},...) % % Parameters: % varargin: chain of input parameters @type sym %
function fun = am_ge(varargin) % am_ge is the amici implementation of the n-ary mathml greaterorequal function % this is an n-ary function, for more than 2 input parameters it will check % whether and(varargin{1} >= varargin{2},varargin{2} >= varargin{3},...) % % Parameters: % varargin: chain of input parameters @type sym % % Return values: % fun: a >= b logical value, negative for false, positive for true a=varargin{1}; b=varargin{2}; fun = a-b; if(nargin>2) fun = am_and(a-b,am_ge(varargin{2:end
632,281
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.rs path of file: ./repos/perseus/packages/perseus-cli/src/bin the code of the file until where you have to start completion: use clap::Parser; use command_group::stdlib::CommandGroup; use directories::ProjectDirs; use fmterr::fmt_err; use indicatif::MultiProgress; use notify::{recommended_watcher, RecursiveMode, Watcher}; use perseus_cli::parse::{ BuildOpts, CheckOpts, ExportOpts, ServeOpts, SnoopServeOpts, SnoopSubcommand, TestOpts, }; use perseus_cli::{ build, check_env, delete_artifacts, deploy, export, init, new, parse::{Opts, Subcommand}, serve, serve_exported, test, tinker, }; use perseus_cli::{ check, create_dist, delete_dist, errors::*, export_error_page, order_reload, run_reload_server, snoop_build, snoop_server, snoop_wasm_build, Tools, WATCH_EXCLUSIONS, }; use std::env; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode}; use std::sync::mpsc::channel; use walkdir::WalkDir; // All this does is run the program and terminate with the acquired exit code #[tokio::main] async fn main() -> ExitCode { // In development, we'll test in the `basic` example if cfg!(debug_assertions) && env::var("TEST_EXAMPLE").is_ok() { let example_to_test = env::var("TEST_EXAMPLE").unwrap(); env::set_current_dir(example_to_test).unwrap(); } let exit_code = real_main().await; let u8_exit_code: u8 = exit_code.try_into().unwrap_or(1); ExitCode::from(u8_exit_code) } // This manages error handling and returns a definite exit code to terminate // with async fn real_main() -> i32 { // Get the working directory let dir = env::current_dir(); let dir = match dir { Ok(dir) => dir
async fn core_watch(dir: PathBuf, opts: Opts) -> Result<i32, Error> { // We install the tools for every command except `new`, `init`, and `clean` let exit_code = match opts.subcmd { Subcommand::Build(ref build_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; // Delete old build artifacts delete_artifacts(dir.clone(), "static")?; delete_artifacts(dir.clone(), "mutable")?; build(dir, build_opts, &tools, &opts)? } Subcommand::Export(ref export_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; // Delete old build/export artifacts delete_artifacts(dir.clone(), "static")?; delete_artifacts(dir.clone(), "mutable")?; delete_artifacts(dir.clone(), "exported")?; let exit_code = export(dir.clone(), export_opts, &tools, &opts)?; if exit_code != 0 { return Ok(exit_code); } if export_opts.serve { // Tell any connected browsers to reload order_reload(opts.reload_server_host.to_string(), opts.reload_server_port); // This will terminate if we get an error exporting the 404 page serve_exported( dir, export_opts.host.to_string(), export_opts.port, &tools, &opts, ) .await? } else { 0 } } Subcommand::Serve(ref serve_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; if !serve_opts.no_build { delete_artifacts(dir.clone(), "static")?; delete_artifacts(dir.clone(), "mutable")?; } // This orders reloads internally let (exit_code, _server_path) = serve(dir, serve_opts, &tools, &opts, &MultiProgress::new(), false)?; exit_code } Subcommand::Test(ref test_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; // Delete old build artifacts if `--no-build` wasn't specified if !test_opts.no_build { delete_artifacts(dir.clone(), "static")?; delete_artifacts(dir.clone(), "mutable")?; } test(dir, test_opts, &tools, &opts)? } Subcommand::Clean => { delete_dist(dir)?; // Warn the user that the next run will be quite a bit slower eprintln!( "[NOTE]: Build artifacts have been deleted, the next run will take some time." ); 0 } Subcommand::Deploy(ref deploy_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; delete_artifacts(dir.clone(), "static")?; delete_artifacts(dir.clone(), "mutable")?; delete_artifacts(dir.clone(), "exported")?; delete_artifacts(dir.clone(), "pkg")?; deploy(dir, deploy_opts, &tools, &opts)? } Subcommand::Tinker(ref tinker_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; // Unless we've been told not to, we start with a blank slate // This will remove old tinkerings and eliminate any possible corruptions (which // are very likely with tinkering!) if !tinker_opts.no_clean { delete_dist(dir.clone())?; } tinker(dir, &tools, &opts)? } Subcommand::Snoop(ref snoop_subcmd) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; match snoop_subcmd { SnoopSubcommand::Build { .. } => snoop_build(dir, &tools, &opts)?, SnoopSubcommand::WasmBuild { .. } => snoop_wasm_build(dir, &tools, &opts)?, SnoopSubcommand::Serve(ref snoop_serve_opts) => { // Warn the user about the perils of watching `snoop serve` if snoop_serve_opts.watch { eprintln!("[WARNING]: Watching `snoop serve` may not be a good idea, because it requires you to have run `perseus build` first. It's not recommended to do this unless you have `perseus build` on a separate watch loop."); } snoop_server(dir, snoop_serve_opts, &tools, &opts)? } } } Subcommand::ExportErrorPage(ref eep_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; export_error_page( dir, eep_opts, &tools, &opts, true, /* Do prompt the user */ )? } Subcommand::New(ref new_opts) => new(dir, new_opts, &opts)?, Subcommand::Init(ref init_opts) => init(dir, init_opts)?, Subcommand::Check(ref check_opts) => { create_dist(&dir)?; let tools = Tools::new(&dir, &opts).await?; // Delete old build artifacts delete_artifacts(dir.clone(), "static")?; delete_artifacts(dir.clone(), "mutable")?; check(dir, check_opts, &tools, &opts)? } }; Ok(exit_code) }
655,722
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: strutil.go path of file: ./repos/scan4all/vendor/github.com/gosuri/uiprogress/util/strutil the code of the file until where you have to start completion: // Package strutil provides various utilities for manipulating strings package strutil import ( "bytes" "time" ) // PadRight returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character. func PadRight(str string
func Resize(s string, length uint) string { n := int(length) if len(s) == n { return s } // Pads only when length of the string smaller than len needed s = PadRight(s, n, ' ') if len(s) > n { b := []byte(s) var buf bytes.Buffer for i := 0; i < n-3; i++ { buf.WriteByte(b[i]) } buf.WriteString("...") s = buf.String() } return s }
140,521
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: account_provider.rb path of file: ./repos/darrrr/lib/darrrr the code of the file until where you have to start completion: # frozen_string_liter
def to_h { "issuer" => self.issuer, "tokensign-pubkeys-secp256r1" => self.unseal_keys.dup, "save-token-return" => self.save_token_return, "recover-account-return" => self.recover_account_return, "privacy-policy" => self.privacy_policy, "icon-152px" => self.icon_152px } end
5,511
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: sysreadfile.go path of file: ./repos/plumber/vendor/github.com/prometheus/procfs/internal/util the code of the file until where you have to start completion: // Copyright 2018 The Prometheus 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
func SysReadFile(file string) (string, error) { f, err := os.Open(file) if err != nil { return "", err } defer f.Close() // On some machines, hwmon drivers are broken and return EAGAIN. This causes // Go's ioutil.ReadFile implementation to poll forever. // // Since we either want to read data or bail immediately, do the simplest // possible read using syscall directly. const sysFileBufferSize = 128 b := make([]byte, sysFileBufferSize) n, err := syscall.Read(int(f.Fd()), b) if err != nil { return "", err } return string(bytes.TrimSpace(b[:n])), nil }
457,582
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-kms-key-list.go path of file: ./repos/mc/cmd the code of the file until where you have to start completion: // Copyright (c) 2015-2023 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 the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package cmd import ( "fmt" "os" "github.com/fatih/color" "github.com/jedib0t/go-pretty/v6/table" "github.com/jedib0t/go-pretty/v6/text" "github.com/minio/cli" json "github.com/minio/colorjson" "github.co
func mainAdminKMSKeyList(ctx *cli.Context) error { if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 { showCommandHelpAndExit(ctx, 1) // last argument is exit code } console.SetColor("KeyName", color.New(color.FgBlue)) // Get the alias parameter from cli args := ctx.Args() aliasedURL := args.Get(0) // Create a new MinIO Admin Client client, err := newAdminClient(aliasedURL) fatalIf(err, "Unable to initialize admin connection.") keys, e := client.ListKeys(globalContext, "*") fatalIf(probe.NewError(e).Trace(args...), "Unable to list KMS keys") var rows []table.Row kmsKeys := []string{} for idx, k := range keys { rows = append(rows, table.Row{idx + 1, k.Name}) kmsKeys = append(kmsKeys, k.Name) } if globalJSON { printMsg(kmsKeysMsg{ Status: "success", Target: aliasedURL, Keys: kmsKeys, }) return nil } t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.SetColumnConfigs([]table.ColumnConfig{{Align: text.AlignCenter}}) t.SetTitle("KMS Keys") t.AppendHeader(table.Row{"S N", "Name"}) t.AppendRows(rows) t.SetStyle(table.StyleLight) t.Render() return nil }
428,766
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: mod.go path of file: ./repos/trivy/pkg/iac/scanners/azure/functions the code of the file until where you have to start completion: package functions func Mod(args ...interface{}) interface{} { if len(args) != 2 { return 0 } if a, ok := a
func Mod(args ...interface{}) interface{} { if len(args) != 2 { return 0 } if a, ok := args[0].(int); ok { if b, ok := args[1].(int); ok { return a % b } } return 0 }
726,260
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.go path of file: ./repos/arvados/lib/controller/federation the code of the file until where you have to start completion: // Copyright (C) The Arvados Authors. All rights reserved. // // SPDX-License-Identifier: AGPL-3.0 package federation import ( "context" "fmt" "net/http" "sort" "sync" "sync/atomic" "git.arvados.org/arvados.git/sdk/go/arvados" "git.arvados.org/arvados.git/sdk/go/httpserver" ) //go:generate go run generate.go // CollectionList is used as a template to auto-generate List() // methods for other types; see generate.go. func (conn *Conn) generated_CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) { var mtx sync.Mutex var merged arvados.CollectionList var needSort atomic.Value needSort.Store(false) err := conn.splitListRequest(ctx, options, func(ctx context.Context, _ string, backend arvados.API, options arvados.ListOptions) ([]string, error) { options.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor cl, err := backend.CollectionList(ctx, options) if err != nil { return nil, err } mtx.Lock() defer mtx.Unlock() if len(merged.Items) == 0 { merged = cl } else if len(cl.Items) > 0 { merged.Items = app
func (conn *Conn) generated_CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) { var mtx sync.Mutex var merged arvados.CollectionList var needSort atomic.Value needSort.Store(false) err := conn.splitListRequest(ctx, options, func(ctx context.Context, _ string, backend arvados.API, options arvados.ListOptions) ([]string, error) { options.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor cl, err := backend.CollectionList(ctx, options) if err != nil { return nil, err } mtx.Lock() defer mtx.Unlock() if len(merged.Items) == 0 { merged = cl } else if len(cl.Items) > 0 { merged.Items = append(merged.Items, cl.Items...) needSort.Store(true) } uuids := make([]string, 0, len(cl.Items)) for _, item := range cl.Items { uuids = append(uuids, item.UUID) } return uuids, nil }) if needSort.Load().(bool) { // Apply the default/implied order, "modified_at desc" sort.Slice(merged.Items, func(i, j int) bool { mi, mj := merged.Items[i].ModifiedAt, merged.Items[j].ModifiedAt return mj.Before(mi) }) } if merged.Items == nil { // Return empty results as [], not null // (https://github.com/golang/go/issues/27589 might be // a better solution in the future) merged.Items = []arvados.Collection{} } return merged, err }
52,379
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: events_test.go path of file: ./repos/evmos/precompiles/distribution the code of the file until where you have to start completion: package distribution_test import ( "math/big" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/crypto" cmn "github.com/evmos/evmos/v16/precompiles/common" "github.com/evmos/evmos/v16/precompiles/distribution" "github.com/evmos/evmos/v16/utils" ) func (s *PrecompileTestSuite) TestSetWithdrawAddressEvent() { method := s.precompile.Methods[distribution.SetWithdrawAddressMethod] testCases := []struct { name string malleate func(operatorAddress string) []interface{} postCheck func() gas uint64 expError bool errContains string }{ { "success - the correct event is emitted", func(string) []interface{} { return []interface{}{ s.address, s.address.String(), } }, func() { log := s.stateDB.Logs()[0] s.Require().Equal(log.Address, s.precompile.Address()) // Check event signature matches the one emitted event := s.precompile.ABI.Events[distribution.EventTypeSetWithdrawAddress] s.Require().Equal(crypto.Keccak256Hash([]byte(event.Sig)), common.HexToHash(log.Topics[0].Hex())) s.Require().Equal(log.BlockNumber, uint64(s.ctx.BlockHeight())) // Check the fully unpacked event matches the one emitted var setWithdrawerAddrEvent distribution.EventSetWithdrawAddress err := cmn.UnpackLog(s.precompile.ABI, &setWithdrawerAddrEvent, distribution.EventTypeSetWithdrawAddress, *log) s.Require().NoError(err) s.Require().Equal(s.address, setWithdrawerAddrEvent.Caller)
func (s *PrecompileTestSuite) TestSetWithdrawAddressEvent() { method := s.precompile.Methods[distribution.SetWithdrawAddressMethod] testCases := []struct { name string malleate func(operatorAddress string) []interface{} postCheck func() gas uint64 expError bool errContains string }{ { "success - the correct event is emitted", func(string) []interface{} { return []interface{}{ s.address, s.address.String(), } }, func() { log := s.stateDB.Logs()[0] s.Require().Equal(log.Address, s.precompile.Address()) // Check event signature matches the one emitted event := s.precompile.ABI.Events[distribution.EventTypeSetWithdrawAddress] s.Require().Equal(crypto.Keccak256Hash([]byte(event.Sig)), common.HexToHash(log.Topics[0].Hex())) s.Require().Equal(log.BlockNumber, uint64(s.ctx.BlockHeight())) // Check the fully unpacked event matches the one emitted var setWithdrawerAddrEvent distribution.EventSetWithdrawAddress err := cmn.UnpackLog(s.precompile.ABI, &setWithdrawerAddrEvent, distribution.EventTypeSetWithdrawAddress, *log) s.Require().NoError(err) s.Require().Equal(s.address, setWithdrawerAddrEvent.Caller) s.Require().Equal(sdk.MustBech32ifyAddressBytes("evmos", s.address.Bytes()), setWithdrawerAddrEvent.WithdrawerAddress) }, 20000, false, "", }, } for _, tc := range testCases { s.SetupTest() contract := vm.NewContract(vm.AccountRef(s.address), s.precompile, big.NewInt(0), tc.gas) s.ctx = s.ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) initialGas := s.ctx.GasMeter().GasConsumed() s.Require().Zero(initialGas) _, err := s.precompile.SetWithdrawAddress(s.ctx, s.address, contract, s.stateDB, &method, tc.malleate(s.validators[0].OperatorAddress)) if tc.expError { s.Require().Error(err) s.Require().Contains(err.Error(), tc.errContains) } else { s.Require().NoError(err) tc.postCheck() } } }
479,593
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.rs path of file: ./repos/electrs/src the code of the file until where you have to start completion: use anyhow::{Context, Result}; use crossbeam_channel::{select, unbounded, Sender}; use rayon::prelude::*; use std::{ collections::hash_map::
fn send(&mut self, values: Vec<String>) -> Result<()> { for mut value in values { debug!("{}: send {}", self.id, value); value += "\n"; self.stream .write_all(value.as_bytes()) .with_context(|| format!("failed to send response: {:?}", value))?; } Ok(()) }
59,683
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: 20170109120109_create_web_settings.rb path of file: ./repos/mastodon/db/migrate the code of the file until where you have to start completion: # frozen_string_literal: true class CreateWebSettings < ActiveRecord::Migra
def change create_table :web_settings do |t| t.integer :user_id t.json :data t.timestamps end add_index :web_settings, :user_id, unique: true end
731,312
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: advrefs.go path of file: ./repos/devspace/vendor/gopkg.in/src-d/go-git.v4/plumbing/protocol/packp the code of the file until where you have to start completion: package packp import ( "fmt" "sort" "strings" "gopkg.in/
func (a *AdvRefs) AddReference(r *plumbing.Reference) error { switch r.Type() { case plumbing.SymbolicReference: v := fmt.Sprintf("%s:%s", r.Name().String(), r.Target().String()) a.Capabilities.Add(capability.SymRef, v) case plumbing.HashReference: a.References[r.Name().String()] = r.Hash() default: return plumbing.ErrInvalidType } return nil }
469,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: writer.go path of file: ./repos/octant/vendor/github.com/sirupsen/logrus the code of the file until where you have to start completion: package logrus import ( "bufio" "io" "runtime" ) // Writer at INFO level. See WriterLevel for details. func (logger *Logger) Writer() *io.PipeWriter {
func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { scanner := bufio.NewScanner(reader) for scanner.Scan() { printFunc(scanner.Text()) } if err := scanner.Err(); err != nil { entry.Errorf("Error while reading from Writer: %s", err) } reader.Close() }
196,526
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: accepts_for_support.rb path of file: ./repos/babushka/spec/babushka the code of the file until where you have to start completion: class AcceptsForTest include Babushka::AcceptsListFor include Babushka::AcceptsValueFor attr_reade
def test_list_lambdas { proc{ } => [], proc{ via :apt, %w[ruby irb ri rdoc] } => [], proc{ via :brew, 'ruby' via :apt, %w[ruby irb ri rdoc] } => ['ruby'], proc{ via :brew, 'something else' via :apt, 'some apt packages' } => ['something else'] } end
413,172
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: gamma_test.go path of file: ./repos/imageserver/http/gamma the code of the file until where you have to start completion: package gamma import ( "net/http" "testing" "github.com/pierrre/imageserver" imageserver_http "github.com/pierrre/imageserver/http" ) var _ imageserver_http.Parser = &CorrectionParser{} fu
func TestCorrectionParserParse(t *testing.T) { parser := &CorrectionParser{} req, err := http.NewRequest("GET", "http://localhost?gamma_correction=true", nil) if err != nil { t.Fatal(err) } params := imageserver.Params{} err = parser.Parse(req, params) if err != nil { t.Fatal(err) } res, err := params.GetBool("gamma_correction") if err != nil { t.Fatal(err) } if !res { t.Fatalf("unexpected result: got %t, want %t", res, true) } }
80,126
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: register.go path of file: ./repos/meshery/server/models/pattern/core the code of the file until where you have to start completion: package core import ( "context" "encoding/json" "fmt" "strings" "sync" "cuelang.org/go/cue" "cuelang.org/go/cue/cuecontext" cueJson "cuelang.org/go/encoding/json" "github.com/layer5io/meshery/server/internal/store" "github.com/layer5io/meshkit/models/oam/core/v1alpha1" "github.com/layer5io/meshkit/utils/kubernetes" "github.com/layer5io/meshkit/utils/manifests" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type genericCapability struct { ID string `json:"id,omitempty"` // OAMRefSchema is the json schema for the workload OAMRefSchema string `json:"oam_ref_schema,omitempty"` // Host is the address of the grpc service registering the capability Host string `json:"host,omitempty"` Restricted bool `json:"restricted,omitempty"` Metadata map[string]string `json:"metadata,omitempty"` } // TraitCapability is the struct for capturing the workload definition // of a particular type type TraitCapability struct { OAMDefinition v1alpha1.TraitDefinition `json:"oam_definition,omitempty"` genericCapability } // SetID sets the ID of the capability func (cap *genericCapability) SetID(id string) { cap.ID = id } // GetID returns the ID of the capability func (cap *genericCapability) GetID() string { return cap.ID } // WorkloadCapability is the struct for capturing the workload definition // of a particular type type WorkloadCapability struct { OAMDefinition v1alpha1.WorkloadDefinition `json:"oam_definition,omitempty"` genericCapability } // present in metadata."adapter.meshery.io/name". Ex- core,kubernetes,istio,linkerd,etc type ComponentTypes struct { Names map[string]bool LatestVersionForComponent map[string]string mx sync.Mutex } func (c *ComponentTypes) Set(name string) { c.mx.Lock() defer c.mx.Unlock() c.Names[name] = true } func (c *ComponentTypes) SetLatestVersion(typ string, ver string) { c.mx.Lock() defer c.mx.Unlock() c.LatestVersionForComponent[typ] = ver } func (c *ComponentTypes) Get() (names []string) { for n := range c.Names { names = append(names, n) } return } // ComponentTypesSingleton is initialized per meshery instance and acts as a helper middleware between client facing API and capability registry. // Examples of names stored in this struct are: core,kubernetes,istio,linkerd var ComponentTypesSingleton = ComponentTypes{ Names: make(map[string]bool), LatestVersionForComponent: make(map[string]string), } const customResourceKey = "isCustomResource" type crd struct { Items []crdhelper `json:"items"` } type crdhelper struct { Metadata map[string]interface{} `json:"metadata"` } // GetK8Components returns all the generated definitions and schemas for available api resources func GetK8Components(ctxt context.Context, config []byte) (*manifests.Component, error) { cli, err := kubernetes.New(config) if err != nil { return nil, ErrGetK8sComponents(err) } req := cli.KubeClient.RESTClient().Get().RequestURI("/openapi/v2") k8version, err := cli.KubeClient.ServerVersion() if err != nil { return nil, ErrGetK8sComponents(err) } var customResources = make(map[string]bool) crdresult, err := cli.KubeClient.RESTClient().Get().RequestURI("/apis/apiextensions.k8s.io/v1/customresourcedefinitions").Do(context.Background()).Raw() if err != nil { r
func GetK8Components(ctxt context.Context, config []byte) (*manifests.Component, error) { cli, err := kubernetes.New(config) if err != nil { return nil, ErrGetK8sComponents(err) } req := cli.KubeClient.RESTClient().Get().RequestURI("/openapi/v2") k8version, err := cli.KubeClient.ServerVersion() if err != nil { return nil, ErrGetK8sComponents(err) } var customResources = make(map[string]bool) crdresult, err := cli.KubeClient.RESTClient().Get().RequestURI("/apis/apiextensions.k8s.io/v1/customresourcedefinitions").Do(context.Background()).Raw() if err != nil { return nil, ErrGetK8sComponents(err) } var xcrd crd err = json.Unmarshal(crdresult, &xcrd) if err != nil { return nil, ErrGetK8sComponents(err) } for _, item := range xcrd.Items { customResources[item.Metadata["name"].(string)] = true } res := req.Do(context.Background()) content, err := res.Raw() if err != nil { return nil, ErrGetK8sComponents(err) } apiResources, err := getAPIRes(cli) if err != nil { return nil, ErrGetK8sComponents(err) } var arrAPIResources []string for res := range apiResources { arrAPIResources = append(arrAPIResources, res) } groups, err := getGroupsFromResource(cli) //change this if err != nil { return nil, err } manifest := string(content) man, err := manifests.GenerateComponents(ctxt, manifest, manifests.K8s, manifests.Config{ Name: "Kubernetes", CrdFilter: manifests.NewCueCrdFilter(manifests.ExtractorPaths{ NamePath: `"x-kubernetes-group-version-kind"[0].kind`, IdPath: `"x-kubernetes-group-version-kind"[0].kind`, VersionPath: `"x-kubernetes-group-version-kind"[0].version`, GroupPath: `"x-kubernetes-group-version-kind"[0].group`, SpecPath: "", }, true), ExtractCrds: func(manifest string) []string { crds := make([]string, 0) cuectx := cuecontext.New() cueParsedManExpr, err := cueJson.Extract("", []byte(manifest)) parsedManifest := cuectx.BuildExpr(cueParsedManExpr) definitions := parsedManifest.LookupPath(cue.ParsePath("definitions")) if err != nil { fmt.Printf("%v", err) return nil } for _, resource := range arrAPIResources { resource = strings.ToLower(resource) fields, err := definitions.Fields() if err != nil { fmt.Printf("%v\n", err) continue } for fields.Next() { fieldVal := fields.Value() kindCue := fieldVal.LookupPath(cue.ParsePath(`"x-kubernetes-group-version-kind"[0].kind`)) if kindCue.Err() != nil { continue } kind, err := kindCue.String() kind = strings.ToLower(kind) if err != nil { fmt.Printf("%v", err) continue } if kind == resource { crd, err := fieldVal.MarshalJSON() if err != nil { fmt.Printf("%v", err) continue } crds = append(crds, string(crd)) } } } return crds }, K8sVersion: k8version.String(), ModifyDefSchema: func(s1, s2 *string) { //s1 is the definition and s2 is the schema var schema map[string]interface{} err = json.Unmarshal([]byte(*s2), &schema) if err != nil { return } prop, ok := schema["properties"].(map[string]interface{}) if !ok { return } var def v1alpha1.WorkloadDefinition err := json.Unmarshal([]byte(*s1), &def) if err != nil { return } //Add additional info in metadata like whether the resource is namespaced or not. Or whether it is a custom resource. kind := strings.TrimSuffix(def.Spec.Metadata["k8sKind"], ".K8s") if apiResources[kind].Namespaced { def.Spec.Metadata["namespaced"] = "true" } else { def.Spec.Metadata["namespaced"] = "false" } def.Spec.Metadata[customResourceKey] = "false" //default for cr := range customResources { if groups[kind][cr] { def.Spec.Metadata[customResourceKey] = "true" break } } b, err := json.Marshal(def) if err != nil { return } *s1 = string(b) // The schema generated has few fields that are not required and can break things, so they are removed here delete(prop, "apiVersion") delete(prop, "metadata") delete(prop, "kind") delete(prop, "status") schema["properties"] = prop schema["$schema"] = "http://json-schema.org/draft-07/schema" b, err = json.Marshal(schema) if err != nil { return } cuectx := cuecontext.New() cueParsedManExpr, err := cueJson.Extract("", []byte(manifest)) if err != nil { return } parsedManifest := cuectx.BuildExpr(cueParsedManExpr) definitions := parsedManifest.LookupPath(cue.ParsePath("definitions")) referenceResolver := manifests.ResolveOpenApiRefs{} cache := make(map[string][]byte) newResRef, err := referenceResolver.ResolveReferences(b, definitions, cache) if err != nil { return } b, _ = json.Marshal(newResRef) resolved := make(map[string]interface{}) err = json.Unmarshal(b, &resolved) if err != nil { return } b, err = json.Marshal(resolved) if err != nil { return } *s2 = string(b) }, }) if err != nil { return nil, ErrGetK8sComponents(err) } return man, nil }
179,769
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: process_collector_windows.go path of file: ./repos/docker-ce/components/cli/vendor/github.com/prometheus/client_golang/prometheus the code of the file until where you have to start completion: // Copyright 2019 The Prometheus 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
func getProcessHandleCount(handle windows.Handle) (uint32, error) { var count uint32 r1, _, err := procGetProcessHandleCount.Call( uintptr(handle), uintptr(unsafe.Pointer(&count)), ) if r1 != 1 { return 0, err } else { return count, nil } }
568,947
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: impl.rs path of file: ./repos/windows-rs/crates/libs/windows/src/Windows/Win32/System/Diagnostics/Etw the code of the file until where you have to start completion: pub trait ITraceEvent_Impl: Sized { fn Clone(&self) -> windows_core::Result<ITraceEvent>; fn GetUserContext(&self) -> windows_core::Result<
pub const fn new<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>() -> ITraceRelogger_Vtbl { unsafe extern "system" fn AddLogfileTraceStream<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void, logfilename: std::mem::MaybeUninit<windows_core::BSTR>, usercontext: *const core::ffi::c_void, tracehandle: *mut RELOGSTREAM_HANDLE) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); match this.AddLogfileTraceStream(core::mem::transmute(&logfilename), core::mem::transmute_copy(&usercontext)) { Ok(ok__) => { core::ptr::write(tracehandle, core::mem::transmute(ok__)); windows_core::HRESULT(0) } Err(err) => err.into(), } } unsafe extern "system" fn AddRealtimeTraceStream<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void, loggername: std::mem::MaybeUninit<windows_core::BSTR>, usercontext: *const core::ffi::c_void, tracehandle: *mut RELOGSTREAM_HANDLE) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); match this.AddRealtimeTraceStream(core::mem::transmute(&loggername), core::mem::transmute_copy(&usercontext)) { Ok(ok__) => { core::ptr::write(tracehandle, core::mem::transmute(ok__)); windows_core::HRESULT(0) } Err(err) => err.into(), } } unsafe extern "system" fn RegisterCallback<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void, callback: *mut core::ffi::c_void) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); this.RegisterCallback(windows_core::from_raw_borrowed(&callback)).into() } unsafe extern "system" fn Inject<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void, event: *mut core::ffi::c_void) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); this.Inject(windows_core::from_raw_borrowed(&event)).into() } unsafe extern "system" fn CreateEventInstance<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void, tracehandle: RELOGSTREAM_HANDLE, flags: u32, event: *mut *mut core::ffi::c_void) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); match this.CreateEventInstance(core::mem::transmute(&tracehandle), core::mem::transmute_copy(&flags)) { Ok(ok__) => { core::ptr::write(event, core::mem::transmute(ok__)); windows_core::HRESULT(0) } Err(err) => err.into(), } } unsafe extern "system" fn ProcessTrace<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); this.ProcessTrace().into() } unsafe extern "system" fn SetOutputFilename<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void, logfilename: std::mem::MaybeUninit<windows_core::BSTR>) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); this.SetOutputFilename(core::mem::transmute(&logfilename)).into() } unsafe extern "system" fn SetCompressionMode<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void, compressionmode: super::super::super::Foundation::BOOLEAN) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); this.SetCompressionMode(core::mem::transmute_copy(&compressionmode)).into() } unsafe extern "system" fn Cancel<Identity: windows_core::IUnknownImpl<Impl = Impl>, Impl: ITraceRelogger_Impl, const OFFSET: isize>(this: *mut core::ffi::c_void) -> windows_core::HRESULT { let this = (this as *const *const ()).offset(OFFSET) as *const Identity; let this = (*this).get_impl(); this.Cancel().into() } Self { base__: windows_core::IUnknown_Vtbl::new::<Identity, OFFSET>(), AddLogfileTraceStream: AddLogfileTraceStream::<Identity, Impl, OFFSET>, AddRealtimeTraceStream: AddRealtimeTraceStream::<Identity, Impl, OFFSET>, RegisterCallback: RegisterCallback::<Identity, Impl, OFFSET>, Inject: Inject::<Identity, Impl, OFFSET>, CreateEventInstance: CreateEventInstance::<Identity, Impl, OFFSET>, ProcessTrace: ProcessTrace::<Identity, Impl, OFFSET>, SetOutputFilename: SetOutputFilename::<Identity, Impl, OFFSET>, SetCompressionMode: SetCompressionMode::<Identity, Impl, OFFSET>, Cancel: Cancel::<Identity, Impl, OFFSET>, } }
66,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: move_lateral_test.go path of file: ./repos/ov/oviewer the code of the file until where you have to start completion: package oviewer import ( "path/filepath" "reflect" "regexp" "testing" ) func TestDocument_moveBeginLeft(t *testing.T) { tests := []struct { name string wantX int }{ { name:
func TestDocument_optimalCursor(t *testing.T) { type fields struct { fileName string wrap bool columnDelimiter string x int width int } type args struct { cursor int } tests := []struct { name string fields fields args args want int }{ { name: "noDelimiter", fields: fields{ fileName: filepath.Join(testdata, "normal.txt"), wrap: true, }, args: args{cursor: 10}, want: 10, }, { name: "CSVRight", fields: fields{ fileName: filepath.Join(testdata, "MOCK_DATA.csv"), columnDelimiter: ",", x: 10, width: 10, }, args: args{cursor: 4}, want: 2, }, { name: "CSVLeft", fields: fields{ fileName: filepath.Join(testdata, "MOCK_DATA.csv"), columnDelimiter: ",", x: 30, width: 10, }, args: args{cursor: 0}, want: 4, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m, err := OpenDocument(tt.fields.fileName) if err != nil { t.Fatal(err) } m.WrapMode = tt.fields.wrap m.ColumnDelimiter = tt.fields.columnDelimiter m.x = tt.fields.x m.width = tt.fields.width for !m.BufEOF() { } if got := m.optimalCursor(tt.args.cursor); got != tt.want { t.Errorf("Document.correctCursor() = %v, want %v", got, tt.want) } }) } }
120,200
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: switch.go path of file: ./repos/golang-for-nodejs-developers/examples the code of the file until where you have to start completion: package main import "fmt" func main() { value := "b" switch value { case "a": fmt.Println("A") case "b": fmt.Println("B") case "c": fmt.Println("C") default: fmt.
func main() { value := "b" switch value { case "a": fmt.Println("A") case "b": fmt.Println("B") case "c": fmt.Println("C") default: fmt.Println("first default") } switch value { case "a": fmt.Println("A - falling through") fallthrough case "b": fmt.Println("B - falling through") fallthrough case "c": fmt.Println("C - falling through") fallthrough default: fmt.Println("second default") } }
179,446
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: util.go path of file: ./repos/corteza/server/vendor/github.com/go-oauth2/oauth2/v4/manage the code of the file until where you have to start completion: package manage import ( "net/url" "strings" "github.com/go-oaut
func DefaultValidateURI(baseURI string, redirectURI string) error { base, err := url.Parse(baseURI) if err != nil { return err } redirect, err := url.Parse(redirectURI) if err != nil { return err } if !strings.HasSuffix(redirect.Host, base.Host) { return errors.ErrInvalidRedirectURI } return nil }
543,225
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: mod.rs path of file: ./repos/hash/libs/@local/hash-authorization/src/backend/spicedb the code of the file until where you have to start completion: mod api; mod model; pub(crate) mod serde; use std::fmt; use error_stack::Result; pub use self::
pub fn new(base_path: impl Into<String>, key: Option<&str>) -> Result<Self, reqwest::Error> { Ok(Self { base_path: base_path.into(), client: reqwest::Client::builder() .default_headers({ let mut headers = reqwest::header::HeaderMap::new(); if let Some(key) = key { headers.insert( reqwest::header::AUTHORIZATION, reqwest::header::HeaderValue::from_str(&format!("Bearer {key}")) .expect("failed to create header value"), ); } headers }) .build()?, }) }
639,980
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: Solution_test.go path of file: ./repos/awesome-golang-algorithm/leetcode/2001-2100/2054.Two-Best-Non-Overlapping-Events the code of the file until where you have to start completion: package Solution import ( "reflect" "strconv" "testing" ) func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string inputs bool expect bool }{ {"TestCase", true, true}, {"TestCase", true, true}, {"Tes
func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string inputs bool expect bool }{ {"TestCase", true, true}, {"TestCase", true, true}, {"TestCase", false, false}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { got := Solution(c.inputs) if !reflect.DeepEqual(got, c.expect) { t.Fatalf("expected: %v, but got: %v, with inputs: %v", c.expect, got, c.inputs) } }) } }
187,578
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: defaults.go path of file: ./repos/kubeedge/vendor/k8s.io/kubernetes/pkg/apis/policy/v1beta1 the code of the file until where you have to start completion: /* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in com
func SetDefaults_PodSecurityPolicySpec(obj *policyv1beta1.PodSecurityPolicySpec) { // This field was added after PodSecurityPolicy was released. // Policies that do not include this field must remain as permissive as they were prior to the introduction of this field. if obj.AllowPrivilegeEscalation == nil { t := true obj.AllowPrivilegeEscalation = &t } }
417,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: list_service_terminators_responses.go path of file: ./repos/ziti/controller/rest_server/operations/service the code of the file until where you have to start completion: // Code generated by go-swagger; DO NOT EDIT. // // Copyright NetFoundry Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file
func (o *ListServiceTerminatorsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(400) if o.Payload != nil { payload := o.Payload if err := producer.Produce(rw, payload); err != nil { panic(err) // let the recovery middleware deal with this } } }
642,405
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: comment_on_table.go path of file: ./repos/cockroach/pkg/sql/sem/tree the code of the file until where you have to start completion: // Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in acc
func (n *CommentOnTable) Format(ctx *FmtCtx) { ctx.WriteString("COMMENT ON TABLE ") ctx.FormatNode(n.Table) ctx.WriteString(" IS ") if n.Comment != nil { // TODO(knz): Replace all this with ctx.FormatNode // when COMMENT supports expressions. if ctx.flags.HasFlags(FmtHideConstants) { ctx.WriteString("'_'") } else { lexbase.EncodeSQLStringWithFlags(&ctx.Buffer, *n.Comment, ctx.flags.EncodeFlags()) } } else { ctx.WriteString("NULL") } }
704,459
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: environments_spec.rb path of file: ./repos/puppet/spec/unit the code of the file until where you have to start completion: require 'spec_helper' require 'puppet/environments' require 'puppet/file_system' describe Puppet::Environments do FS = Puppet::FileSystem module FsRemove def remove @properties[:directory?] = false @properties[:exist?] = false @properties[:executable?] = false
def with_environment_loaded(service, &block) loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader| using_expiration_service(service) do cached = Puppet::Environments::Cached.new(loader) cached.get!(:an_environment) yield cached if block_given? end end end
600,441
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: PodClient.go path of file: ./repos/rancher/pkg/catalogv2/system/mocks the code of the file until where you have to start completion: // Code generated by mockery v2.30.16. DO NOT EDIT. package mocks import ( generic "github.com/ranc
func NewPodClient(t interface { mock.TestingT Cleanup(func()) }) *PodClient { mock := &PodClient{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) return mock }
681,082
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/learning_tools/grpc/simple_rpc the code of the file until where you have to start completion: package main import ( "fmt" "golang.org/x/net/context" "google.golang.org/grpc" pr "learning_tools/grpc/etcd-grpc/
func main() { listener, err := net.Listen("tcp", ":8099") if err != nil { log.Panic(err) } g := grpc.NewServer() pr.RegisterHowieServer(g, &Server{}) fmt.Println("GRPC 启动成功") g.Serve(listener) }
168,599
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: config.rb path of file: ./repos/timber-ruby/lib/timber the code of the file until where you have to start completion: require "logger" require "singleton" module Timber # Singleton class for reading and setting Timber configuration. # #
def debug_to_file!(file_path) FileUtils.mkdir_p( File.dirname(file_path) ) file = File.open(file_path, "ab") file_logger = ::Logger.new(file) file_logger.formatter = SimpleLogFormatter.new self.debug_logger = file_logger end
309,155
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: google_spreadsheets.rs path of file: ./repos/roapi/columnq/src/table the code of the file until where you have to start completion: use std::collections::{HashMap, HashSe
fn sheetvalue_to_record_batch() { let sheet = property_sheet(); let batch = sheet_values_to_record_batch(&sheet.values).unwrap(); assert_eq!(batch.num_columns(), 9); assert_eq!( batch.column(3).as_ref(), Arc::new(Int64Array::from(vec![3, 3, 5, 1])).as_ref(), ); assert_eq!( batch.column(5).as_ref(), Arc::new(BooleanArray::from(vec![false, true, false, true])).as_ref(), ); assert_eq!( batch.column(2).as_ref(), Arc::new(StringArray::from(vec!["Roger", "Sam", "Daniel", "Roger"])).as_ref(), ); }
62,010
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: query.go path of file: ./repos/wechat/pay/order the code of the file until where you have to start completion: package order import ( "encoding/xml" "errors" "github.com/silenceper/wechat/v2/pay/notify" "github.com/silenceper/wechat/v2/util" ) var queryGateway = "https://api.mch.weixin.qq.com/pay/orderquery" // QueryParams 传入的参数 type QueryParams struct { OutTradeNo string // 商户订单号 SignType string // 签名类型 TransactionID string // 微信订单号 } // queryRequest 接口请求参数 type queryRequest struct { AppID string `xml:"appid"` // 公众账号ID MchID string `xml:"mch_id"` // 商户号 NonceStr string `xml:"nonce_str"` // 随机字符串 Sign string `xml:"sign"` // 签名 SignType string `xml:"sign_type,omitempty"` // 签名类型 TransactionID string `xml:"transaction_id"` // 微信订单号 OutTradeNo stri
func (o *Order) QueryOrder(p *QueryParams) (paidResult notify.PaidResult, err error) { nonceStr := util.RandomStr(32) // 签名类型 if p.SignType == "" { p.SignType = "MD5" } params := make(map[string]string) params["appid"] = o.AppID params["mch_id"] = o.MchID params["nonce_str"] = nonceStr params["out_trade_no"] = p.OutTradeNo params["sign_type"] = p.SignType params["transaction_id"] = p.TransactionID sign, err := util.ParamSign(params, o.Key) if err != nil { return } request := queryRequest{ AppID: o.AppID, MchID: o.MchID, NonceStr: nonceStr, Sign: sign, OutTradeNo: p.OutTradeNo, TransactionID: p.TransactionID, SignType: p.SignType, } rawRet, err := util.PostXML(queryGateway, request) if err != nil { return } err = xml.Unmarshal(rawRet, &paidResult) if err != nil { return } if *paidResult.ReturnCode == SUCCESS { // query success if *paidResult.ResultCode == SUCCESS { err = nil return } err = errors.New(*paidResult.ErrCode + *paidResult.ErrCodeDes) return } err = errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [sign : " + sign + "]") return }
428,938
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: task.go path of file: ./repos/bzppx-codepub/app/remotes the code of the file until where you have to start completion: package remotes import ( "encoding/json" "strconv" "bzppx-codepub/app/models" "time" ) var Task = TaskRemote{} const ( Rpc_Task_Service = "ServiceTask" Rpc_Task_Method_Publish = Rpc_Task_Service+".Publish" Rpc_Task_Method_GetStatus = Rpc_Task_Service+".Status" Rpc_Task_Method_Delete = Rpc_Task_Service+".Delete" ) type TaskRemote struct { BaseRemote } // 发布 func (this *TaskRemote) Publish(ip string, port string, token string, args map[string]interface{}) error { _, err := this.Call(ip, port, token, Rpc_Task_Method_Publish, args, Conn_Timeout) return err } // 获取节点执行结果 func (this *TaskRemote) GetResults(
func (this *TaskRemote) GetResults(ip string, port string, token string, args map[string]interface{}) (bool, error) { replay, err := this.Call(ip, port, token, Rpc_Task_Method_GetStatus, args, Conn_Timeout) if err != nil { return false, err } res := map[string]string{} json.Unmarshal([]byte(replay), &res) // 任务执行完成 if res["status"] == strconv.Itoa(models.TASKLOG_STATUS_FINISH) { taskLogId := args["task_log_id"].(string) taskLogValue := map[string]interface{}{ "status": res["status"], "is_success": res["is_success"], "result": res["result"], "commit_id": res["commit_id"], "update_time": time.Now().Unix(), } _, err := models.TaskLogModel.Update(taskLogId, taskLogValue) if err != nil { return false, err } // 删除 agent _, err = this.Call(ip, port, token, Rpc_Task_Method_Delete, args, Conn_Timeout) return true, nil } else { return false, nil } }
403,674
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: mirror.rb path of file: ./repos/ruby-packer/ruby/lib/bundler the code of the file until where you have to start completion: # frozen_string_literal: true require "socket" module Bundler class Settings # Class used to build the mirror set and then find a mirror for a given URI # # @param prober [Prober object, nil] by default a TCPSocketProbe, this object # will be used
def any? @addresses.any? do |address| socket = Socket.new(Socket.const_get(address.type), Socket::SOCK_STREAM, 0) socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) value = yield socket, address.to_socket_address, @timeout socket.close unless socket.closed? value end end
750,244
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: register.go path of file: ./repos/octant/vendor/k8s.io/api/discovery/v1 the code of the file until where you have to start completion: /* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (th
func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &EndpointSlice{}, &EndpointSliceList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
198,106
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: _201_bitwise_and_of_numbers_range.rs path of file: ./repos/rustgym/leetcode/src/d2 the code of the file until where you have to start completion: struct Solut
fn test() { let m = 5; let n = 7; let res = 4; assert_eq!(Solution::range_bitwise_and(m, n), res); let m = 0; let n = 1; let res = 0; assert_eq!(Solution::range_bitwise_and(m, n), res); }
71,256
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: atom.rb path of file: ./repos/brew/Library/Homebrew/vendor/bundle-standalone/ruby/2.3.0/gems/concurrent-ruby-1.1.4/lib/concurrent the code of the file until where you have to start completion: require 'concurrent/atomic/atomic_reference' require 'concurrent/collection/copy_on_notify_observer_set
def swap(*args) raise ArgumentError.new('no block given') unless block_given? loop do old_value = value new_value = yield(old_value, *args) begin break old_value unless valid?(new_value) break new_value if compare_and_set(old_value, new_value) rescue break old_value end end
18,097
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: metadata.rb path of file: ./repos/heroku-buildpack-ruby/lib/language_pack the code of the file until where you have to start completion: require "language_pack" require "language_pack/base" c
def fetch(key) return read(key) if exists?(key) value = yield write(key, value.to_s) return value end
86,723
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: metadata_clear.go path of file: ./repos/graphql-engine/cli/commands the code of the file until where you have to start completion: package commands import ( "fmt" "github.com/hasura/graphql-engine/cli/v2" "github.com/hasura/graphql-engine/cli/v2/internal/errors" "github.com/hasura/graphql-engine/cli/v2/internal/projectmetadata" "github.com/spf13/cobra" ) func newMetadataClearCmd(ec *cli.ExecutionContext) *cobra.Command { opts := &MetadataClearOptions{ EC: ec, } metadataResetCmd := &cobra.Command{ Use: "clear", Aliases: []string{"reset"}, Short: "Clear Hasura GraphQL Engine Metadata on the database", Long: "This command a
func newMetadataClearCmd(ec *cli.ExecutionContext) *cobra.Command { opts := &MetadataClearOptions{ EC: ec, } metadataResetCmd := &cobra.Command{ Use: "clear", Aliases: []string{"reset"}, Short: "Clear Hasura GraphQL Engine Metadata on the database", Long: "This command allows you to clear the Hasura GraphQL Engine Metadata. Passing in the `--endpoint` flag will clear the Hasura Metadata on the HGE instance specified by the endpoint.", Example: ` # Clear all the metadata information from database: hasura metadata clear # Use with admin secret: hasura metadata clear --admin-secret "<admin-secret>" # Clear metadata on a different Hasura instance: hasura metadata clear --endpoint "<endpoint>"`, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { op := genOpName(cmd, "RunE") if cmd.CalledAs() == "reset" { opts.EC.Logger.Warn("metadata reset command is deprecated, use metadata clear instead") } opts.EC.Spin("Clearing metadata...") err := opts.Run() opts.EC.Spinner.Stop() if err != nil { return errors.E(op, fmt.Errorf("failed to clear metadata: %w", err)) } opts.EC.Logger.Info("Metadata cleared") return nil }, } return metadataResetCmd }
115,332
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: openldap.rb path of file: ./repos/homebrew-core/Formula/o the code of the file until where you have to start completion: class Openldap < Formula desc "Open source suite of directory software" homepage "https://www.openldap.org/software/" url "https://www.openldap.org/software/download/OpenLDAP/openldap-release/openldap-2.6.7.tgz" mirror "http://fresh-center.net/linux/misc/openldap-2.6.7.tgz" mirror "http://fresh-center.net/linux/misc/legacy/openldap-2.6.7.tgz" sha256 "cd775f625c944ed78a3da18a03b03b08e
def install args = %W[ --disable-dependency-tracking --prefix=#{prefix} --sysconfdir=#{etc} --localstatedir=#{var} --enable-accesslog --enable-auditlog --enable-bdb=no --enable-constraint --enable-dds --enable-deref --enable-dyngroup --enable-dynlist --enable-hdb=no --enable-memberof --enable-ppolicy --enable-proxycache --enable-refint --enable-retcode --enable-seqmod --enable-translucent --enable-unique --enable-valsort --without-systemd ] soelim = if OS.mac? if MacOS.version >= :ventura "mandoc_soelim" else "soelim" end
696,779
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: indifferent_hash.rb path of file: ./repos/ferrocarril/mruby-gems/vendor/ruby/2.6.0/gems/sinatra-2.0.5/lib/sinatra the code of the file until where you have to start completion: # frozen_string_literal: true $stderr.puts <<EOF if !Hash.method_defined?(:slice) && !$LOAD_PATH.grep(%r{gems/activesupport}).empty? && ENV['SINATRA_ACTIVESUPPORT_WARNING'] != 'false' WARNING: If you plan to load any of ActiveSupport's core extensions to Hash, be sure to do so *before* loading Sinatra::Application or Sinatra::Base. If not, you may disregard this warning. Set SINATRA_ACTIVESUPPORT_WARNING=false in the environment to hide this warning. EOF module Sinatra # A poor man's ActiveSupport::HashWithIndifferentAccess, with all the Rails-y # stuff removed. # # Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are # considered to be t
def dig(key, *other_keys) super(convert_key(key), *other_keys) end if method_defined?(:dig) # Added in Ruby 2.3 def fetch_values(*keys) keys.map!(&method(:convert_key)) super(*keys) end if method_defined?(:fetch_values) # Added in Ruby 2.3 def slice(*keys) keys.map!(&method(:convert_key)) self.class[super(*keys)] end if method_defined?(:slice) # Added in Ruby 2.5 def values_at(*keys) keys.map!(&method(:convert_key)) super(*keys) end def merge!(other_hash) return super if other_hash.is_a?(self.class) other_hash.each_pair do |key, value| key = convert_key(key) value = yield(key, self[key], value) if block_given? && key?(key) self[key] = convert_value(value) end self end alias_method :update, :merge! def merge(other_hash, &block) dup.merge!(other_hash, &block) end def replace(other_hash) super(other_hash.is_a?(self.class) ? other_hash : self.class[other_hash]) end if method_defined?(:transform_values!) # Added in Ruby 2.4 def transform_values(&block) dup.transform_values!(&block) end def transform_values! super super(&method(:convert_value)) end end if method_defined?(:transform_keys!) # Added in Ruby 2.5 def transform_keys(&block) dup.transform_keys!(&block) end def transform_keys! super super(&method(:convert_key)) end end private def convert_key(key) key.is_a?(Symbol) ? key.to_s : key end def convert_value(value) case value when Hash value.is_a?(self.class) ? value : self.class[value] when Array value.map(&method(:convert_value)) else value end end
547,762
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: inspect_pretty_test.go path of file: ./repos/docker-ce/components/cli/cli/command/trust the code of the file until where you have to start completion: package trust import ( "bytes" "context" "encoding/hex" "io" "io/ioutil" "testing" "github.com/docker/cli/cli/trust" "github.com/docker/cli/internal/test" notaryfake "github.com/docker/cli/internal/test/notary" "githu
func TestTrustInspectPrettyCommandOfflineErrors(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cmd := newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"nonexistent-reg-name.io/image"}) cmd.SetOut(ioutil.Discard) assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image") cli = test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cmd = newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"nonexistent-reg-name.io/image:tag"}) cmd.SetOut(ioutil.Discard) assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image") }
567,745
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: all_set.m path of file: ./repos/bspm/thirdparty/spm8/matlabbatch/@cfg_item the code of the file until where you have to start completion: function ok = all_set(item) % function ok = all_set(item)
function ok = all_set(item) % function ok = all_set(item) % Generic all_set function - checks whether item.val is not empty. No % checks based on the content of item.val are performed here. % Content checking is done in the following places: % * context-insensitive checks based on configuration specifications % are performed during subsasgn/setval. This will happen during user % input or while resolving depend
521,195
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_DescribeAppBlockBuilderAppBlockAssociations.go path of file: ./repos/aws-sdk-go-v2/service/appstream the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package appstream import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/service/appstream/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Retrieves a list that describes one or more app block builder associations. func (c *Client) DescribeAppBlockBuilderAppBlockAssociations(ctx context.Context, params *DescribeAppBlockBuilderAppBlockAssociationsInput, optFns ...func(*Options)) (*DescribeAppBlockBuilderAppBlockAssociationsOutput, error) { if params == nil { params = &DescribeAppBlockBuilderAppBlockAssociat
func (p *DescribeAppBlockBuilderAppBlockAssociationsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeAppBlockBuilderAppBlockAssociationsOutput, error) { if !p.HasMorePages() { return nil, fmt.Errorf("no more pages available") } params := *p.params params.NextToken = p.nextToken var limit *int32 if p.options.Limit > 0 { limit = &p.options.Limit } params.MaxResults = limit result, err := p.client.DescribeAppBlockBuilderAppBlockAssociations(ctx, &params, optFns...) if err != nil { return nil, err } p.firstPage = false prevToken := p.nextToken p.nextToken = result.NextToken if p.options.StopOnDuplicateToken && prevToken != nil && p.nextToken != nil && *prevToken == *p.nextToken { p.nextToken = nil } return result, nil }
225,653
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: endpoints_test.go path of file: ./repos/aws-sdk-go-v2/service/cognitosync the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package cognitosync import ( "context" smithy "github.com/aws/smithy-go" smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/ptr" "net/http" "net/url" "reflect" "strings" "testing" ) // For region ap-northeas
func TestEndpointCase12(t *testing.T) { var params = EndpointParameters{ Region: ptr.String("us-east-1"), UseFIPS: ptr.Bool(true), UseDualStack: ptr.Bool(false), } resolver := NewDefaultEndpointResolverV2() result, err := resolver.ResolveEndpoint(context.Background(), params) _, _ = result, err if err != nil { t.Fatalf("expect no error, got %v", err) } uri, _ := url.Parse("https://cognito-sync-fips.us-east-1.amazonaws.com") expectEndpoint := smithyendpoints.Endpoint{ URI: *uri, Headers: http.Header{}, Properties: smithy.Properties{}, } if e, a := expectEndpoint.URI, result.URI; e != a { t.Errorf("expect %v URI, got %v", e, a) } if !reflect.DeepEqual(expectEndpoint.Headers, result.Headers) { t.Errorf("expect headers to match\n%v != %v", expectEndpoint.Headers, result.Headers) } if !reflect.DeepEqual(expectEndpoint.Properties, result.Properties) { t.Errorf("expect properties to match\n%v != %v", expectEndpoint.Properties, result.Properties) } }
221,816
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: nufft1_kernel.m path of file: ./repos/CS_MoCo_LAB/reconstruction/matlab/CS_LAB_matlab/@NUFFT/private the code of the file until where you have to start completion: function kern = nufft1_kernel(klist, N, J, K, alpha, beta)
function kern = nufft1_kernel(klist, N, J, K, alpha, beta) %function kern = nufft1_kernel(klist, N, J, K, alpha, beta) % compute equivalent interpolation kernel (real part) % at points in klist if nargin < 4 help(mfilename) J = 7; N = 100; K = 2*N; k = linspace(-J/2-1,J/2+1,201)'; % fine sampling for display ker = nufft1_kernel(k, N, J, K, 1, 0); plot(k, ker), axis tight return end
61,225
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_test.go path of file: ./repos/golang-samples/asset/quickstart/analyze-org-policy-governed-assets the code of the file until where you have to start completion: // Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0
func TestAnalyzeOrgPolicyGovernedAssets(t *testing.T) { buf := new(bytes.Buffer) err := analyzeOrgPolicyGovernedAssets(buf, organization, constraint) if err != nil { t.Errorf("analyzeOrgPolicyGovernedAssets: %v", err) } got := buf.String() if !strings.Contains(got, expected_result) { t.Errorf("analyzeOrgPolicyGoverneddAssets got%q, want%q", got, expected_result) } }
536,333
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: c.go path of file: ./repos/codeforces-go/leetcode/biweekly/44/c the code of the file until where you have to start completion: package main // github.com/EndlessCheng/codeforces-go func decode(encoded []int) (ans []int) { n := len(encoded) a0 := 0 for i := 1; i <= n+1; i++ { a0 ^
func decode(encoded []int) (ans []int) { n := len(encoded) a0 := 0 for i := 1; i <= n+1; i++ { a0 ^= i } for i := 1; i < n; i += 2 { a0 ^= encoded[i] } ans = append(ans, a0) for _, v := range encoded { ans = append(ans, ans[len(ans)-1]^v) } return }
132,570
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: merge_functions.rs path of file: ./repos/meilisearch/milli/src/update/index_documents/helpers the code of the file until where you have to start completion: use std::borrow::Cow; use std::collections::BTreeSet; use std::io; use std::result::Result as StdResult; use roaring::RoaringBitmap; use crate::heed_codec::CboRoaringBitmapCodec; use crate::update::del_add::{DelAdd, KvReaderDelAdd, KvWriterDelAdd}; use crate::update::index_documents::transform::Operation; use crate::Result; pub type MergeFn = for<'a> fn(&[u8], &[Cow<'a, [u8]>]) -> Resul
pub fn merge_roaring_bitmaps<'a>(_key: &[u8], values: &[Cow<'a, [u8]>]) -> Result<Cow<'a, [u8]>> { if values.len() == 1 { Ok(values[0].clone()) } else { let merged = values .iter() .map(AsRef::as_ref) .map(RoaringBitmap::deserialize_from) .map(StdResult::unwrap) .reduce(|a, b| a | b) .unwrap(); let mut buffer = Vec::new(); serialize_roaring_bitmap(&merged, &mut buffer)?; Ok(Cow::Owned(buffer)) } }
540,148
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: moderation_tests.rb path of file: ./repos/plots2/test/system the code of the file until where you have to start completion: require "app
def setup visit "/" click_on "Login" fill_in 'user_session[username]', with: 'palpatine' fill_in 'user_session[password]', with: 'secretive' click_on "Log in" end
158,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: dao.go path of file: ./repos/teamgram-server/app/service/idgen/internal/dao the code of the file until where you have to start completion: /* * Created from 'scheme.tl' by 'mtprotoc' * * Copyright (c) 2021-present, Teamgram Studio (https://teamgram.io). * All rights
func New(c config.Config) *Dao { var ( err error d = new(Dao) ) d.Node, err = snowflake.NewNode(c.NodeId) if err != nil { log.Fatal("new snowflake node error: ", err) } d.KV = kv.NewStore(c.SeqIDGen) return d }
83,456
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: aamod_biascorrect_ANTS.m path of file: ./repos/automaticanalysis/aa_modules the code of the file until where you have to start completion: % AA module % Use the Anatomical Transformation Toolbox to normalise the structural to % a template image function [aap,resp]=aamod_biascorrect_ANTS(aap,task,subj) resp=''; switch task case 'doit' %% Get image to bias correct % Find out what stream we should use inputstream = aap.tasklist.currenttask.inputstreams.stream; % And the names of the output streams outputstream = aap.tasklist.currenttask.outputstreams.stream; % Let us get the image we want to bias correct... Simg = aas_getfiles_bystream(aap,subj,inputstream{:}); %% Use ANTS to bias correct them % Set the ANTS path setenv('ANTSPATH', aap.directory_convention
function [aap,resp]=aamod_biascorrect_ANTS(aap,task,subj) resp=''; switch task case 'doit' %% Get image to bias correct % Find out what stream we should use inputstream = aap.tasklist.currenttask.inputstreams.stream; % And the names of the output streams outputstream = aap.tasklist.currenttask.outputstreams.stream; % Let us get the image we want to bias correct... Simg = aas_getfiles_bystream(aap,subj,inputstream{:}); %% Use ANTS to bias correct them % Set the ANTS path setenv('ANTSPATH', aap.directory_conventions.ANTSdir) ANTSpath = [fullfile(getenv('ANTSPATH'), 'bin', 'N4BiasFieldCorrection') ' ']; % Dimension number (always 3 for structural) Ndim = [num2str(3) ' ']; % Any extra options?... if ~isempty(aap.tasklist.currenttask.settings.extraoptions) extraoptions = aap.tasklist.currenttask.settings.extraoptions; else extraoptions = ''; end
3,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: _service_event.rs path of file: ./repos/aws-sdk-rust/sdk/ecs/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codege
pub fn build(self) -> crate::types::ServiceEvent { crate::types::ServiceEvent { id: self.id, created_at: self.created_at, message: self.message, } }
813,002
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: param.go path of file: ./repos/IOC-golang/extension/registry/nacos the code of the file until where you have to start completion: /* * Copyright (c) 2022, Alibaba Group; * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the L
func (c *Param) New(impl *NamingClient) (*NamingClient, error) { var err error impl.INamingClient, err = clients.NewNamingClient(c.NacosClientParam) if err != nil { return nil, err } return impl, nil }
504,594
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: mod.rs path of file: ./repos/pioneer-pro-dj-linux/src/component the code of the file until where you have to start completion: use std::thread; use std::sync::mp
pub async fn run(&mut self) { self.rekordbox_server.run().await; loop { self.next(); thread::sleep(std::time::Duration::from_millis(150)); } }
66,519
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: event.rb path of file: ./repos/dd-trace-rb/lib/datadog/tracing/contrib/racecar the code of the file until where you have to start completion: # frozen_string_literal: true require_relative '../../metadata/ext' require_relative '../active_support/notifications/event' require_relative '../analytics' require_relative 'ext' module Datadog module Tracing module Contrib module Racecar
def process(span, event, _id, payload) span.service = configuration[:service_name] span.resource = payload[:consumer_class] span.set_tag(Contrib::Ext::Messaging::TAG_SYSTEM, Ext::TAG_MESSAGING_SYSTEM) span.set_tag(Tracing::Metadata::Ext::TAG_COMPONENT, Ext::TAG_COMPONENT) # Set analytics sample rate if Contrib::Analytics.enabled?(configuration[:analytics_enabled]) Contrib::Analytics.set_sample_rate(span, configuration[:analytics_sample_rate]) end
209,464
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: lobby_cleanup.rs path of file: ./repos/rivet/svc/pkg/mm/worker/src/workers the code of the file until where you have to start completion: use chirp_worker::prelude::*; use proto::backend::{self, pkg::*}; use redis::AsyncCommands; use serde_json::json; use std::collections::HashMap; #[derive(Debug, sqlx::FromRow)] struct LobbyRow { namespace_i
async fn worker(ctx: &OperationContext<mm::msg::lobby_cleanup::Message>) -> GlobalResult<()> { // NOTE: Idempotent let lobby_id = unwrap_ref!(ctx.lobby_id).as_uuid(); // TODO: Wrap this in a MULTI/WATCH // Remove from Redis before attempting to remove from database. // // We do this before the SQL command because: // * this needs to execute ASAP in order to prevent new players from // attempting to join this lobby // * cleans up lobbies correctly even if mm-lobby-find failed to insert in // to SQL // * if mm-lobby-create times out, we need to clean up Redis nonetheless let mut redis_mm = ctx.redis_mm().await?; let lobby_config = redis_mm .hgetall::<_, HashMap<String, String>>(util_mm::key::lobby_config(lobby_id)) .await?; let did_remove_from_redis = if let (Some(namespace_id), Some(region_id), Some(lobby_group_id)) = ( lobby_config.get(util_mm::key::lobby_config::NAMESPACE_ID), lobby_config.get(util_mm::key::lobby_config::REGION_ID), lobby_config.get(util_mm::key::lobby_config::LOBBY_GROUP_ID), ) { let namespace_id = util::uuid::parse(namespace_id)?; let region_id = util::uuid::parse(region_id)?; let lobby_group_id = util::uuid::parse(lobby_group_id)?; remove_from_redis( &mut redis_mm, namespace_id, region_id, lobby_group_id, lobby_id, ) .await?; true } else { // This is idempotent, don't raise error tracing::info!("lobby not present in redis"); false }; // Fetch the lobby. // // This also ensures that mm-lobby-find or mm-lobby-create // has already inserted the row. // // This also locks the lobby row in case there is a race condition with // mm-lobby-create. let lobby_row = sql_fetch_optional!( [ctx, LobbyRow] " WITH select_lobby AS ( SELECT namespace_id, region_id, lobby_group_id, run_id, create_ts, stop_ts FROM db_mm_state.lobbies WHERE lobby_id = $1 ), _update AS ( UPDATE db_mm_state.lobbies SET stop_ts = $2 WHERE lobby_id = $1 AND stop_ts IS NULL RETURNING 1 ) SELECT * FROM select_lobby ", lobby_id, ctx.ts(), ) .await?; tracing::info!(?lobby_row, "lobby row"); let Some(lobby_row) = lobby_row else { if ctx.req_dt() > util::duration::minutes(5) { tracing::error!("discarding stale message"); return Ok(()); } else { retry_bail!("lobby not found, may be race condition with insertion"); } }; // TODO: Handle race condition here where mm-lobby-find will insert players on a stopped lobby. This can be fixed by checking the lobby stop_ts in the mm-lobby-find trans. // Find players to remove. This is idempotent, so we do this regardless of // if the lobby was already stopped. let players_to_remove = sql_fetch_all!( [ctx, (Uuid,)] " SELECT player_id FROM db_mm_state.players WHERE lobby_id = $1 AND remove_ts IS NULL ", lobby_id, ) .await? .into_iter() .map(|x| x.0) .collect::<Vec<_>>(); tracing::info!(player_len = ?players_to_remove.len(), "removing players"); for player_id in &players_to_remove { msg!([ctx] @wait mm::msg::player_remove(player_id) { player_id: Some((*player_id).into()), lobby_id: Some(lobby_id.into()), from_lobby_destroy: true, }) .await?; } // If we couldn't read the lobby configuration from Redis, then try to // remove it from Redis again using the information fetched from the // database. // // This helps mitigate edge cases where part of the root lobby configuration // was removed from Redis but lingering data. These problems should no // longer exist, but required from much older deployments. // // See `util_mm:key::invalid_lobby_ids` if !did_remove_from_redis { tracing::info!("removing lobby from redis using information from crdb"); remove_from_redis( &mut redis_mm, lobby_row.namespace_id, lobby_row.region_id, lobby_row.lobby_group_id, lobby_id, ) .await?; } msg!([ctx] mm::msg::lobby_cleanup_complete(lobby_id) { lobby_id: Some(lobby_id.into()), }) .await?; // Publish analytics event if not already stopped if lobby_row.stop_ts.is_none() { // Fetch run data let run_json = if let Some(run_id) = lobby_row.run_id { let run_res = op!([ctx] job_run_get { run_ids: vec![run_id.into()], }) .await?; if let Some(run) = run_res.runs.first() { #[allow(clippy::manual_map)] let run_meta_json = match run.run_meta.as_ref().and_then(|x| x.kind.as_ref()) { Some(backend::job::run_meta::Kind::Nomad(meta)) => Some(json!({ "nomad": { "failed": meta.failed, "exit_code": meta.exit_code, } })), None => None, }; Some(json!({ "meta": run_meta_json, })) } else { None } } else { None }; msg!([ctx] analytics::msg::event_create() { events: vec![ analytics::msg::event_create::Event { event_id: Some(Uuid::new_v4().into()), name: "mm.lobby.destroy".into(), properties_json: Some(serde_json::to_string(&json!({ "namespace_id": lobby_row.namespace_id, "lobby_id": lobby_id, "lobby_group_id": lobby_row.lobby_group_id, "region_id": lobby_row.region_id, "create_ts": lobby_row.create_ts, "removed_player_count": players_to_remove.len(), "run": run_json, }))?), ..Default::default() } ], }) .await?; } Ok(()) }
339,953
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: market.rb path of file: ./repos/cryptoexchange/lib/cryptoexchange/exchanges/dex_blue/services the code of the file until where you have to start completion: module Cryptoexchange::Exchanges module DexBlue module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? true end end de
def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = DexBlue::Market::NAME ticker.last = NumericHelper.to_d(output['data']['rate']) ticker.volume = NumericHelper.to_d(output['data']['volumeTraded24h']) ticker.high = NumericHelper.to_d(output['data']['high24h']) ticker.low = NumericHelper.to_d(output['data']['low24h']) ticker.change = NumericHelper.to_d(output['data']['change24h']) ticker.timestamp = nil ticker.payload = output ticker end
644,159
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: palm_datapval.m path of file: ./repos/CBIG/external_packages/matlab/non_default_packages/palm/palm-alpha109 the code of the file until where you have to start completion: function pvals = palm_datapval(G,Gvals,rev) % Compute the p-values for a set of statistics G, taking % as reference a set of observed values for G, from which % the empirical cumulative distribution function (cdf) is % generated, or using a custom cdf. % % Usage: % pvals = palm_datapval(G,Gvals,rev) % % Inputs: % G : Vector of Nx1 statistics to be converted to p-values % Gvals : A Mx1 vector of observed values for the same statistic % from which the empirical cdf is build and p-values % obtained. It doesn't have to be sorted. % rev : If true, indicates that the smallest values in G and % Gvals, rather than the largest, are the most significant. % % Output: % pvals : P-values. % % This function is a simplification of the much more generic % 'cdftool.m' so that only the 'data' option is retained. % To increase speed, there is no argument checking. % % _____________________________________ % Anderson M. Winkler % FMRIB / Univ. of Oxford % Jul/2012 (1st version) % Jan/2014 (this version) % http://brainder.org % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - % PALM -- Permutation Analysis of Linear Models % Copyright (C) 2015 Anderson M. Winkler % % This program is free software: you can redistribute it and/or modify
function pvals = palm_datapval(G,Gvals,rev) % Compute the p-values for a set of statistics G, taking % as reference a set of observed values for G, from which % the empirical cumulative distribution function (cdf) is % generated, or using a custom cdf. % % Usage: % pvals = palm_datapval(G,Gvals,rev) % % Inputs: % G : Vector of Nx1 statistics to be converted to p-values % Gvals : A Mx1 vector of observed values for the same statistic % from which the empirical cdf is build and p-values % obtained. It doesn't have to be sorted. % rev : If true, indicates that the smallest values in G and % Gvals, rather than the largest, are the most significant. % % Output: % pvals : P-values. % % This function is a simplification of the much more generic % 'cdftool.m' so that only the 'data' option is retained. % To increase speed, there is no argument checking. % % _____________________________________ % Anderson M. Winkler % FMRIB / Univ. of Oxford % Jul/2012 (1st version) % Jan/2014 (this version) % http://brainder.org % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - % PALM -- Permutation Analysis of Linear Models % Copyright (C) 2015 Anderson M. Winkler % % 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 3 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, see <http://www.gnu.org/licenses/>. % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if rev, % if small G are significant % Sort the data and compute the empirical distribution [~,cdfG,distp] = palm_competitive(Gvals(:),'ascend
618,028
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: git.go path of file: ./repos/agola/internal/util the code of the file until where you have to start completion: // Copyright 2019 Sorint.lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compli
func (g *Git) Output(ctx context.Context, stdin io.Reader, args ...string) ([]byte, error) { cmd := g.gitCmd(ctx, args...) if stdin != nil { cmd.Stdin = stdin } stderr := &bytes.Buffer{} cmd.Stderr = stderr out, err := cmd.Output() if err != nil { gitErr := stderr.String() if len(gitErr) > 0 { return nil, errors.New(stderr.String()) } else { return nil, errors.WithStack(err) } } return out, errors.WithStack(err) }
554,258
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: gen_DeviceProximityEventInit.rs path of file: ./repos/phaser/phaser/vendor/web-sys/src/features the code of the file until where you have to start completion: #![allow(unused_imports)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] exter
pub fn bubbles(&mut self, val: bool) -> &mut Self { use wasm_bindgen::JsValue; let r = ::js_sys::Reflect::set( self.as_ref(), &JsValue::from("bubbles"), &JsValue::from(val), ); debug_assert!( r.is_ok(), "setting properties should never fail on our dictionary objects" ); let _ = r; self }
622,416
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: dev_linux.go path of file: ./repos/learning/golang/practice/go-crontab/gopath/src/github.com/coreos/etcd/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // Copyright 2017 The Go Authors. All rig
func Mkdev(major, minor uint32) uint64 { dev := (uint64(major) & 0x00000fff) << 8 dev |= (uint64(major) & 0xfffff000) << 32 dev |= (uint64(minor) & 0x000000ff) << 0 dev |= (uint64(minor) & 0xffffff00) << 12 return dev }
556,265
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.rs path of file: ./repos/kani/tests/coverage/unreachable/while-loop-break the code of the file until where you have to start completion: // Copyright Kani Contributors // SPDX-License-Identif
fn find_first_negative(nums: &[i32]) -> Option<i32> { let mut index = 0; while index < nums.len() { if nums[index] < 0 { return Some(nums[index]); } index += 1; } None }
629,855
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: subsasgn.m path of file: ./repos/malini/Codes/deconvolution - model/spm8/@file_array the code of the file until where you have to start completion: function obj = subsasgn(obj,subs,dat) % Overloaded subsasgn function for file_array objects. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
function obj = subsasgn(obj,subs,dat) % Overloaded subsasgn function for file_array objects. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: subsasgn.m 4136 2010-12-09 22:22:28Z guillaume $ if isempty(subs) return; end
388,771
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: components.gen.go path of file: ./repos/oapi-codegen/internal/test/components the code of the file until where you have to start completion: // Package components provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/deepmap/oapi
func (t *OneOfObject2) MergeOneOfObject20(v OneOfObject20) error { b, err := json.Marshal(v) if err != nil { return err } merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err }
626,966
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: vl_argparse.m path of file: ./repos/panorama/lib/vlfeat-0.9.20/toolbox/misc the code of the file until where you have to start completion: function [conf, args] = vl_argparse(conf, args, varargin) % VL_ARGPARSE Parse list of parameter-value pairs % CONF = VL_ARGPARSE(CONF, ARGS) updates the structure CONF based on % the specified parameter-value pairs ARGS={PAR1, VAL1, ... PARN, % VALN}. The function produces an error if an unknown parameter name % is passed in. % % [CONF, ARGS] = VL_ARGPARSE(CONF, ARGS) copies any parameter in % ARGS that does not match CONF back to ARGS instead of producing an % error. % % Example::
function [conf, args] = vl_argparse(conf, args, varargin) % VL_ARGPARSE Parse list of parameter-value pairs % CONF = VL_ARGPARSE(CONF, ARGS) updates the structure CONF based on % the specified parameter-value pairs ARGS={PAR1, VAL1, ... PARN, % VALN}. The function produces an error if an unknown parameter name % is passed in. % % [CONF, ARGS] = VL_ARGPARSE(CONF, ARGS) copies any parameter in % ARGS that does not match CONF back to ARGS instead of producing an % error. % % Example:: % The function can be used to parse a list of arguments % passed to a MATLAB functions: % % function myFunction(x,y,z,varargin) % conf.parameterName = defaultValue ; % conf = vl_argparse(conf, varargin) % % If only a subset of the options should be parsed, for example % because the other options are interpreted by a subroutine, then % use the form % % [conf, varargin] = vl_argparse(conf, varargin) % % that copies back to VARARGIN any unknown parameter. % % See also: VL_OVERRIDE(), VL_HELP(). % Authors: Andrea Vedaldi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if ~isstruct(conf), error('CONF must be a structure') ; end
673,040
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: encryptionscopes_server.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fake 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. DO NOT EDIT. // Changes may cause incorrect behavi
func (e *EncryptionScopesServerTransport) Do(req *http.Request) (*http.Response, error) { rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) method, ok := rawMethod.(string) if !ok { return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } var resp *http.Response var err error switch method { case "EncryptionScopesClient.Get": resp, err = e.dispatchGet(req) case "EncryptionScopesClient.NewListPager": resp, err = e.dispatchNewListPager(req) case "EncryptionScopesClient.Patch": resp, err = e.dispatchPatch(req) case "EncryptionScopesClient.Put": resp, err = e.dispatchPut(req) default: err = fmt.Errorf("unhandled API %s", method) } if err != nil { return nil, err } return resp, nil }
267,483
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: canvas_cairo_file.go path of file: ./repos/genometools/gtgo the code of the file until where you have to start completion: // +build cairo package gt /* #include "genometools.h" static GtCanvasCairoFile* to_canvas_cairo_file_ptr(GtCanvas *c) { return (GtCanvasCairoFile*) c; } */ import "C" import ( "unsafe" ) // Ca
func CanvasCairoFileNew(s *Style, width, height uint) (*CanvasCairoFile, error) { e := ErrorNew() r := C.gt_canvas_cairo_file_new(s.s, C.GT_GRAPHICS_PNG, C.ulong(width), C.ulong(height), nil, e.e) if r == nil { return nil, e.Get() } return &CanvasCairoFile{canvasNew(r)}, nil }
109,885
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: testsupport.go path of file: ./repos/encore/runtimes/go/appruntime/shared/testsupport the code of the file until where you have to start completion: package testsupport import ( "context" "os" "path/filepath" "reflect" "runtime" "runtime/debug" "slices" "strings" "sync" "testing" "time" _ "unsafe" // for go:linkname "github.com/rs/zerolog" "encore.dev/appruntime/exported/config" "encore.dev/appruntime/exported/model" "encore.dev/appruntime/exported/trace2" "encore.dev/appruntime/shared/reqtrack" ) type Manager struct { static *config.Static rt *reqtrack.RequestTracker rootLogger zerolog.Logger rootTestConfig *TestConfig wd string testServiceOnce sync.Once testService string testServiceNum uint16 } func NewManager(static *config.Static, rt *reqtrack.RequestTracker, rootLogger zerolog.Logger) *Manager { wd, _ := os.Getwd() return &Manager{static: static, rt: rt, rootLogger: rootLogger, wd: wd, rootTestConfig: newTestConfig(nil)} } // StartTest is called when a test starts running. This allows Encore's testing framework to // isolate behavior between different tests on global state. func (mgr *Manager) StartTest(t *testing.T, fn func(*testing.T)) { var parent *model.Request parentConfig := mgr.rootTestConfig // Convert the fn pointer to a file/line number if possible // This is useful for debugging tests that are hanging var testFile string var testLine int fnPtr := reflect.ValueOf(fn).Pointer() if f := runtime.FuncForPC(fn
func (mgr *Manager) StartTest(t *testing.T, fn func(*testing.T)) { var parent *model.Request parentConfig := mgr.rootTestConfig // Convert the fn pointer to a file/line number if possible // This is useful for debugging tests that are hanging var testFile string var testLine int fnPtr := reflect.ValueOf(fn).Pointer() if f := runtime.FuncForPC(fnPtr); f != nil { testFile, testLine = f.FileLine(fnPtr) if mgr.static.TestAppRootPath != "" { testFile = strings.TrimPrefix(testFile, mgr.static.TestAppRootPath+string(filepath.Separator)) } } var traceID model.TraceID var parentSpanID model.SpanID if curr := mgr.rt.Current(); curr.Req != nil { parent = curr.Req traceID = curr.Req.TraceID parentSpanID = curr.Req.ParentSpanID parentConfig = curr.Req.Test.Config } spanID, err := model.GenSpanID() if err != nil { t.Fatalf("encoreStartTest: failed to generate span ID: %v", err) } ctx, cancel := context.WithCancel(context.Background()) logger := mgr.rootLogger.With().Str("test", t.Name()).Logger() testService, svcNum := mgr.TestService() if traceID.IsZero() { id, err := model.GenTraceID() if err != nil { t.Fatalf("encoreStartTest: failed to generate trace ID: %v", err) } traceID = id } req := &model.Request{ Type: model.Test, TraceID: traceID, SpanID: spanID, ParentSpanID: parentSpanID, Start: time.Now(), Traced: mgr.rt.TracingEnabled(), Test: &model.TestData{ Ctx: ctx, Cancel: cancel, Current: t, Parent: parent, Service: testService, TestFile: testFile, TestLine: uint32(testLine), Config: newTestConfig(parentConfig), ServiceInstances: make(map[string]any), }, Logger: &logger, SvcNum: svcNum, } mgr.rt.BeginRequest(req) if curr := mgr.rt.Current(); curr.Trace != nil { curr.Trace.TestSpanStart(req, curr.Goctr) } }
153,061
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: modelgeneration.go path of file: ./repos/juju/state the code of the file until where you have to start completion: // Copyright 2018 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package state import ( "fmt" "sort" "strconv" "time" "github.com/juju/charm/v12" "github.com/juju/collections/set" "github.com/juju/errors" "github.com/juju/mgo/v3" "github.com/juju/mgo/v3/bson" "github.com/juju/mgo/v3/txn" "github.com/juju/names/v5" jujutxn "github.com/juju/txn/v3" "github.com/juju/juju/core/settings" "github.com/juju/juju/mongo/utils" stateerrors "github.com/juju/juju/state/errors" ) // itemChange is the state representation of a core settings ItemChange. type itemChange struct { Type int `bson:"type"` Key string `bson:"key"` OldValue interface{} `bson:"old,omitempty"` NewValue interface{} `bson:"new,omitempty"` } // coreChange returns the core package representation of this change. // Stored keys are unescaped. func (c *itemChange) coreChange() settings.ItemChange { return settings.ItemChange{ Type: c.Type, Key: utils.UnescapeKey(c.Key), OldValue: c.OldValue, NewValue: c.NewValue, } } // generationDoc represents the state of a model generation in MongoDB. type generationDoc struct { DocId string `bson:"_id"` TxnRevno int64 `bson:"txn-revno"` // Name is the name given to this branch at creation. // There should never be more than one branch, not applied or aborted, // with the same name. Branch names can otherwise be re-used. Name string `bson:"name"` // GenerationId is a monotonically incrementing sequence, // set when a branch is committed to the model. // Branches that are not applied, or that have been
func (g *Generation) Commit(userName string) (int, error) { var newGenId int buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := g.Refresh(); err != nil { return nil, errors.Trace(err) } } if g.IsCompleted() { if g.GenerationId() == 0 { return nil, errors.New("branch was already aborted") } return nil, jujutxn.ErrNoOperations } now, err := g.st.ControllerTimestamp() if err != nil { return nil, errors.Trace(err) } assigned, err := g.assignedWithAllUnits() if err != nil { return nil, errors.Trace(err) } ops, err := g.commitConfigTxnOps() if err != nil { return nil, errors.Trace(err) } // Get the new sequence as late as we can. // If assigned is empty, indicating no changes under this branch, // then the generation ID in not incremented. // This effectively means the generation is aborted, not committed. if len(assigned) > 0 { id, err := sequenceWithMin(g.st, "generation", 1) if err != nil { return nil, errors.Trace(err) } newGenId = id } // As a proxy for checking that the generation has not changed, // Assert that the txn rev-no has not changed since we materialised // this generation object. ops = append(ops, txn.Op{ C: generationsC, Id: g.doc.DocId, Assert: bson.D{{"txn-revno", g.doc.TxnRevno}}, Update: bson.D{ {"$set", bson.D{ {"assigned-units", assigned}, {"completed", now.Unix()}, {"completed-by", userName}, {"generation-id", newGenId}, }}, }, }) return ops, nil } if err := g.st.db().Run(buildTxn); err != nil { return 0, errors.Trace(err) } return newGenId, nil }
612,335
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: generate.go path of file: ./repos/linkerd2/pkg/charts/static the code of the file until where you have to start completion: //go:build ignore package main import ( "github.com/linkerd/linkerd2/pkg/charts/static" "github.com/shurcooL/vfsgen" log "github.com/sirupsen/logrus"
func main() { err := vfsgen.Generate(static.Templates, vfsgen.Options{ Filename: "generated_linkerd_templates.gogen.go", PackageName: "static", BuildTags: "prod", VariableName: "Templates", }) if err != nil { log.Fatalln(err) } }
333,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: goroot.go path of file: ./repos/gitkube/vendor/golang.org/x/tools/cmd/godoc 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. package main import ( "os" "path/filepath" "runtime" ) // Copies of functions from src/cmd/go/internal/cfg/cfg.go for // finding the GOROOT. // Keep them in sync until support is moved to a common place, if ever. func findGOROOT() string { if env := os.Getenv("GOROOT"); env != "" { return filepath.Clean(env) } def := filepath.Clean(runtime.GOROOT()) if runtime.Compiler == "gccgo" { // gccgo has no real GOROOT, and it certainly doesn't // depend on the executable's location. return def } exe, err := os.Executable() if err == nil { exe, err = filepath.Abs(exe) if err == nil { i
func findGOROOT() string { if env := os.Getenv("GOROOT"); env != "" { return filepath.Clean(env) } def := filepath.Clean(runtime.GOROOT()) if runtime.Compiler == "gccgo" { // gccgo has no real GOROOT, and it certainly doesn't // depend on the executable's location. return def } exe, err := os.Executable() if err == nil { exe, err = filepath.Abs(exe) if err == nil { if dir := filepath.Join(exe, "../.."); isGOROOT(dir) { // If def (runtime.GOROOT()) and dir are the same // directory, prefer the spelling used in def. if isSameDir(def, dir) { return def } return dir } exe, err = filepath.EvalSymlinks(exe) if err == nil { if dir := filepath.Join(exe, "../.."); isGOROOT(dir) { if isSameDir(def, dir) { return def } return dir } } } } return def }
509,297