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: test_sessions.rb path of file: ./repos/kbsecret/test the code of the file until where you have to start completion: # frozen_string_literal: true require_relative "helpers" require "fileutils" # Tests for KBSecret::Session and related classes/mo
def test_default_session # the default session should always exist, and session? should take both a string # and a symbol assert KBSecret::Config.session?(:default) assert KBSecret::Config.session?("default") hsh = KBSecret::Config.session(:default) # the default session also has a configured hash, and that hash is the same whether # looked up by string or by symbol assert_instance_of Hash, hsh assert_equal hsh, KBSecret::Config.session("default") end
630,538
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: formatter.go path of file: ./repos/scan4all/vendor/github.com/alecthomas/chroma the code of the file until where you have to start completion: package chroma import ( "io" ) // A Formatter for Chroma lexers. type Formatter interface { // Format returns a formatting function for
func (r recoveringFormatter) Format(w io.Writer, s *Style, it Iterator) (err error) { defer func() { if perr := recover(); perr != nil { err = perr.(error) } }() return r.Formatter.Format(w, s, it) }
142,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: main.rs path of file: ./repos/coreutils/nohup/src the code of the file until where you have to start completion: use std::{ env, fs::{File, OpenOptions}, io, os::unix::process::CommandExt, process::
fn main() { let matches = cli::create_app().get_matches(); // Ok to unwrap: COMMAND is required let mut cmd = matches.values_of("COMMAND").unwrap(); // Ok to unwrap: Since COMMAND is required, there must be the first value let command_name = cmd.next().unwrap(); let args: Vec<_> = cmd.collect(); let mut command = Command::new(command_name); let mut command_c = command.args(&args); let mut open_opts = OpenOptions::new(); open_opts.write(true).create(true).append(true); // If standard input is a terminal, redirect it from an unreadable file. if io::stdin().is_tty() { command_c = command_c.stdin(Stdio::null()); } if io::stdout().is_tty() { // Try to open in write append nohup.out else open $HOME/nohup.out let stdout = match get_stdout(&open_opts) { Ok(f) => { println!("nohup: stdout is redirected to 'nohup.out'"); f }, Err(err) => { eprintln!("nohup: {}", err); process::exit(125); }, }; command_c = command_c.stdout(stdout); } // If standard error is a terminal, redirect it to standard output. if io::stderr().is_tty() { let stderr = match get_stdout(&open_opts) { Ok(f) => { println!("nohup: stderr is redirected to 'nohup.out'"); f }, Err(err) => { eprintln!("nohup: {}", err); process::exit(125); }, }; command_c = command_c.stderr(stderr); } // Make all SIGHUP a ignored signal unsafe { signal(SIGHUP, SIG_IGN) }; let err = command_c.exec(); if let Some(ENOENT) = err.raw_os_error() { eprintln!("nohup: '{}': {}", command_name, err); process::exit(127); } else { eprintln!("nohup: {}", err); process::exit(126); } }
168,868
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: fileutil_test.go path of file: ./repos/etcd/client/pkg/fileutil the code of the file until where you have to start completion: // Copyright 2015 The etcd 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 t
func TestDirEmpty(t *testing.T) { dir := t.TempDir() if !DirEmpty(dir) { t.Fatalf("expected DirEmpty true, got %v", DirEmpty(dir)) } file, err := os.CreateTemp(dir, "new_file") if err != nil { t.Fatal(err) } file.Close() if DirEmpty(dir) { t.Fatalf("expected DirEmpty false, got %v", DirEmpty(dir)) } if DirEmpty(file.Name()) { t.Fatalf("expected DirEmpty false, got %v", DirEmpty(file.Name())) } }
208,259
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_UpdateDatabase.go path of file: ./repos/aws-sdk-go-v2/service/timestreamwrite the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package timestreamwrite import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" internalEndpointDiscovery "github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery" "github.com/aws/aws-sdk-go-v2/service/timestreamwrite/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Modifies the KMS key for an existing database. While updating the database, you // must specify the database name and the identifier of the new KMS key to be used // ( KmsKeyId ). If there
func (c *Client) fetchOpUpdateDatabaseDiscoverEndpoint(ctx context.Context, region string, optFns ...func(*internalEndpointDiscovery.DiscoverEndpointOptions)) (internalEndpointDiscovery.WeightedAddress, error) { input := getOperationInput(ctx) in, ok := input.(*UpdateDatabaseInput) if !ok { return internalEndpointDiscovery.WeightedAddress{}, fmt.Errorf("unknown input type %T", input) } _ = in identifierMap := make(map[string]string, 0) identifierMap["sdk#Region"] = region key := fmt.Sprintf("Timestream Write.%v", identifierMap) if v, ok := c.endpointCache.Get(key); ok { return v, nil } discoveryOperationInput := &DescribeEndpointsInput{} opt := internalEndpointDiscovery.DiscoverEndpointOptions{} for _, fn := range optFns { fn(&opt) } endpoint, err := c.handleEndpointDiscoveryFromService(ctx, discoveryOperationInput, region, key, opt) if err != nil { return internalEndpointDiscovery.WeightedAddress{}, err } weighted, ok := endpoint.GetValidAddress() if !ok { return internalEndpointDiscovery.WeightedAddress{}, fmt.Errorf("no valid endpoint address returned by the endpoint discovery api") } return weighted, nil }
230,037
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_ListResourceDataSync.go path of file: ./repos/teller/vendor/github.com/aws/aws-sdk-go-v2/service/ssm the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package ssm import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/ssm/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Lists your resource data sy
func (c *Client) ListResourceDataSync(ctx context.Context, params *ListResourceDataSyncInput, optFns ...func(*Options)) (*ListResourceDataSyncOutput, error) { if params == nil { params = &ListResourceDataSyncInput{} } result, metadata, err := c.invokeOperation(ctx, "ListResourceDataSync", params, optFns, c.addOperationListResourceDataSyncMiddlewares) if err != nil { return nil, err } out := result.(*ListResourceDataSyncOutput) out.ResultMetadata = metadata return out, nil }
526,088
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_aggregations.rs path of file: ./repos/chiselstrike/cli/tests/integration_tests/rust_tests the code of the file until where you have to start completion: // SPDX-FileCopyrightText: © 2022 ChiselStrike <info@chiselstrike.com> use crate::framework::prelude::*; static MODELS: &str = r#" import { ChiselEntity } from '@chiselstrike/api'; export class Biography extends ChiselEntity { title: string = ""; page_count: number = 0; } export class Person extends ChiselEntity { name: string = "bob"; age: number = 0; bio
pub async fn count_basic(c: TestContext) { c.chisel.write("models/models.ts", MODELS); c.chisel.write("routes/people.ts", PEOPLE_CRUD); c.chisel.write( "routes/count.ts", r#" import { Person } from "../models/models.ts"; export default async function chisel(req: Request) { return await Person.cursor().count() }"#, ); c.chisel.apply_ok().await; assert_eq!( c.chisel.get_json("/dev/count").await, json!(0) ); store_people(&c.chisel).await; assert_eq!( c.chisel.get_json("/dev/count").await, json!(3) ); c.chisel.write( "routes/count.ts", r#" import { Person } from "../models/models.ts"; export default async function chisel(req: Request) { return await Person.cursor() .filter({age: 50}) .count() }"#, ); c.chisel.apply_ok().await; assert_eq!( c.chisel.get_json("/dev/count").await, json!(1) ); }
408,466
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_source_api_associations.rs path of file: ./repos/aws-sdk-rust/sdk/appsync/src/operation the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `ListSourceApiAssociations`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct ListSourceApiAssoci
fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::BadRequestException(_inner) => ::std::option::Option::Some(_inner), Self::InternalFailureException(_inner) => ::std::option::Option::Some(_inner), Self::NotFoundException(_inner) => ::std::option::Option::Some(_inner), Self::UnauthorizedException(_inner) => ::std::option::Option::Some(_inner), Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } }
801,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: lib.rs path of file: ./repos/fuel-core/bin/e2e-test-client/src the code of the file until where you have to start completion: use crate::{ config::SuiteConfig, test_context::TestContext, }; use libtest_mimic::{ Arguments, Failed, Trial, }; use std::{ env, fs, future::Future, time::Duration, }; pub const CONFIG_FILE_KEY: &str = "FUEL_CORE_E2E_CONFIG"; pub const SYNC_TIMEOUT: Duration = Duration::from_secs(10); pub mod config; pub mod test_context; pub mod tests; pub fn main_body(config: SuiteConfig, mut args: Arguments) { fn with_cloned( config: &SuiteConfig, f: impl FnOnce(SuiteConfig) -> anyhow::Result<(), Failed>, ) -> impl FnOnce() -> anyhow::Result<(), Failed> { let config = config.clone(); move || f(config) } // If we run tests in parallel they may fail because try to use the same state like UTXOs. args.test_threads = Some(1); let tests = vec![ Trial::test( "can transfer from alice to bob", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::transfers::basic_transfer(&ctx).await }) }), ), Trial::test( "can transfer from alice to bob and back", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::transfers::transfer_back(&ctx).await }) }), ), Trial::test( "can collect fee from alice", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::col
pub fn main_body(config: SuiteConfig, mut args: Arguments) { fn with_cloned( config: &SuiteConfig, f: impl FnOnce(SuiteConfig) -> anyhow::Result<(), Failed>, ) -> impl FnOnce() -> anyhow::Result<(), Failed> { let config = config.clone(); move || f(config) } // If we run tests in parallel they may fail because try to use the same state like UTXOs. args.test_threads = Some(1); let tests = vec![ Trial::test( "can transfer from alice to bob", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::transfers::basic_transfer(&ctx).await }) }), ), Trial::test( "can transfer from alice to bob and back", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::transfers::transfer_back(&ctx).await }) }), ), Trial::test( "can collect fee from alice", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::collect_fee::collect_fee(&ctx).await }) }), ), Trial::test( "can execute script and get receipts", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::transfers::transfer_back(&ctx).await }) }), ), Trial::test( "can dry run transfer script and get receipts", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::script::dry_run(&ctx).await })?; Ok(()) }), ), Trial::test( "can dry run multiple transfer scripts and get receipts", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::script::dry_run_multiple_txs(&ctx).await })?; Ok(()) }), ), Trial::test( "dry run script that touches the contract with large state", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::script::run_contract_large_state(&ctx).await })?; Ok(()) }), ), Trial::test( "dry run transaction from `non_specific_tx.raw` file", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::script::non_specific_transaction(&ctx).await })?; Ok(()) }), ), Trial::test( "can deploy a large contract", with_cloned(&config, |config| { async_execute(async { let ctx = TestContext::new(config).await; tests::transfers::transfer_back(&ctx).await }) }), ), ]; libtest_mimic::run(&args, tests).exit(); }
491,501
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: reservoir_errors.go path of file: ./repos/tania-core/backend/src/assets/domain the code of the file until where you have to start completion: package domain const ( ReservoirErrorNameEmptyCode = iota ReservoirErrorNameNotEnoughCharacterCode ReservoirErrorNameExceedMaximunCharacterCode ReservoirErrorNameAlphanumericOnlyCode ReservoirErrorFarmNotFound ReservoirErrorPHInvalidCode ReservoirErrorECInvalidCode ReservoirErrorBucketCapacityInvalidCode ReservoirErrorBucketV
func (e ReservoirError) Error() string { switch e.Code { case ReservoirErrorNameEmptyCode: return "Reservoir name is required." case ReservoirErrorNameNotEnoughCharacterCode: return "Not enough character on Reservoir Name" case ReservoirErrorNameExceedMaximunCharacterCode: return "Reservoir name cannot more than 100 characters" case ReservoirErrorNameAlphanumericOnlyCode: return "Reservoir name should be alphanumeric, space, hypen, or underscore" case ReservoirErrorPHInvalidCode: return "Reservoir pH value is invalid." case ReservoirErrorECInvalidCode: return "Reservoir EC value is invalid." case ReservoirErrorBucketCapacityInvalidCode: return "Reservoir bucket capacity is invalid." case ReservoirErrorWaterSourceAlreadyAttachedCode: return "Reservoir water source is already attached." case ReservoirErrorBucketVolumeInvalidCode: return "Reservoir bucket volume is invalid." case ReservoirNoteErrorInvalidContent: return "Invalid reservoir notes content" default: return "Unrecognized Reservoir Error Code" } }
410,866
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_queue.rb path of file: ./repos/polyphony/test the code of the file until where you have to start completion: # frozen_string_literal: true require_relative 'helper' class QueueTest < MiniTest::Test def setup
def test_push_shift spin { @queue << 42 } v = @queue.shift assert_equal 42, v (1..4).each { |i| @queue << i } buf = [] 4.times { buf << @queue.shift } assert_equal [1, 2, 3, 4], buf end
258,910
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: spm_eeg_prep_ui.m path of file: ./repos/malini/Codes/deconvolution - model/spm8 the code of the file until where you have to start completion: function spm_eeg_prep_ui(callback) % User interface for spm_eeg_prep function performing several tasks % for
function getD %========================================================================== function D = getD Finter = spm_figure('GetWin','Interactive'); D = get(Finter, 'UserData'); if ~isa(D, 'meeg') D = []; end
386,287
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/medialive/src/operation/delete_tags 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, } }
779,760
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: local.go path of file: ./repos/docker-ce/components/engine/vendor/github.com/cloudflare/cfssl/signer/local the code of the file until where you have to start completion: // Package local implements certificate signature functionality for CFSSL.
func PopulateSubjectFromCSR(s *signer.Subject, req pkix.Name) pkix.Name { // if no subject, use req if s == nil { return req } name := s.Name() if name.CommonName == "" { name.CommonName = req.CommonName } replaceSliceIfEmpty(&name.Country, &req.Country) replaceSliceIfEmpty(&name.Province, &req.Province) replaceSliceIfEmpty(&name.Locality, &req.Locality) replaceSliceIfEmpty(&name.Organization, &req.Organization) replaceSliceIfEmpty(&name.OrganizationalUnit, &req.OrganizationalUnit) if name.SerialNumber == "" { name.SerialNumber = req.SerialNumber } return name }
566,664
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: generic_test.go path of file: ./repos/mockery/pkg/fixtures/test the code of the file until where you have to start completion: package test import ( "testing" "github.com/stretchr/testify/assert" mocks "github.com/vektra/mockery/v2/mocks/github.com/vektra/mockery/v2/pkg/fixtures" rtb "github.com/vektra/mockery/v2/pkg/fixtures/redefined_type_b" ) func TestRe
func TestReplaceGeneric(t *testing.T) { type str string m := mocks.NewReplaceGeneric[str, str](t) m.EXPECT().A(rtb.B(1)).Return("") assert.Equal(t, m.A(rtb.B(1)), str("")) m.EXPECT().B().Return(2) assert.Equal(t, m.B(), rtb.B(2)) m.EXPECT().C().Return("") assert.Equal(t, m.C(), str("")) }
238,298
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: gbtest63.m path of file: ./repos/SuiteSparse/GraphBLAS/GraphBLAS/test the code of the file until where you have to start completion: function gbtest63 %GBTEST63 test GrB.incidence
function gbtest63 %GBTEST63 test GrB.incidence % SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2023, All Rights Reserved. % SPDX-License-Identifier: Apache-2.0 rng ('default') ; for trial = 1:2 if (trial == 1) ij = [ 4 1 1 2 4 3 6 3 7 3 1 4 7 4 2 5 7 5 3 6 5 6 2 7 ] ; W = sparse (ij (:,1), ij (:,2), ones (12,1), 8, 8) ; else % load west0479 ; %#ok<*LOAD> % W = west0479 ; load west0479_correct ; %#ok<*LOAD> W = Problem.A ; end
192,601
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: issue.go path of file: ./repos/erda/tools/cli/common the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with t
func UpdateIssue(ctx *command.Context, orgID uint64, request *apistructs.IssueUpdateRequest) error { var resp apistructs.IssueUpdateResponse var b bytes.Buffer path := fmt.Sprintf("/api/issues/%d", request.ID) response, err := ctx.Put().Path(path).JSONBody(request). Header("org", strconv.FormatUint(orgID, 10)). Do().Body(&b) if err != nil { return fmt.Errorf(utils.FormatErrMsg( "get issues", "failed to request ("+err.Error()+")", false)) } if !response.IsOK() { return fmt.Errorf(utils.FormatErrMsg("update issue", fmt.Sprintf("failed to request, status-code: %d, content-type: %s, raw bod: %s", response.StatusCode(), response.ResponseHeader("Content-Type"), b.String()), false)) } if err := json.Unmarshal(b.Bytes(), &resp); err != nil { return fmt.Errorf(utils.FormatErrMsg("update issue", fmt.Sprintf("failed to unmarshal response ("+err.Error()+")"), false)) } if !resp.Success { return fmt.Errorf(utils.FormatErrMsg("update issue", fmt.Sprintf("failed to request, error code: %s, error message: %s", resp.Error.Code, resp.Error.Msg), false)) } return nil }
713,465
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: lib.rs path of file: ./repos/gdnative/examples/scene-create/src the code of the file until where you have to start completion: use gdnative::prelude::*; #[derive(Debug, Clone, Eq, PartialEq)] pub enum ManageErrs { CouldNotMakeInstance, RootClassNotSpatial(String), } #[derive(gdnative::derive::NativeClass)] #[inherit(Spatial)] struct SceneCreate { // Store the loaded scene for a very slight performance boost but mostly to show you how. template: Option<Ref<PackedScene, ThreadLocal>>, children_spawned: u32, } // Demonstrates Scene creation, calling to/from gdscript // // 1. Child scene is created when spawn_one is called // 2. Child scenes are deleted when remove_one is called // 3. Find and call functions in a node (Panel) // 4. Call functions in GDNative (from panel into spawn/remove) // // Note, the same mechanism which is used to call from panel into spawn_one and remove_one c
fn update_panel(owner: &Spatial, num_children: i64) { // Here is how we call into the panel. First we get its node (we might have saved it // from earlier) let panel_node_opt = owner.get_parent().and_then(|parent| { let parent = unsafe { parent.assume_safe() }; parent.find_node("Panel", true, false) }); if let Some(panel_node) = panel_node_opt { let panel_node = unsafe { panel_node.assume_safe() }; // Put the Node let mut as_variant = Variant::new(panel_node); let result = unsafe { as_variant.call("set_num_children", &[Variant::new(num_children as u64)]) }; match result { Ok(_) => godot_print!("Called Panel OK."), Err(_) => godot_print!("Error calling Panel"), } } else { godot_print!("Could not find panel node"); } }
734,180
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: Solution_test.go path of file: ./repos/awesome-golang-algorithm/leetcode/1701-1800/1782.Count-Pairs-Of-Nodes 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}, {"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
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,218
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: spec_helper.rb path of file: ./repos/dry-monads/spec the code of the file until where you have to start completion: # frozen_string_literal:
def suppress_warnings original_verbosity = $VERBOSE $VERBOSE = nil result = yield $VERBOSE = original_verbosity result end
52,983
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: stdtdis_rnd.m path of file: ./repos/malini/Codes/FC_EC_calculation code/DynamicFC/jplv7/Ucsd_garch/Distributions the code of the file until where you have to start completion: function t = stdtdis_rnd(n,df) % PURPOSE: % returns random draws from the standardized t(n) distribution with unit variance % rnd = stdtdis_rnd(n,df) % % USAGE: % random = stdtdis_rnd(n,df) % % INPUTS: % n = size of vector % df = a scalar dof parameter must be > 2 % % OUTPUTS:
function t = stdtdis_rnd(n,df) % PURPOSE: % returns random draws from the standardized t(n) distribution with unit variance % rnd = stdtdis_rnd(n,df) % % USAGE: % random = stdtdis_rnd(n,df) % % INPUTS: % n = size of vector % df = a scalar dof parameter must be > 2 % % OUTPUTS: % random = a vector of random draws from the standardized t(n) distribution % % % COMMENTS: % SEE ALSO: stdtdis_cdf, stdtdis_rnd, stdtdis_pdf, % % written by: % James P. LeSage, Dept of Economics % University of Toledo % 2801 W. Bancroft St, % Toledo, OH 43606 % jpl@jpl.econ.utoledo.edu % Author: Kevin Sheppard % kevin.sheppard@economics.ox.ac.uk % Revision: 2 Date: 12/31/2001 if nargin ~= 2 error('Wrong # of arguments to tdis_rnd'); end
386,152
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.rs path of file: ./repos/sysinfo/src/unix/linux the code of the file until where you have to start completion: // Take a look at the license at the top of the repository in the LICENSE file. use std::cell::UnsafeCell; use std::collections::{HashMap, HashSet}; use std::ffi::OsStr; use std::fmt; use std::fs::{self, DirEntry, File}; use std::io::Read; use std::path::{Path, PathBuf}; use std::str::FromStr; use libc::{c_ulong, gid_t, kill, uid_t}; use crate::sys::system::SystemInfo; use crate::sys::utils::{ get_all_data, get_all_data_from_file, realpath, FileCounter, PathHandler, PathPush, }; use crate::{ DiskUsage, Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, Signal, ThreadKin
pub(crate) fn update_process_disk_activity(p: &mut ProcessInner, path: &mut PathHandler) { let data = match get_all_data(path.join("io"), 16_384) { Ok(d) => d, Err(_) => return, }; let mut done = 0; for line in data.split('\n') { let mut parts = line.split(": "); match parts.next() { Some("read_bytes") => { p.old_read_bytes = p.read_bytes; p.read_bytes = parts .next() .and_then(|x| x.parse::<u64>().ok()) .unwrap_or(p.old_read_bytes); } Some("write_bytes") => { p.old_written_bytes = p.written_bytes; p.written_bytes = parts .next() .and_then(|x| x.parse::<u64>().ok()) .unwrap_or(p.old_written_bytes); } _ => continue, } done += 1; if done > 1 { // No need to continue the reading. break; } } }
661,588
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: rdir.m path of file: ./repos/CBIG/external_packages/matlab/default_packages/others the code of the file until where you have to start completion: function [varargout] = rdir(rootdir,varargin) % Lists the files in a directory and its sub directories.
function [varargout] = rdir(rootdir,varargin) % Lists the files in a directory and its sub directories. % % function [D] = rdir(ROOT,TEST) % % Recursive directory listing. % % ROOT is the directory starting point and includes the % wildcard specification. % The function returns a structure D similar to the one % returned by the built-in dir command. % There is one exception, the name field will include % the relative path as well as the name to the file that % was found. % Pathnames and wildcards may be used. Wild cards can exist % in the pathname too. A special case is the double * that % will match multiple directory levels, e.g. c:\**\*.m. % Otherwise a single * will only match one directory level. % e.g. C:\Program Files\Windows *\ % % TEST is an optional test that can be performed on the % files. Two variables are supported, datenum & bytes. % Tests are strings similar to what one would use in a % if statement. e.g. 'bytes>1024 & datenum>now-7' % % If not output variables are specified then the output is % sent to the screen. % % See also DIR % % examples: % D = rdir('*.m'); % for ii=1:length(D), disp(D(ii).name); end
617,530
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _bad_request_exception.rs path of file: ./repos/aws-sdk-rust/sdk/transcribe/src/types/error the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NO
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ::std::write!(f, "BadRequestException")?; if let ::std::option::Option::Some(inner_1) = &self.message { { ::std::write!(f, ": {}", inner_1)?; } } Ok(()) }
756,927
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: KronGraph500NoPerm.m path of file: ./repos/d4m/examples/3Scaling/2ParallelDatabase/alg the code of the file until where you have to start completion: function [StartVertex, EndVertex] = KronGraph500NoPerm(SCALE,EdgesPerVertex)
function [StartVertex, EndVertex] = KronGraph500NoPerm(SCALE,EdgesPerVertex) %Graph500NoPerm: Generates graph edges using the same 2x2 Kronecker algorithm (R-MAT) as the Graph500 benchmark, but no permutation of vertex labels is performed. %IO user function. % Usage: % [StartVertex EndVertex] = Graph500NoPerm(SCALE,edgefactor) % Inputs: % SCALE = integer scale factor that sets the max number of vertices to 2^SCALE % EdgesPerVertex = sets the total number of edges to M = K*N; % Outputs: % StartVertex = Mx1 vector of integer start vertices in the range [1,N] % EndVertex = Mx1 vector of integer end
727,509
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: meta_test.go path of file: ./repos/erda/internal/tools/pipeline/pipengine/actionexecutor/plugins/apitest/logic the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance wit
func TestWriteMetaFile(t *testing.T) { pipelinefunc.CallbackActionFunc = func(data []byte) (err error) { return nil } meta := &Meta{ Result: "success", } t.Run("writeMetaFile", func(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, CtxKeyLogger, &logrus.Entry{}) writeMetaFile(ctx, &spec.PipelineTask{}, meta) }) }
712,128
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: delete_snapshot_group.go path of file: ./repos/sealer/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/ecs the code of the file until where you have to start completion: package ecs //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS
func (client *Client) DeleteSnapshotGroupWithCallback(request *DeleteSnapshotGroupRequest, callback func(response *DeleteSnapshotGroupResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *DeleteSnapshotGroupResponse var err error defer close(result) response, err = client.DeleteSnapshotGroup(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result }
723,187
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: plugin.go path of file: ./repos/buildkit/vendor/github.com/containerd/containerd/plugin the code of the file until where you have to start completion: /* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file excep
func (r *Registration) Init(ic *InitContext) *Plugin { p, err := r.InitFn(ic) return &Plugin{ Registration: r, Config: ic.Config, Meta: ic.Meta, instance: p, err: err, } }
652,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: option.go path of file: ./repos/tun2socks/core/option the code of the file until where you have to start completion: package option import ( "fmt" "golang.org/x/time/rate" "gvisor.dev/
func WithTCPDelay(v bool) Option { return func(s *stack.Stack) error { opt := tcpip.TCPDelayEnabled(v) if err := s.SetTransportProtocolOption(tcp.ProtocolNumber, &opt); err != nil { return fmt.Errorf("set TCP delay: %s", err) } return nil } }
547,955
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: repositories_manager.go path of file: ./repos/cds/engine/api/repositoriesmanager the code of the file until where you have to start completion: package repositoriesmanager import ( "context" "encoding/base64" "errors" "fmt" "io" "net/http" "net/url" "strconv" "time" "github.com/go-gorp/gorp" gocache "github.com/patrickmn/go-cache" "github.com/rockbears/log" "github.com/xanzy/go-gitlab" "github.com/ovh/cds/engine/api/database/gorpmapping" "github.com/ovh/cds/engine/api/services" "github.com/ovh/cds/engine/api/vcs" "github.com/ovh/cds/engine/cache" "github.com/ovh/cds/sdk" "github.com/ovh/cds/sdk/telemetry" ) func (c *vcsClient) IsBitbucketCloud() bool { if c.vcsProject != nil { return c.vcsProject.Type == "bitbucketcloud" } return false } func (c *vcsClient) IsGerrit(ctx
func (c *vcsClient) doJSONRequest(ctx context.Context, method, path string, in interface{}, out interface{}) (int, error) { _, code, err := services.NewClient(c.srvs).DoJSONRequest(ctx, method, path, in, out, func(req *http.Request) { c.setAuthHeader(ctx, req) }) if code >= 400 { log.Warn(ctx, "repositories manager %s HTTP %s %s error %d", c.name, method, path, code) switch code { case http.StatusUnauthorized: err = sdk.NewError(sdk.ErrNoReposManagerClientAuth, err) case http.StatusBadRequest: err = sdk.NewError(sdk.ErrWrongRequest, err) case http.StatusNotFound: err = sdk.NewError(sdk.ErrNotFound, err) case http.StatusForbidden: err = sdk.NewError(sdk.ErrForbidden, err) default: err = sdk.NewError(sdk.ErrUnknownError, err) } } return code, sdk.WithStack(err) }
513,641
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: lib.rs path of file: ./repos/rules_rust/tools/rustfmt/src the code of the file until where you have to start completion: use std::env; use std::fs; use std::path::{Path, PathBuf}; /// The expected extension of rustfmt manifest files generated by `rustfmt_aspect`. pub const RUSTFMT_MANIFEST_EXTENSION: &str = "rustfmt
pub fn find_manifests() -> Vec<PathBuf> { let runfiles = runfiles::Runfiles::create().unwrap(); std::env::var("RUSTFMT_MANIFESTS") .map(|var| { var.split(PATH_ENV_SEP) .filter_map(|path| match path.is_empty() { true => None, false => Some(runfiles.rlocation(format!( "{}/{}", runfiles.current_repository(), path ))), }) .collect() }) .unwrap_or_default() }
22,920
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: read_test.go path of file: ./repos/gitkube/vendor/cloud.google.com/go/bigquery the code of the file until where you have to start completion: // Copyright 2015 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bigquery import ( "errors" "testing" "github.com/google/go-cmp/cmp" "cloud.google.com/go/internal/testutil" "golang.org/x/net/context" bq "google.go
func TestReadQueryOptions(t *testing.T) { // test that read options are propagated. c := &Client{projectID: "project-id"} pf := &pageFetcherReadStub{ values: [][][]Value{{{1, 2}}}, } tr := &bq.TableReference{ ProjectId: "project-id", DatasetId: "dataset-id", TableId: "table-id", } queryJob := &Job{ projectID: "project-id", jobID: "job-id", c: c, config: &bq.JobConfiguration{ Query: &bq.JobConfigurationQuery{DestinationTable: tr}, }, } it, err := queryJob.read(context.Background(), waitForQueryStub, pf.fetchPage) if err != nil { t.Fatalf("err calling Read: %v", err) } it.PageInfo().MaxSize = 5 var vals []Value if err := it.Next(&vals); err != nil { t.Fatalf("Next: got: %v: want: nil", err) } want := []pageFetcherArgs{{ table: bqToTable(tr, c), pageSize: 5, pageToken: "", }} if !testutil.Equal(pf.calls, want, cmp.AllowUnexported(pageFetcherArgs{}, Table{}, Client{})) { t.Errorf("reading: got:\n%v\nwant:\n%v", pf.calls, want) } }
504,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: _s3_bucket_repository.rs path of file: ./repos/aws-sdk-rust/sdk/codegurureviewer/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Information about an associated repository in an S3 bucket. The associated repository contains a source code .zip file and a build artifacts .zip file that contains .jar or .class files.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct S3BucketRepository { /// <p>The name of the repository when the <cod
pub fn build(self) -> ::std::result::Result<crate::types::S3BucketRepository, ::aws_smithy_types::error::operation::BuildError> { ::std::result::Result::Ok(crate::types::S3BucketRepository { name: self.name.ok_or_else(|| { ::aws_smithy_types::error::operation::BuildError::missing_field( "name", "name was not specified but it is required when building S3BucketRepository", ) })?, details: self.details, }) }
772,317
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_DragEventInit.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] extern "C" { # [wasm_bindgen (extends = :: js_sys :: O
pub fn modifier_symbol_lock(&mut self, val: bool) -> &mut Self { use wasm_bindgen::JsValue; let r = ::js_sys::Reflect::set( self.as_ref(), &JsValue::from("modifierSymbolLock"), &JsValue::from(val), ); debug_assert!( r.is_ok(), "setting properties should never fail on our dictionary objects" ); let _ = r; self }
622,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: spm_vb_regionF.m path of file: ./repos/spm the code of the file until where you have to start completion: function [F] = spm_vb_regionF (Y,xY,SPM) % Get log model evidence over a region of data for a GLM % FORMAT [F] = spm_vb_regionF (Y,xY,SPM) % % Y Matrix of fMRI data (eg. from spm_summarise.m) % xY Coordinates etc from region (eg. from spm_voi.m) % SPM SPM data structure (this must be loaded in from an % SPM.mat file). If this field is not specified this function % will prompt you for the name of an SPM.mat file % % F Log model evidence (single number for whole region) % % Importantly, the design matrix is normalised so that when you compare % models their regressors will be identically scaled. % % Valid model comparisons also require that the DCT basis set used in high % pass filtering, as specified in SPM.xX.K.X0, is the same for all models % that are to be compared. % % W. Penny, G. Flandin, and N. Trujillo-Barreto. (2007). Bayesian Model % Comparison of Spatially Regularised General Linear Models. Human % Brain Mapping, 28(4):275-293. %__________________________________________________________________________ % Will Penny
function [F] = spm_vb_regionF (Y,xY,SPM) % Get log model evidence over a region of data for a GLM % FORMAT [F] = spm_vb_regionF (Y,xY,SPM) % % Y Matrix of fMRI data (eg. from spm_summarise.m) % xY Coordinates etc from region (eg. from spm_voi.m) % SPM SPM data structure (this must be loaded in from an % SPM.mat file). If this field is not specified this function % will prompt you for the name of an SPM.mat file % % F Log model evidence (single number for whole region) % % Importantly, the design matrix is normalised so that when you compare % models their regressors will be identically scaled. % % Valid model comparisons also require that the DCT basis set used in high % pass filtering, as specified in SPM.xX.K.X0, is the same for all models % that are to be compared. % % W. Penny, G. Flandin, and N. Trujillo-Barreto. (2007). Bayesian Model % Comparison of Spatially Regularised General Linear Models. Human % Brain Mapping, 28(4):275-293. %__________________________________________________________________________ % Will Penny % Copyright (C) 2005-2022 Wellcome Centre for Human Neuroimaging try SPM; catch [Pf, sts] = spm_select(1,'^SPM\.mat$','Select SPM.mat'); if ~sts, return; end
715,814
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: ifstatus_windows.go path of file: ./repos/sliver/vendor/tailscale.com/net/tstun the code of the file until where you have to start completion: // Copyright (c) Tailscale Inc & AUTHORS // SPDX-License-Identifier: BSD-3-Clause package tstun import ( "fmt" "s
func (iw *ifaceWatcher) callback(notificationType winipcfg.MibNotificationType, iface *winipcfg.MibIPInterfaceRow) { // Probably should check only when MibParameterNotification, but just in case included MibAddInstance also. if notificationType == winipcfg.MibParameterNotification || notificationType == winipcfg.MibAddInstance { // Out of paranoia, start a goroutine to finish our work, to return to Windows out of this callback. go iw.isUp() } }
454,473
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: union.rs path of file: ./repos/materialize/src/transform/src/fusion the code of the file until where you have to start completion: // Copyright Materialize, Inc. and contributors. All
pub fn action(relation: &mut MirRelationExpr) { if let MirRelationExpr::Union { inputs, .. } = relation { let mut list: Vec<MirRelationExpr> = Vec::with_capacity(1 + inputs.len()); Self::unfold_unions_into(relation.take_dangerous(), &mut list); *relation = MirRelationExpr::Union { base: Box::new(list.remove(0)), inputs: list, } } }
370,585
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: client.go path of file: ./repos/teller/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault the code of the file until where you have to start completion: // Package keyvault implements the Azure ARM Keyvault service API version 2016-10-01. // // The key vault client performs cryptographic key operations and vault operations against the Key Vault service. package keyvault
func (client BaseClient) GetCertificateContacts(ctx context.Context, vaultBaseURL string) (result Contacts, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateContacts") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetCertificateContactsPreparer(ctx, vaultBaseURL) if err != nil { err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateContacts", nil, "Failure preparing request") return } resp, err := client.GetCertificateContactsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateContacts", resp, "Failure sending request") return } result, err = client.GetCertificateContactsResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateContacts", resp, "Failure responding to request") return } return }
526,507
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: reference_images.rs path of file: ./repos/image/tests the code of the file until where you have to start completion: //! Compares the decoding results with reference renderings. use std::fs; use std::io; use std::path::PathBuf; use std::u32; use crc32fast::Hasher as Crc32; use image::DynamicImage; const BASE_PATH: [&str; 2] = [".", "tests"]; const IMAGE_DIR: &str = "images"; const OUTPUT_DIR: &str = "output"; const REFERENCE_DIR: &str = "reference"; fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F) where F: Fn(&PathBuf, PathBuf, &str), { let base: PathBuf = BASE_PATH.iter().collect(); let decoders = &[ "tga", "tiff", "png", "gif", "bmp", "ico", "hdr", "pbm", "webp", ]; for decoder in decoders { let mut path = base.clone(); path.push(dir); path.push(decoder); path.push("**"); path.push( "*.".to_string() + match input_decoder { Some(val) => val, None => decoder, }, ); let pattern = &*format!("{}", path.display()); for path in glob::glob(pattern).unwrap().filter_map(Result::ok) { func(&base, path, decoder) } } } #[cfg(feature = "png")] #[test] fn render_images() { process_images(IMAGE_DIR, None, |base, path, decoder| { println!("render_images {}", path.display()); let img = match image::open(&path) { Ok(DynamicImag
fn from_str(filename: &str) -> Result<Self, Self::Err> { let mut filename_parts = filename.rsplitn(3, '.'); // Ignore the file extension filename_parts.next().unwrap(); // The penultimate part of `filename_parts` represents the metadata, // describing the test type and other details. let meta_str = filename_parts.next().ok_or("missing metadata part")?; let meta = meta_str.split('_').collect::<Vec<_>>(); let (crc, kind); if meta.len() == 1 { // `CRC` crc = parse_crc(meta[0]).ok_or("malformed CRC")?; kind = ReferenceTestKind::SingleImage; } else if meta.len() == 3 && meta[0] == "anim" { // `anim_FRAME_CRC` crc = parse_crc(meta[2]).ok_or("malformed CRC")?; let frame: usize = meta[1].parse().map_err(|_| "malformed frame number")?; kind = ReferenceTestKind::AnimatedFrame { frame: frame.checked_sub(1).ok_or("frame number must be 1-based")?, }; } else { return Err("unrecognized reference image metadata format"); } // The remaining part represents the original file name let orig_filename = filename_parts .next() .ok_or("missing original file name")? .to_owned(); Ok(Self { orig_filename, crc, kind, }) }
598,935
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.go path of file: ./repos/awless/vendor/github.com/aws/aws-sdk-go/service/s3 the code of the file until where you have to start completion: // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package s3 import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/pro
func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *S3 { svc := &S3{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, APIVersion: "2006-03-01", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(restxml.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(restxml.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(restxml.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed(restxml.UnmarshalErrorHandler) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc }
335,136
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/rust-for-backend-development/lesson_5/src/db the code of the file until where you have to start completion: use postgres::error::Error; use postgres::NoTls; use postgres::Row; use r2d2::{Pool, PooledConnection}; use r2d2_postgres::PostgresConnectionManager; /** * Copyright [2020] [Dario Alessandro Lencina Talarico] * Licensed under the Apache License, Version 2.0 (the "License"); * y ou may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by app
pub fn read_movies(db: &mut PooledConnection<PostgresConnectionManager<NoTls>>) -> Result<Vec<Movie>, Error> { let statement = db .prepare( "select * from movies", )?; let movies: Vec<Movie> = db.query(&statement, &[])? .iter() .map(|row| { let title: String = row.get("title"); let genre: String = row.get("genre"); Movie { title, genre, } }).collect(); Ok(movies) }
11,753
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: authentication_client.go path of file: ./repos/hubble-ui/backend/vendor/k8s.io/client-go/kubernetes/typed/authentication/v1beta1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a co
func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1beta1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err } return &AuthenticationV1beta1Client{client}, nil }
380,372
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: a_test.go path of file: ./repos/codeforces-go/leetcode/weekly/200/a the code of the file until where you have to start completion: // Code generated by copypasta/template/leetcode/generator_test.go package main import ( "github.com/EndlessCheng/codeforces-go
func Test(t *testing.T) { t.Log("Current test is [a]") examples := [][]string{ { `[3,0,1,1,9,7]`, `7`, `2`, `3`, `4`, }, { `[1,1,2,2,3]`, `0`, `0`, `1`, `0`, }, // TODO 测试参数的下界和上界 } targetCaseNum := 0 if err := testutil.RunLeetCodeFuncWithExamples(t, countGoodTriplets, examples, targetCaseNum); err != nil { t.Fatal(err) } }
132,066
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/greengrass/src/operation/update_thing_runtime_configuration the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
819,836
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: grant_test.go path of file: ./repos/infra/internal/server/data the code of the file until where you have to start completion: package data import ( "context" "errors" "testing" "time" "golang.org/x/sync/errgroup" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp"
func isNotBlocked[T any](t *testing.T, ch chan T) (result T) { t.Helper() timeout := 100 * time.Millisecond select { case item := <-ch: return item case <-time.After(timeout): t.Fatalf("expected operation to not block, timeout after: %v", timeout) return result } }
571,316
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: proposals_test.go path of file: ./repos/cosmos-sdk/x/bank/simulation the code of the file until where you have to start completion: package simulation_test import ( "math/rand" "testing" "gotest.tools/v3/assert" "cosmossdk.io/x/ban
func TestProposalMsgs(t *testing.T) { // initialize parameters s := rand.NewSource(1) r := rand.New(s) ctx := sdk.NewContext(nil, true, nil) accounts := simtypes.RandomAccounts(r, 3) // execute ProposalMsgs function weightedProposalMsgs := simulation.ProposalMsgs() assert.Assert(t, len(weightedProposalMsgs) == 1) w0 := weightedProposalMsgs[0] // tests w0 interface: assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) msg := w0.MsgSimulatorFn()(r, ctx, accounts) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) //nolint:staticcheck // we're testing the old way here assert.Equal(t, true, msgUpdateParams.Params.DefaultSendEnabled) }
29,374
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: safe_migrate_spec.rb path of file: ./repos/discourse/spec/lib/migration the code of the file until where you have to start completion: # frozen_string_literal: true RSpec.describe Migration::SafeMigrate do before { Migration::SafeMigrate::SafeMigration.disable_safe! } after do Migration::Sa
def migrate_up(path) migrations = ActiveRecord::MigrationContext.new(path, ActiveRecord::SchemaMigration).migrations ActiveRecord::Migrator.new( :up, migrations, ActiveRecord::SchemaMigration, migrations.first.version, ).run end
616,579
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_website_certificate_authorities.rs path of file: ./repos/aws-sdk-rust/sdk/worklink/src/operation the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `ListWebsiteCertificateAuthorities`. #[derive(::std::clone::Clone, ::std::defaul
pub fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::InternalServerErrorException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::InvalidRequestException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::TooManyRequestsException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::UnauthorizedException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::Unhandled(e) => &e.meta, } }
811,319
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: theme.rs path of file: ./repos/cosmic-time/examples/stopwatch/src the code of the file until where you have to start completion: /* * This file is not specific to cosmic-time. * The relevant code to this example is in main.rs. * This is just code to make an iced theme, so * the stopwatch example can be prettier, and * show the andvantages of style animations * with a custom theme. * */ use iced::widget::{button, container, text}; use iced::{application, color, Shadow, Vector}; use iced::{Background as B, Border}; #[derive(Default)] pub struct Theme; impl application::StyleSheet for Theme { type Style = (); fn appearance(&self, _style: &Self::Style) -> application::Appearance { application::Appearance { background_color: color!(0xff, 0xff, 0xff), text_color: color!(0xff, 0x00, 0x00), } } } impl text::StyleShe
fn appearance(&self, style: &Self::Style) -> container::Appearance { match style { Container::White => container::Appearance { background: Some(B::Color(color!(0xd1, 0xd5, 0xdb))), text_color: Some(color!(0x00, 0x00, 0x00)), ..Default::default() }, Container::Red => container::Appearance { background: Some(B::Color(color!(0xfc, 0xa5, 0xa5))), text_color: Some(color!(0x00, 0x00, 0x00)), ..Default::default() }, Container::Green => container::Appearance { background: Some(B::Color(color!(0xb3, 0xf2, 0x64))), text_color: Some(color!(0x00, 0x00, 0x00)), ..Default::default() }, Container::Blue => container::Appearance { background: Some(B::Color(color!(0x93, 0xc5, 0xfd))), text_color: Some(color!(0x00, 0x00, 0x00)), ..Default::default() }, } }
478,444
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: room_based_stairs.rs path of file: ./repos/rustrogueliketutorial/chapter-71-logging/src/map_builders the code of the file until where you have to start completion: use super::{MetaMapBuilder, BuilderMap, TileType}; use rltk::RandomNumberGenerator; pub struct RoomBasedStairs {} impl MetaMapBuilder for RoomBasedStairs { fn build_map(&mut self, rng: &mut rltk::Ran
fn build(&mut self, _rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) { if let Some(rooms) = &build_data.rooms { let stairs_position = rooms[rooms.len()-1].center(); let stairs_idx = build_data.map.xy_idx(stairs_position.0, stairs_position.1); build_data.map.tiles[stairs_idx] = TileType::DownStairs; build_data.take_snapshot(); } else { panic!("Room Based Stairs only works after rooms have been created"); } }
38,647
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: encoding.go path of file: ./repos/streamdal/apps/server/vendor/github.com/DataDog/sketches-go/ddsketch/encoding the code of the file until where you have to start completion: // Unless explicitly stated otherwise all files in this repository ar
func DecodeFloat64LE(b *[]byte) (float64, error) { if len(*b) < 8 { return 0, io.EOF } v := math.Float64frombits(binary.LittleEndian.Uint64(*b)) *b = (*b)[8:] return v, nil }
206,643
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_user_groups_output.rs path of file: ./repos/aws-sdk-rust/sdk/quicksight/src/operation/list_user_groups 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. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct ListUserGroupsOutput { /// <p>T
pub fn build(self) -> crate::operation::list_user_groups::ListUserGroupsOutput { crate::operation::list_user_groups::ListUserGroupsOutput { group_list: self.group_list, next_token: self.next_token, request_id: self.request_id, status: self.status.unwrap_or_default(), _request_id: self._request_id, } }
762,323
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: template_test.go path of file: ./repos/db/adapter/ql the code of the file until where you have to start completion: package ql import ( "testing" "github.com/stretchr/testify/assert" db "github.com/upper/db/v4" "github.com/upper/db/v4/internal/sqlbuilder" ) func TestTemplateSelect(t *testing.T) { b := sqlbuilder.WithTemplate(template) assert := assert.New(t) assert.Equal( "SELECT * FROM artist ORDER BY id() ASC", b.SelectFrom("artist").String(), ) assert.Equal( "SELECT * FROM artist ORDER BY id() ASC", b.Select().From("artist").String(), ) assert.Equal( "SELECT * FROM artist ORDER BY name DESC", b.Select().From("artist").OrderBy("name DESC").String(), ) assert.Equal( "SELECT * FROM artist ORDER BY name DESC", b.Select().From("artist").OrderBy("-name").String(), ) assert.Equal( "SE
func TestTemplateUpdate(t *testing.T) { b := sqlbuilder.WithTemplate(template) assert := assert.New(t) assert.Equal( "UPDATE artist SET name = $1", b.Update("artist").Set("name", "Artist").String(), ) assert.Equal( "UPDATE artist SET name = $1 WHERE (id < $2)", b.Update("artist").Set("name = ?", "Artist").Where("id <", 5).String(), ) assert.Equal( "UPDATE artist SET name = $1 WHERE (id < $2)", b.Update("artist").Set(map[string]string{"name": "Artist"}).Where(db.Cond{"id <": 5}).String(), ) assert.Equal( "UPDATE artist SET name = $1 WHERE (id < $2)", b.Update("artist").Set(struct { Nombre string `db:"name"` }{"Artist"}).Where(db.Cond{"id <": 5}).String(), ) assert.Equal( "UPDATE artist SET name = $1, last_name = $2 WHERE (id < $3)", b.Update("artist").Set(struct { Nombre string `db:"name"` }{"Artist"}).Set(map[string]string{"last_name": "Foo"}).Where(db.Cond{"id <": 5}).String(), ) assert.Equal( "UPDATE artist SET name = $1 || ' ' || $2 || id, id = id + $3 WHERE (id > $4)", b.Update("artist").Set( "name = ? || ' ' || ? || id", "Artist", "#", "id = id + ?", 10, ).Where("id > ?", 0).String(), ) }
2,520
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: remove_entry.rs path of file: ./repos/holochain-rust/crates/core/src/wasm_engine/api the code of the file until where you have to start completion: use crate::{ wasm_engine::{api::ZomeApiResult, Runtime}, workflows::{author_entry::author_entry, get_entry_result::get_entry_result_workflow}, }; use holochain_core_types::{ entry::{deletion_entry::DeletionEntry, Entry}, error::HolochainError, }; use holochain_persistence_api::cas::content::{Address, AddressableContent}; use
pub fn invoke_remove_entry(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { let context = runtime.context()?; // deserialize args let args_str = runtime.load_json_string_from_args(&args); let try_address = Address::try_from(args_str.clone()); // Exit on error if try_address.is_err() { log_error!( context, "zome: invoke_remove_entry failed to deserialize Address: {:?}", args_str ); return ribosome_error_code!(ArgumentDeserializationFailed); } let deleted_entry_address = try_address.unwrap(); // Get Current entry's latest version let get_args = GetEntryArgs { address: deleted_entry_address, options: Default::default(), }; let maybe_entry_result = context .clone() .block_on(get_entry_result_workflow(&context, &get_args)); if let Err(err) = maybe_entry_result { log_error!(context, "zome: get_entry_result_workflow failed: {:?}", err); return ribosome_error_code!(WorkflowFailed); } let entry_result = maybe_entry_result.unwrap(); if !entry_result.found() { return ribosome_error_code!(EntryNotFound); } let deleted_entry_address = entry_result.latest().unwrap().address(); // Create deletion entry let deletion_entry = Entry::Deletion(DeletionEntry::new(deleted_entry_address.clone())); let res: Result<Address, HolochainError> = context .block_on(author_entry( &deletion_entry.clone(), Some(deleted_entry_address), &context.clone(), &vec![], )) .map(|_| deletion_entry.address()); runtime.store_result(res) }
150,697
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: ticker.go path of file: ./repos/hatchet/internal/services/ticker the code of the file until where you have to start completion: package ticker import ( "context" "fmt" "sync" "time" "github.com/go-co-op/gocron/v2" "github.com/google/uuid" "github.com/rs/zerolog" "github.com/hatchet-dev/hatchet/internal/datautils" "github.com/hatchet-dev/hatchet/internal/logger" "github.com/hatchet-dev/hatchet/internal/repository" "github.com/hatchet-dev/hatchet/internal/services/shared/tasktypes" "github.com/hatchet-dev/hatchet/internal/taskqueue" ) type Ticker interface { Start(ctx context.Context) error } type TickerIm
func (t *TickerImpl) Start() (func() error, error) { ctx, cancel := context.WithCancel(context.Background()) t.l.Debug().Msgf("starting ticker %s", t.tickerId) // register the ticker ticker, err := t.repo.Ticker().CreateNewTicker(&repository.CreateTickerOpts{ ID: t.tickerId, }) if err != nil { cancel() return nil, err } // subscribe to a task queue with the dispatcher id cleanupQueue, taskChan, err := t.tq.Subscribe(taskqueue.QueueTypeFromTickerID(ticker.ID)) if err != nil { cancel() return nil, err } _, err = t.s.NewJob( gocron.DurationJob(time.Second*5), gocron.NewTask( t.runGetGroupKeyRunRequeue(ctx), ), ) if err != nil { cancel() return nil, fmt.Errorf("could not schedule get group key run requeue: %w", err) } _, err = t.s.NewJob( gocron.DurationJob(time.Second*5), gocron.NewTask( t.runUpdateHeartbeat(ctx), ), ) t.s.Start() wg := sync.WaitGroup{} go func() { for task := range taskChan { wg.Add(1) go func(task *taskqueue.Task) { defer wg.Done() err := t.handleTask(ctx, task) if err != nil { t.l.Error().Err(err).Msgf("could not handle ticker task %s", task.ID) } }(task) } }() cleanup := func() error { t.l.Debug().Msg("removing ticker") cancel() if err := cleanupQueue(); err != nil { return fmt.Errorf("could not cleanup queue: %w", err) } wg.Wait() // delete the ticker err = t.repo.Ticker().Delete(t.tickerId) if err != nil { t.l.Err(err).Msg("could not delete ticker") return err } // add the task after the ticker is deleted err = t.tq.AddTask( ctx, taskqueue.JOB_PROCESSING_QUEUE, tickerRemoved(t.tickerId), ) if err != nil { t.l.Err(err).Msg("could not add ticker removed task") return err } if err := t.s.Shutdown(); err != nil { return fmt.Errorf("could not shutdown scheduler: %w", err) } return nil } return cleanup, nil }
591,310
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: rust_doc.rs path of file: ./repos/rust-analyzer/crates/ide-db/src the code of the file until where you have to start completion: //! Rustdoc specific doc comment handling use crate::documentation::Documentation; // stripped down version of https://github.com/rust-lang/rust/blob/392ba2ba1a7d6c542d2459fb8133bebf62a4a423/src/librustdoc/html/markdown.rs#L8
pub fn is_rust_fence(s: &str) -> bool { let mut seen_rust_tags = false; let mut seen_other_tags = false; let tokens = s .trim() .split(|c| c == ',' || c == ' ' || c == '\t') .map(str::trim) .filter(|t| !t.is_empty()); for token in tokens { match token { "should_panic" | "no_run" | "ignore" | "allow_fail" => { seen_rust_tags = !seen_other_tags } "rust" => seen_rust_tags = true, "test_harness" | "compile_fail" => seen_rust_tags = !seen_other_tags || seen_rust_tags, x if x.starts_with("edition") => {} x if x.starts_with('E') && x.len() == 5 => { if x[1..].parse::<u32>().is_ok() { seen_rust_tags = !seen_other_tags || seen_rust_tags; } else { seen_other_tags = true; } } _ => seen_other_tags = true, } } !seen_other_tags || seen_rust_tags }
368,120
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _match_.rs path of file: ./repos/aws-sdk-rust/sdk/codeguruprofiler/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust
pub fn build(self) -> crate::types::Match { crate::types::Match { target_frames_index: self.target_frames_index, frame_address: self.frame_address, threshold_breach_value: self.threshold_breach_value, } }
777,890
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_test.go path of file: ./repos/kratos/contrib/config/nacos the code of the file until where you have to start completion: package config import ( "reflect" "testing" "time" "github.com/nacos-group/nacos-sdk-go/clients" "github.com/nacos-group/nacos-sdk-go/common/constant" "github.com/nacos-group/nacos-sdk-go/vo" "github.com/go-kratos/kratos/v2/config" ) func TestConfig_Load(t *testing.T) { sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848), } cc := constant.ClientConfig{ TimeoutMs: 5000, NotLoadCacheAtStart: true, LogDir: "/tmp/nacos/log", CacheDir: "/tmp/nacos/cache", RotateTime: "1h", MaxAge: 3, LogLevel: "debug", } client, err := clients.NewConfigClient( vo.NacosClientParam{ ClientConfig: &cc, ServerConfigs: sc, }, ) if err != nil { t.Fatal(err) } source := NewConfigSource(client, WithGroup("test"), WithDataID("test.yaml")) type fields struct { source config.Source } tests := []struct { name string fields fields want []*config.KeyValue wantErr bool preFunc func(t *testing.T) deferFunc func(t *testing.T) }{ { name: "normal", fields: fields{ source: source, }, wantErr: false, preFunc: func(t *testing.T) { _, err = client.PublishConfig(vo.ConfigParam{DataId: "test.yaml", Group: "test", Content: "test: test"}) if err != nil { t.Error(err) } time.Sleep(time.Second * 1) }, deferFunc: func(t *testing.T) { _, dErr
func TestConfig_Watch(t *testing.T) { sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848), } cc := constant.ClientConfig{ TimeoutMs: 5000, NotLoadCacheAtStart: true, LogDir: "/tmp/nacos/log", CacheDir: "/tmp/nacos/cache", RotateTime: "1h", MaxAge: 3, LogLevel: "debug", } client, err := clients.NewConfigClient( vo.NacosClientParam{ ClientConfig: &cc, ServerConfigs: sc, }, ) if err != nil { t.Fatal(err) } source := NewConfigSource(client, WithGroup("test"), WithDataID("test.yaml")) type fields struct { source config.Source } tests := []struct { name string fields fields want []*config.KeyValue wantErr bool processFunc func(t *testing.T, w config.Watcher) deferFunc func(t *testing.T, w config.Watcher) }{ { name: "normal", fields: fields{ source: source, }, wantErr: false, processFunc: func(t *testing.T, w config.Watcher) { _, pErr := client.PublishConfig(vo.ConfigParam{DataId: "test.yaml", Group: "test", Content: "test: test"}) if pErr != nil { t.Error(pErr) } }, deferFunc: func(t *testing.T, w config.Watcher) { _, dErr := client.DeleteConfig(vo.ConfigParam{DataId: "test.yaml", Group: "test"}) if dErr != nil { t.Error(dErr) } }, want: []*config.KeyValue{{ Key: "test.yaml", Value: []byte("test: test"), Format: "yaml", }}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { s := test.fields.source watch, wErr := s.Watch() if wErr != nil { t.Error(wErr) return } if test.processFunc != nil { test.processFunc(t, watch) } if test.deferFunc != nil { defer test.deferFunc(t, watch) } want, nErr := watch.Next() if (nErr != nil) != test.wantErr { t.Errorf("Watch error = %v, wantErr %v", nErr, test.wantErr) return } if !reflect.DeepEqual(want, test.want) { t.Errorf("Watch watcher = %v, want %v", watch, test.want) } }) } }
441,753
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: local.rb path of file: ./repos/gitlabhq/lib/gitlab/ci/config/external/file the code of the file until where you have to start completion: # frozen_string_literal: true module Gitlab module Ci class Config module External module File class Local < Base extend ::Gitlab::Utils::Override include Gitlab::Utils::StrongMemoize def initialize(params, context) # `Repository#blobs_at` does not support files with the `/` prefix. @location = Gitlab::Utils.remove_leading_slashes(params[:local]) super end def content strong_memoize(:content) { fetch_local_content } end def metadata super.merge( type: :local, location: masked_location, blob: masked_blob, raw: masked_raw, extra: {} ) end def validate_context! return if context.project&.repository errors.push("Local file `#{masked_location}` does not have project!") end def validate_content! if content.nil? errors.push("Local file `#{masked_location}` does not exist!") elsif content.blank? errors.push("Local file `#{masked_location}` is empty!") end end private def fetch_local_content BatchLoader.for([context.sha, location]) .batch(key: context.project) do |locations, loader, args| context.logger.instrument(:config_file_fetch_local_content) do args[:key].repos
def initialize(params, context) # `Repository#blobs_at` does not support files with the `/` prefix. @location = Gitlab::Utils.remove_leading_slashes(params[:local]) super end def content strong_memoize(:content) { fetch_local_content } end def metadata super.merge( type: :local, location: masked_location, blob: masked_blob, raw: masked_raw, extra: {} ) end def validate_context! return if context.project&.repository errors.push("Local file `#{masked_location}` does not have project!") end def validate_content! if content.nil? errors.push("Local file `#{masked_location}` does not exist!") elsif content.blank? errors.push("Local file `#{masked_location}` is empty!") end end private def fetch_local_content BatchLoader.for([context.sha, location]) .batch(key: context.project) do |locations, loader, args| context.logger.instrument(:config_file_fetch_local_content) do args[:key].repository.blobs_at(locations).each do |blob| loader.call([blob.commit_id, blob.path], blob.data) end end rescue GRPC::InvalidArgument # no-op end end override :expand_context_attrs def expand_context_attrs { project: context.project, sha: context.sha, user: context.user, parent_pipeline: context.parent_pipeline, variables: context.variables } end def masked_blob return unless valid? strong_memoize(:masked_blob) do context.mask_variables_from( Gitlab::Routing.url_helpers.project_blob_url(context.project, ::File.join(context.sha, location)) ) end end def masked_raw return unless valid? strong_memoize(:masked_raw) do context.mask_variables_from( Gitlab::Routing.url_helpers.project_raw_url(context.project, ::File.join(context.sha, location)) ) end end end end
298,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: trimpathseparator_test.go path of file: ./repos/k6/lib/fsext the code of the file until where you have to start completion: package fsext import ( "errors" "io/fs" "path/filepath" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/require" ) func TestTrimAferoPathSeparatorFs(t *testing.T) { t.Parallel() m := afero.NewMemMapFs() f := NewTrimFilePathSeparatorFs(m) expecteData := []byte("something") err := afero.WriteFile(f, f
func TestTrimAferoPathSeparatorFs(t *testing.T) { t.Parallel() m := afero.NewMemMapFs() f := NewTrimFilePathSeparatorFs(m) expecteData := []byte("something") err := afero.WriteFile(f, filepath.FromSlash("/path/to/somewhere"), expecteData, 0o644) require.NoError(t, err) data, err := afero.ReadFile(m, "/path/to/somewhere") require.Error(t, err) require.True(t, errors.Is(err, fs.ErrNotExist)) require.Nil(t, data) data, err = afero.ReadFile(m, "path/to/somewhere") require.NoError(t, err) require.Equal(t, expecteData, data) err = afero.WriteFile(f, filepath.FromSlash("path/without/separtor"), expecteData, 0o644) require.Error(t, err) require.True(t, errors.Is(err, fs.ErrNotExist)) }
735,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: tape_test.go path of file: ./repos/learn-go-with-tests/io/v7 the code of the file until where you have to start completion: package main import ( "io" "testing" ) func TestTape_Write(t *testing.T) { file, clean := createTempFile(t, "12345") defer clean() tape
func TestTape_Write(t *testing.T) { file, clean := createTempFile(t, "12345") defer clean() tape := &tape{file} tape.Write([]byte("abc")) file.Seek(0, 0) newFileContents, _ := io.ReadAll(file) got := string(newFileContents) want := "abc" if got != want { t.Errorf("got %q want %q", got, want) } }
604,605
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: build.go path of file: ./repos/fabio/vendor/google.golang.org/protobuf/internal/filetype the code of the file until where you have to start completion: // Copyright 2019 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 filetype provides functionality for wrapping descriptors // with Go type information. package filetype import ( "reflect" "google.golang.org/protobuf/internal/descopts" "google.golang.org/protobuf/internal/filedesc" pimpl "google.golang.org/protobuf/internal/impl" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) // Builder constructs type descriptors from a raw file descriptor // and associated Go types for each enum and message declaration. // // # Flattened Ordering // // The protobuf type system represents declarations as a tree. Certain nodes in // the tree require us to either associate it with a concrete Go type or to // resolve a dependency, which is information that must be provided separately // since it cannot be derived from the file descriptor alone. // // However, representing a tree as Go literals is difficult to simply do in a // space and time efficient way. Thus, we store them as a flattened list of // objects where the serialization order from the tree-based form is important. // // The "flattened ordering" is defined as a tree traversal of all enum, message, // extension, and service declarations using the following algorithm: // // def VisitFileDecls(fd): // for e in fd.Enums: yield e // for m in fd.Messages: yield m // for x in fd.Extensions: yield x // for s in fd.Services: yield s // for m in fd.Messages: yield from VisitMessageDecls(m) // // def VisitMessageDecls(md): // for e in md.Enums: yield e // for m in md.Messages: yield m // for x in md.Extensions: yield x // for m in md.Messages: yield from VisitMessageDecls(m) // // The traversal starts at the root file descriptor and yields each direct // declaration within each node before traversing into sub-declarations // that children themselves may have. type Builder struct { // File is the underlying file descriptor builder. File filedesc.Builder // GoTypes is a unique set of the Go types for all declarations and // dependencies. Each type is represented as a zero value of the Go type. // // Declarations are Go types generated for enums and messages directly // declared (not publicly imported) in the proto source file. // Messages for map entries are accounted for, but represented by nil. // Enum declarations in "flattened ordering" come first, followed by // message declarations in "flattened ordering". // // Dependencies are Go types for enums or messages referenced by // message fields (excluding weak fields), for parent extended messages of // extension fields, for enums or message
func (tb Builder) Build() (out Out) { // Replace the resolver with one that resolves dependencies by index, // which is faster and more reliable than relying on the global registry. if tb.File.FileRegistry == nil { tb.File.FileRegistry = protoregistry.GlobalFiles } tb.File.FileRegistry = &resolverByIndex{ goTypes: tb.GoTypes, depIdxs: tb.DependencyIndexes, fileRegistry: tb.File.FileRegistry, } // Initialize registry if unpopulated. if tb.TypeRegistry == nil { tb.TypeRegistry = protoregistry.GlobalTypes } fbOut := tb.File.Build() out.File = fbOut.File // Process enums. enumGoTypes := tb.GoTypes[:len(fbOut.Enums)] if len(tb.EnumInfos) != len(fbOut.Enums) { panic("mismatching enum lengths") } if len(fbOut.Enums) > 0 { for i := range fbOut.Enums { tb.EnumInfos[i] = pimpl.EnumInfo{ GoReflectType: reflect.TypeOf(enumGoTypes[i]), Desc: &fbOut.Enums[i], } // Register enum types. if err := tb.TypeRegistry.RegisterEnum(&tb.EnumInfos[i]); err != nil { panic(err) } } } // Process messages. messageGoTypes := tb.GoTypes[len(fbOut.Enums):][:len(fbOut.Messages)] if len(tb.MessageInfos) != len(fbOut.Messages) { panic("mismatching message lengths") } if len(fbOut.Messages) > 0 { for i := range fbOut.Messages { if messageGoTypes[i] == nil { continue // skip map entry } tb.MessageInfos[i].GoReflectType = reflect.TypeOf(messageGoTypes[i]) tb.MessageInfos[i].Desc = &fbOut.Messages[i] // Register message types. if err := tb.TypeRegistry.RegisterMessage(&tb.MessageInfos[i]); err != nil { panic(err) } } // As a special-case for descriptor.proto, // locally register concrete message type for the options. if out.File.Path() == "google/protobuf/descriptor.proto" && out.File.Package() == "google.protobuf" { for i := range fbOut.Messages { switch fbOut.Messages[i].Name() { case "FileOptions": descopts.File = messageGoTypes[i].(protoreflect.ProtoMessage) case "EnumOptions": descopts.Enum = messageGoTypes[i].(protoreflect.ProtoMessage) case "EnumValueOptions": descopts.EnumValue = messageGoTypes[i].(protoreflect.ProtoMessage) case "MessageOptions": descopts.Message = messageGoTypes[i].(protoreflect.ProtoMessage) case "FieldOptions": descopts.Field = messageGoTypes[i].(protoreflect.ProtoMessage) case "OneofOptions": descopts.Oneof = messageGoTypes[i].(protoreflect.ProtoMessage) case "ExtensionRangeOptions": descopts.ExtensionRange = messageGoTypes[i].(protoreflect.ProtoMessage) case "ServiceOptions": descopts.Service = messageGoTypes[i].(protoreflect.ProtoMessage) case "MethodOptions": descopts.Method = messageGoTypes[i].(protoreflect.ProtoMessage) } } } } // Process extensions. if len(tb.ExtensionInfos) != len(fbOut.Extensions) { panic("mismatching extension lengths") } var depIdx int32 for i := range fbOut.Extensions { // For enum and message kinds, determine the referent Go type so // that we can construct their constructors. const listExtDeps = 2 var goType reflect.Type switch fbOut.Extensions[i].L1.Kind { case protoreflect.EnumKind: j := depIdxs.Get(tb.DependencyIndexes, listExtDeps, depIdx) goType = reflect.TypeOf(tb.GoTypes[j]) depIdx++ case protoreflect.MessageKind, protoreflect.GroupKind: j := depIdxs.Get(tb.DependencyIndexes, listExtDeps, depIdx) goType = reflect.TypeOf(tb.GoTypes[j]) depIdx++ default: goType = goTypeForPBKind[fbOut.Extensions[i].L1.Kind] } if fbOut.Extensions[i].IsList() { goType = reflect.SliceOf(goType) } pimpl.InitExtensionInfo(&tb.ExtensionInfos[i], &fbOut.Extensions[i], goType) // Register extension types. if err := tb.TypeRegistry.RegisterExtension(&tb.ExtensionInfos[i]); err != nil { panic(err) } } return out }
597,199
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: badcell.rs path of file: ./repos/gentle-intro/code the code of the file until where you have to start completion: // badcell.rs use std::cell::RefCell; fn main() { let greeting = RefCell::new("hello".to_string()); assert_eq!(*greeting.borrow(), "hello"); assert_eq!(greeting.borrow().len(), 5);
fn main() { let greeting = RefCell::new("hello".to_string()); assert_eq!(*greeting.borrow(), "hello"); assert_eq!(greeting.borrow().len(), 5); let mut gr = greeting.borrow_mut(); *gr = "hola".to_string(); assert_eq!(*greeting.borrow(), "hola"); }
8,889
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: error.rs path of file: ./repos/parity-ethereum/ipfs/src the code of the file until where you have to start completion: // Copyright 2015-2020 Parity
fn from(err: Error) -> Out { use self::Error::*; match err { UnsupportedHash => Out::Bad("Hash must be Keccak-256"), UnsupportedCid => Out::Bad("CID codec not supported"), CidParsingFailed => Out::Bad("CID parsing failed"), BlockNotFound => Out::NotFound("Block not found"), TransactionNotFound => Out::NotFound("Transaction not found"), StateRootNotFound => Out::NotFound("State root not found"), ContractNotFound => Out::NotFound("Contract not found"), } }
73,705
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.go path of file: ./repos/minicron/client/vendor/golang.org/x/text/internal/number the code of the file until where you have to start completion: // Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main impo
func main() { gen.Init() const pkg = "number" gen.Repackage("gen_common.go", "common.go", pkg) // Read the CLDR zip file. r := gen.OpenCLDRCoreZip() defer r.Close() d := &cldr.Decoder{} d.SetDirFilter("supplemental", "main") d.SetSectionFilter("numbers", "numberingSystem") data, err := d.DecodeZip(r) if err != nil { log.Fatalf("DecodeZip: %v", err) } w := gen.NewCodeWriter() defer w.WriteGoFile(*outputFile, pkg) fmt.Fprintln(w, `import "golang.org/x/text/internal/stringset"`) gen.WriteCLDRVersion(w) genNumSystem(w, data) genSymbols(w, data) genFormats(w, data) }
350,088
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: mailer.rb path of file: ./repos/pakyow/frameworks/mailer/lib/pakyow/mailer the code of the file until where you have to start completion: # frozen_string_literal: true require "mail" require "oga" require_relative "plaintext" require_relative "style_inliner" module Pakyow module Mailer class Mailer def initialize(config:, renderer: nil, logger: Pakyow.logger) @config, @renderer, @logger = config, renderer, logger end def deliver_to(recipient, subject: nil, sender: nil, content: nil, type: nil) processed_content = if content process(content, type || "text/plain") elsif @renderer process(
def process(content, content_type) processed_content = {} if content_type.include?("text/html") document = Oga.parse_html(content) mailable_document = document.at_css("body") || document processed_content[:text] = Plaintext.convert_to_text( mailable_document.to_xml ) stylesheets = if @renderer @renderer.app.class.packs_for_view(@renderer.presenter.view).select(&:stylesheets?).map(&:stylesheets) else [] end processed_content[:html] = StyleInliner.new( mailable_document, stylesheets: stylesheets ).inlined else processed_content[:text] = content end
651,866
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: epoch_retrieval.rs path of file: ./repos/diem/consensus/consensus-types/src the code of the file until where you have to start completion: // Copyright (c) The Diem Core Contributors // SPDX-License
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "EpochRetrievalRequest: start_epoch {}, end_epoch {}", self.start_epoch, self.end_epoch ) }
316,907
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: faces_match_test.go path of file: ./repos/photoprism/internal/photoprism the code of the file until where you have to start completion: package photoprism import ( "testing" "github.com/photopris
func TestFaces_Match(t *testing.T) { c := config.TestConfig() m := NewFaces(c) opt := FacesOptions{ Force: true, Threshold: 1, } r, err := m.Match(opt) if err != nil { t.Fatal(err) } t.Log(r) }
400,726
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: timeseries.go path of file: ./repos/docker-ce/components/cli/vendor/golang.org/x/net/internal/timeseries the code of the file until where you have to start completion: // Copyright 2015 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 timeseries implements a
func (ts *timeSeries) Clear() { ts.lastAdd = time.Time{} ts.total = ts.resetObservation(ts.total) ts.pending = ts.resetObservation(ts.pending) ts.pendingTime = time.Time{} ts.dirty = false for i := range ts.levels { ts.levels[i].Clear() } }
569,924
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: issue_comment_extractor.go path of file: ./repos/incubator-devlake/backend/plugins/bitbucket/tasks the code of the file until where you have to start completion: /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless requir
func convertIssueComment(issueComment *BitbucketIssueCommentsResponse) (*models.BitbucketIssueComment, errors.Error) { bitbucketIssueComment := &models.BitbucketIssueComment{ BitbucketId: issueComment.BitbucketId, AuthorId: issueComment.User.AccountId, IssueId: issueComment.Issue.Id, AuthorName: issueComment.User.DisplayName, BitbucketCreatedAt: issueComment.CreatedOn, BitbucketUpdatedAt: issueComment.UpdatedOn, Type: issueComment.Type, Body: issueComment.Content.Raw, } return bitbucketIssueComment, nil }
528,322
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: flowcontrol_client.go path of file: ./repos/agones/vendor/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
func NewForConfigOrDie(c *rest.Config) *FlowcontrolV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client }
445,901
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.rs path of file: ./repos/bottlerocket/sources/api/migration/migrations/archived/v1.1.0/schnauzer-paws/src the code of the file until where you have to start completion: use migration_helpers::{migrate, Migration, MigrationData, Result}; use std::process; const SETTING: &str = "settings.kubernetes.pod-infra-container-image"; const OLD_SETTING_GENERATOR: &str = "pluto pod-infra-container-image"; const NEW_SETTING_GENERATOR: &str = "schnauzer settings.kubernetes.pod-infra-container-image"; const NEW_TEMPLATE: &str = "{{ pause-prefix settings.aws.region }}/eks/pause-{{ goarch os.arch }}:3.1"; /// We moved from using pluto to schnauzer for generating the pause container image URL, since it /// lets us reuse the existing region and arch settings, improving reliability and allowing for /// testing new regions through settings overrides. pub struct SchnauzerPaws; impl Migration for SchnauzerPaws { fn forward(&mut self, mut input: MigrationData) -> Result<MigrationData> { // Check if we have this setting at all. if let Some(metadata) = input.metadata.get_mut(SETTING) { if let Some(metadata_value) = metadata.get_mut("setting-generator") { // Make sure the value is what we expect. match metadata_value { serde_json::Value::String(string) => { if string == OLD_SETTING_GENERATOR { // Happy path. Update the generator. *metadata_value = NEW_SETTING_GENERATOR.into(); println!( "Changed setting-generator for '{}' from {:?} to {:?} on upgrade", SETTING, OLD_SETTING_GENERATOR, NEW_SETTING_GENERATOR ); // Set the associated template. We didn't have a template for this // setting before, and metadata can't be changed by the user, so we can // just set it. metadata.insert("template".to_string(), NEW_TEMPLATE.into()); println!( "Set 'template' metadata on '{}' to '{}'", SETTING, NEW_TEMPLATE ); } else { println!( "setting-generator for '{}' is not set to {:?}, leaving alone", SETTING, OLD_SETTING_G
fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> { // Check if we have this setting at all. if let Some(metadata) = input.metadata.get_mut(SETTING) { if let Some(metadata_value) = metadata.get_mut("setting-generator") { // Make sure the value is what we expect. match metadata_value { serde_json::Value::String(string) => { if string == NEW_SETTING_GENERATOR { // Happy path. Update the generator. *metadata_value = OLD_SETTING_GENERATOR.into(); println!( "Changed setting-generator for '{}' from {:?} to {:?} on downgrade", SETTING, NEW_SETTING_GENERATOR, OLD_SETTING_GENERATOR ); // Remove the associated template. We didn't have a template for this // setting before, and metadata can't be changed by the user, so we can // just remove it. if let Some(metadata_value) = metadata.remove("template") { println!( "Removed 'template' metadata on '{}', which was set to '{}'", SETTING, metadata_value ); } else { println!( "Found no 'template' metadata to remove on setting '{}'", SETTING ); } } else { println!( "setting-generator for '{}' is not set to {:?}, leaving alone", SETTING, NEW_SETTING_GENERATOR ); } } _ => { println!( "setting-generator for '{}' is set to non-string value '{}'; SchnauzerPaws only handles strings", SETTING, metadata_value ); } } } else { println!("Found no setting-generator for '{}'", SETTING); } } else { println!("Found no metadata for '{}'", SETTING); } Ok(input) }
363,755
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: archive.go path of file: ./repos/docker-ce/components/engine/builder/remotecontext the code of the file until where you have to start completion: package remotecontext // import "github.com/docker/docker/builder/remotecontext" import ( "io" "os" "path/filepath" "github.com/docker/docker/builder" "github.com/docker/docker/pkg/archive" "github.com/doc
func normalize(path string, root containerfs.ContainerFS) (cleanPath, fullPath string, err error) { cleanPath = root.Clean(string(root.Separator()) + path)[1:] fullPath, err = root.ResolveScopedPath(path, true) if err != nil { return "", "", errors.Wrapf(err, "forbidden path outside the build context: %s (%s)", path, cleanPath) } return }
564,004
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: patience.rs path of file: ./repos/similar/examples the code of the file until where you have to start completion: use similar::{Algorithm, T
fn main() { println!( "{}", TextDiff::configure() .algorithm(Algorithm::Patience) .diff_lines(OLD, NEW) .unified_diff() ); }
397,574
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: Solution_test.go path of file: ./repos/awesome-golang-algorithm/leetcode/2401-2500/2464.Minimum-Subarrays-in-a-Valid-Split 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}, {"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
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) } }) } }
185,339
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: column.rb path of file: ./repos/rodf/lib/rodf the code of the file until where you have to start completion: module RODF class Column def initialize(opts={
def initialize(opts={}) @elem_attrs = {} @elem_attrs['table:style-name'] = opts[:style] unless opts[:style].nil? if opts[:attributes] @elem_attrs.merge!(opts[:attributes]) end
365,574
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _event_type.rs path of file: ./repos/aws-sdk-rust/sdk/pinpointsmsvoice/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// When writing a match expression against `EventType`, it is important to ensure /// your code is forward-compatible. That is, if a match arm handles a case for a /// feature that is supported by the service but has n
pub fn as_str(&self) -> &str { match self { EventType::Answered => "ANSWERED", EventType::Busy => "BUSY", EventType::CompletedCall => "COMPLETED_CALL", EventType::Failed => "FAILED", EventType::InitiatedCall => "INITIATED_CALL", EventType::NoAnswer => "NO_ANSWER", EventType::Ringing => "RINGING", EventType::Unknown(value) => value.as_str(), } }
816,389
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: basic.rb path of file: ./repos/stackneveroverflow/vendor/bundle/ruby/2.3.0/gems/rack-2.0.3/lib/rack/auth the code of the file until where you have to start completion: require 'rack/auth/abstract/handler' require 'rack/auth/abstract/request' module Rack module Auth # Rack::Auth::Basic implements HTTP Basic Authenticat
def call(env) auth = Basic::Request.new(env) return unauthorized unless auth.provided? return bad_request unless auth.basic? if valid?(auth) env['REMOTE_USER'] = auth.username return @app.call(env) end
244,558
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: delete_objects_on_cancel.rs path of file: ./repos/aws-sdk-rust/sdk/lakeformation/src/operation the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `DeleteObjectsOnCancel`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct DeleteObjectsOnCancel; impl DeleteObjectsOnCancel { /// Creates a new `DeleteObjectsOnCancel` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins, input: crate::operation::delete_objects_on_cancel::DeleteObjectsOnCancelInput, ) -> ::std::result::Result< crate::operation::delete_objects_on_cancel::DeleteObjectsOnCancel
fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::ConcurrentModificationException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::EntityNotFoundException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::InternalServiceException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::InvalidInputException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::OperationTimeoutException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::ResourceNotReadyException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::TransactionCanceledException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::TransactionCommittedException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner), Self::Unhandled(_inner) => &_inner.meta, } }
764,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: questions_controller.rb path of file: ./repos/bootcamp/app/controllers/practices the code of the file until where you have to start completion: # frozen_string_literal: true class Practice
def empty_message case params[:target] when 'solved' '解決済みのQ&Aはありません。' when 'not_solved' '未解決のQ&Aはありません。' else '質問はありません。' end
146,373
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: read_freesurfer_file.m path of file: ./repos/fieldtrip/external/gifti/@gifti/private the code of the file until where you have to start completion: function this = read_freesurfer_file(filename) % Low level reader of FreeSurfer files (ASCII triangle surface file) % FORMAT this = read_freesurfer_file(filename) % filename - FreeSurfer file % % See http://wideman-one.com/gw/brain/fs/surfacefileformats.htm
function this = read_freesurfer_file(filename) % Low level reader of FreeSurfer files (ASCII triangle surface file) % FORMAT this = read_freesurfer_file(filename) % filename - FreeSurfer file % % See http://wideman-one.com/gw/brain/fs/surfacefileformats.htm %__________________________________________________________________________ % Copyright (C) 2013 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id: read_freesurfer_file.m 5322 2013-03-13 15:04:14Z guillaume $ fid = fopen(filename,'rt'); if fid == -1, error('Cannot open "%s".',filename); end
685,060
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: node_list.go path of file: ./repos/podman/vendor/github.com/docker/docker/client the code of the file until where you have to start completion: package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" "net/url" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/
func (cli *Client) NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) { query := url.Values{} if options.Filters.Len() > 0 { filterJSON, err := filters.ToJSON(options.Filters) if err != nil { return nil, err } query.Set("filters", filterJSON) } resp, err := cli.get(ctx, "/nodes", query, nil) defer ensureReaderClosed(resp) if err != nil { return nil, err } var nodes []swarm.Node err = json.NewDecoder(resp.body).Decode(&nodes) return nodes, err }
105,270
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: pool.go path of file: ./repos/chainlink/core/chains/evm/client the code of the file until where you have to start completion: package client import ( "context" "fmt" "math/big" "sync" "time" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/common/config" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" ) var ( // PromEVMPoolRPCNodeStates reports current RPC node state PromEVMPoolRPCNodeStates = promauto.NewGaugeVec(prometheus.GaugeOpts{ Name: "evm_pool_rpc_node_states", Help: "The number of
func (p *Pool) SendTransaction(ctx context.Context, tx *types.Transaction) error { main := p.selectNode() var all []SendOnlyNode for _, n := range p.nodes { all = append(all, n) } all = append(all, p.sendonlys...) for _, n := range all { if n == main { // main node is used at the end for the return value continue } // Parallel send to all other nodes with ignored return value // Async - we do not want to block the main thread with secondary nodes // in case they are unreliable/slow. // It is purely a "best effort" send. // Resource is not unbounded because the default context has a timeout. ok := p.IfNotStopped(func() { // Must wrap inside IfNotStopped to avoid waitgroup racing with Close p.wg.Add(1) go func(n SendOnlyNode) { defer p.wg.Done() sendCtx, cancel := p.chStop.CtxCancel(ContextWithDefaultTimeout()) defer cancel() err := NewSendError(n.SendTransaction(sendCtx, tx)) p.logger.Debugw("Sendonly node sent transaction", "name", n.String(), "tx", tx, "err", err) if err == nil || err.IsNonceTooLowError() || err.IsTransactionAlreadyMined() || err.IsTransactionAlreadyInMempool() { // Nonce too low or transaction known errors are expected since // the primary SendTransaction may well have succeeded already return } p.logger.Warnw("Eth client returned error", "name", n.String(), "err", err, "tx", tx) }(n) }) if !ok { p.logger.Debug("Cannot send transaction on sendonly node; pool is stopped", "node", n.String()) } } return main.SendTransaction(ctx, tx) }
492,223
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sub_wrapped.rs path of file: ./repos/snarkVM/circuit/types/integers/src the code of the file until where you have to start completion: // Copyright (C) 2019-2023 Aleo Systems Inc. // This file is part of the snarkVM library. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::*; impl<E: Environment, I: IntegerType> SubWrapped<Self> for Integer<E, I> { type Output = Self; #[inline] fn sub_wrapped(&self, other
fn sub_wrapped(&self, other: &Integer<E, I>) -> Self::Output { // Determine the variable mode. if self.is_constant() && other.is_constant() { // Compute the difference and return the new constant. witness!(|self, other| console::Integer::new(self.wrapping_sub(&other))) } else { // Instead of subtracting the bits of `self` and `other` directly, the integers are // converted into field elements to perform the operation, before converting back to integers. // Note: This is safe as the field is larger than the maximum integer type supported. let difference = self.to_field() + (!other).to_field() + Field::one(); // Extract the integer bits from the field element, with a carry bit. let mut bits_le = difference.to_lower_bits_le(I::BITS as usize + 1); // Drop the carry bit as the operation is wrapped subtraction. bits_le.pop(); // Return the difference of `self` and `other`. Integer { bits_le, phantom: Default::default() } } }
332,862
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: map.rs path of file: ./repos/jumpy/src/core/metadata the code of the file until where you have to start completion: use super::*; #[derive(Clone, HasSchema, Default, Debug)] #[type_data(metadata_asset("map"))] #[repr(C)] pub struct MapMeta { pub name: Ustr, /// The parallax background layers pub background: BackgroundMe
pub fn is_out_of_bounds(&self, pos: &Vec3) -> bool { const KILL_ZONE_BORDER: f32 = 500.0; let map_width = self.grid_size.x as f32 * self.tile_size.x; let left_kill_zone = -KILL_ZONE_BORDER; let right_kill_zone = map_width + KILL_ZONE_BORDER; let bottom_kill_zone = -KILL_ZONE_BORDER; pos.x < left_kill_zone || pos.x > right_kill_zone || pos.y < bottom_kill_zone }
303,937
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: zsyscall_darwin_amd64.go path of file: ./repos/xorm/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,darwin package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GEN
func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return }
194,211
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: client.go path of file: ./repos/magistrala/pkg/auth the code of the file until where you have to start completion: // Copyright (c) Abstract Machines // SPDX-License-Identifier: Apache-2.0 package auth import ( "github.com/absmach/magistra
func SetupAuthz(cfg Config) (magistrala.AuthzServiceClient, Handler, error) { client, err := newHandler(cfg) if err != nil { return nil, nil, err } return thingsauth.NewClient(client.Connection(), cfg.Timeout), client, nil }
693,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: put_lte_network_id_cellular_ran_responses.go path of file: ./repos/magma/orc8r/cloud/api/v1/go/client/lte_networks the code of the file until where you have to start completion: // Code generated by go-swagger; DO NOT EDIT. package lte_networks // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" mod
func (o *PutLTENetworkIDCellularRanDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.Error) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
572,810
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: times.m path of file: ./repos/chebfun/@chebfun3v the code of the file until where you have to start completion: function F = times(F, G) %.* Pointwise multiplication of two CHEBFUN3V objects. % F.*G computes pointwise, componentwise multiplication of two % CHEBFUN3V objects, a CHEBFUN3V and a CHEBFUN3, or a CHEBFUN3V
function F = times(F, G) %.* Pointwise multiplication of two CHEBFUN3V objects. % F.*G computes pointwise, componentwise multiplication of two % CHEBFUN3V objects, a CHEBFUN3V and a CHEBFUN3, or a CHEBFUN3V % and a double. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. % Empty check: if ( isempty(F) || isempty(G) ) F = chebfun3v(); return end
394,326
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: status.rb path of file: ./repos/notifications-rails/notification-settings/lib/notification_settings the code of the file until where you have to start completion: # frozen_string_literal:
def default_status if idle? && !offline? 'idle' elsif offline? 'offline' else 'online' end
213,122
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: split2.m path of file: ./repos/optimviz/utils/mcs/private the code of the file until where you have to start completion: %%%%%%%%%%%%%%%%%%%%%%%%%%
function x1 = split2(x,y) % determines a value x1 for splitting the interval [min(x,y),max(x,y)] % is modeled on the function subint with safeguards for infinite y function x1 = split2(x,y) x2 = y; if x == 0 & abs(y) > 1000 x2 = sign(y); elseif x ~= 0 & abs(y) > 100*abs(x) x2 = 10.*sign(y)*abs(x); end
139
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.go path of file: ./repos/agones/vendor/google.golang.org/protobuf/proto the code of the file until where you have to start completion: // Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in
func (o MarshalOptions) marshalMessageSlow(b []byte, m protoreflect.Message) ([]byte, error) { if messageset.IsMessageSet(m.Descriptor()) { return o.marshalMessageSet(b, m) } fieldOrder := order.AnyFieldOrder if o.Deterministic { // TODO: This should use a more natural ordering like NumberFieldOrder, // but doing so breaks golden tests that make invalid assumption about // output stability of this implementation. fieldOrder = order.LegacyFieldOrder } var err error order.RangeFields(m, fieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { b, err = o.marshalField(b, fd, v) return err == nil }) if err != nil { return b, err } b = append(b, m.GetUnknown()...) return b, nil }
446,962
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/ec2/src/operation/describe_transit_gateway_policy_tables 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, } }
805,901
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: helper.go path of file: ./repos/sentinel-golang/ext/datasource the code of the file until where you have to start completion: // Copyright 1999-2020 Alibaba Group Holding Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with th
func FlowRuleJsonArrayParser(src []byte) (interface{}, error) { if valid, err := checkSrcComplianceJson(src); !valid { return nil, err } rules := make([]*flow.Rule, 0, 8) if err := json.Unmarshal(src, &rules); err != nil { desc := fmt.Sprintf("Fail to convert source bytes to []*flow.Rule, err: %s", err.Error()) return nil, NewError(ConvertSourceError, desc) } return rules, nil }
110,023
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: 20130814174329_alter_timestamp_to_include_timezone.rb path of file: ./repos/catarse/db/migrate the code of the file until where you have to start completion: class AlterTimestampToIncludeTimezone < ActiveRecord::Migration def up execute " DROP FUNCTION if exists expires_at(projects); drop VIEW if exists financial_reports ; ALTER TABLE projects ALTER COLUMN online_date set data type timestamp with time zone; CREATE OR REPLACE FUNCTION expires_at(projects) RETURNS timestamptz AS $$ SELECT (($1.online_date AT TIME ZONE coalesce((SELECT value FROM configurations WHERE name = 'timezone'), 'America/Sao_Paulo') + ($1.online_days || ' days')::interval):
def up execute " DROP FUNCTION if exists expires_at(projects); drop VIEW if exists financial_reports ; ALTER TABLE projects ALTER COLUMN online_date set data type timestamp with time zone; CREATE OR REPLACE FUNCTION expires_at(projects) RETURNS timestamptz AS $$ SELECT (($1.online_date AT TIME ZONE coalesce((SELECT value FROM configurations WHERE name = 'timezone'), 'America/Sao_Paulo') + ($1.online_days || ' days')::interval)::date::text || ' 23:59:59')::timestamptz $$ LANGUAGE SQL; CREATE or replace VIEW financial_reports AS SELECT p.name, u.moip_login, p.goal, ((p.online_date + (p.online_days||' days')::interval)::date::text || ' 23:59:59') as expires_at, p.state FROM (projects p JOIN users u ON ((u.id = p.user_id))); " end
91,339
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: regexp.rb path of file: ./repos/ferrocarril/mruby/src/extn/stdlib/json/add the code of the file until where you have to start completion: # frozen_string_literal
def as_json(*) { JSON.create_id => self.class.name, 'o' => options, 's' => source } end
547,888
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: eegplotsold.m path of file: ./repos/eeglab/functions/miscfunc the code of the file until where you have to start completion: % EEGPLOTSOLD - display data in a clinical format without scrolling % % Usage: % >> eegplotsold(data, srate, 'chanfile', 'title', ... % yscaling, epoch, linecolor,xstart,vertmark) % % Inputs: %
function y = eegplotsold(data, srate, channamefile, titleval, yscaling, epoch, linecolor,xstart,vertmark) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% icadefs; % read MAXEEGPLOTCHANS, DEFAULT_SRATE, DEFAULT_EPOCH from icadefs.m if nargin < 1 help eegplotsold % print usage message PLOT_TIME = 10; data = 0.5*randn(8,floor(DEFAULT_SRATE*PLOT_TIME*2)); titleval = ['eegplotsold() example - random noise']; % show example plot end
553,077
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: cell_component.rb path of file: ./repos/govuk-components/app/components/govuk_component/table_component the code of the file until where you have to start completion: class GovukComponent::
def determine_scope conditions = { scope:, parent:, header:, auto_table_scopes: config.enable_auto_table_scopes } case conditions in { scope: String } scope in { scope: false } | { header: false } | { auto_table_scopes: false } nil in { auto_table_scopes: true, parent: 'thead' } 'col' in { auto_table_scopes: true, parent: 'tbody' } | { auto_table_scopes: true, parent: 'tfoot' } 'row' else nil end
693,934
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: client.go path of file: ./repos/pixie/src/pixie_cli/pkg/vizier the code of the file until where you have to start completion: /* * Copyright 2018- The Pixie 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 * *
func newVizierClusterInfoClient(cloudAddr string) (cloudpb.VizierClusterInfoClient, error) { isInternal := strings.Contains(cloudAddr, "cluster.local") dialOpts, err := services.GetGRPCClientDialOptsServerSideTLS(isInternal) if err != nil { return nil, err } c, err := grpc.Dial(cloudAddr, dialOpts...) if err != nil { return nil, err } return cloudpb.NewVizierClusterInfoClient(c), nil }
737,421
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: protocol_serde.rs path of file: ./repos/aws-sdk-rust/sdk/sms/src the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub(crate
pub(crate) fn or_empty_doc(data: &[u8]) -> &[u8] { if data.is_empty() { b"{}" } else { data } }
801,382