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: desc_list.go path of file: ./repos/octant/vendor/google.golang.org/protobuf/internal/filedesc 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 // licen
func (p *EnumRanges) Has(n pref.EnumNumber) bool { for ls := p.lazyInit().sorted; len(ls) > 0; { i := len(ls) / 2 switch r := enumRange(ls[i]); { case n < r.Start(): ls = ls[:i] // search lower case n > r.End(): ls = ls[i+1:] // search upper default: return true } } return false }
198,293
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: manager_test.go path of file: ./repos/lakeFS/pkg/graveler/ref the code of the file until where you have to start completion: package ref_test import ( "context" "encoding/hex" "errors" "fmt" "reflect" "sort" "strconv" "strings" "testing" "time" "github.com/go-test/deep" "github.com/golang/mock/gomock" "github.com/rs/xid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/treeverse/lakefs/pkg/b
func TestManager_GetRepositoryMetadata(t *testing.T) { ctx := context.Background() r, _ := testRefManager(t) const ( repoID = "repo1" ) repository, err := r.CreateRepository(context.Background(), repoID, graveler.Repository{ StorageNamespace: "s3://", CreationDate: time.Now(), DefaultBranchID: "main", }) testutil.Must(t, err) t.Run("get_on_non_existing_repo", func(t *testing.T) { _, err := r.GetRepositoryMetadata(ctx, "not_exist") require.ErrorIs(t, err, graveler.ErrNotFound) }) t.Run("basic", func(t *testing.T) { metadata, err := r.GetRepositoryMetadata(ctx, repository.RepositoryID) require.NoError(t, err) require.Nil(t, metadata) }) }
203,840
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: module.rs path of file: ./repos/wasmer/lib/types/src the code of the file until where you have to start completion: // This file contains code from external sources. // Attributions: https://github.com/wasmerio/wasmer/blob/master
fn from(it: ModuleInfo) -> Self { Self { name: it.name, imports: it.imports, exports: it.exports, start_function: it.start_function, table_initializers: it.table_initializers, passive_elements: it.passive_elements.into_iter().collect(), passive_data: it.passive_data.into_iter().collect(), global_initializers: it.global_initializers, function_names: it.function_names.into_iter().collect(), signatures: it.signatures, functions: it.functions, tables: it.tables, memories: it.memories, globals: it.globals, custom_sections: it.custom_sections, custom_sections_data: it.custom_sections_data, num_imported_functions: it.num_imported_functions, num_imported_tables: it.num_imported_tables, num_imported_memories: it.num_imported_memories, num_imported_globals: it.num_imported_globals, } }
442,302
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: clksin.m path of file: ./repos/nav_matlab/example/gps_spp_test/easysuite the code of the file until where you have to start completion: function [re, im] = clksin(ar, degree, arg_real, arg_imag) % Clenshaw summation of sinus with complex argument % Written by Kai Borre % December 20, 1995
function [re, im] = clksin(ar, degree, arg_real, arg_imag) % Clenshaw summation of sinus with complex argument % Written by Kai Borre % December 20, 1995 % See also WGS2UTM sin_arg_r = sin(arg_real); cos_arg_r = cos(arg_real); sinh_arg_i = sinh(arg_imag); cosh_arg_i = cosh(arg_imag); r = 2*cos_arg_r*cosh_arg_i; i = -2*sin_arg_r*sinh_arg_i; hr1 = 0; hr = 0; hi1 = 0; hi = 0; for t = degree:-1:1 hr2 = hr1; hr1 = hr; hi2 = hi1; hi1 = hi; z = ar(t)+r*hr1-i*hi-hr2; hi = i*hr1+r*hi1-hi2; hr = z; end
273,898
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: cat_long_multi_run1173.m path of file: ./repos/ExploreASL/External/SPMmodified/toolbox/cat12/cat_run1173 the code of the file until where you have to start completion: function out = cat_long_multi_run(job) % Call cat_long_main for multiple subjects % % Christian Gaser % $Id: cat_long_multi_run1173.m 1389 2018-11-11 10:39:41Z dahnke $
function out = cat_long_multi_run(job) % Call cat_long_main for multiple subjects % % Christian Gaser % $Id: cat_long_multi_run1173.m 1389 2018-11-11 10:39:41Z dahnke $ global opts extopts output modulate dartel warps warning off; % use some options from GUI or default file opts = job.opts; extopts = job.extopts; output = job.output; modulate = job.modulate; dartel = job.dartel; warps = job.warps; jobs = repmat({'cat_long_main.m'}, 1, numel(job.subj)); inputs = cell(1, numel(job.subj)); if cat_get_defaults('extopts.subfolders') mrifolder = 'mri'; else mrifolder = ''; end
173,191
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mediator.go path of file: ./repos/go-design-pattern/22_mediator the code of the file until where you have to start completion: // Package mediator 中介模式 // 采用原课程的示例,并且做了一些裁剪 // 假设我们现
func (d *Dialog) HandleEvent(component interface{}) { switch { case reflect.DeepEqual(component, d.Selection): if d.Selection.Selected() == "登录" { fmt.Println("select login") fmt.Printf("show: %s\n", d.UsernameInput) fmt.Printf("show: %s\n", d.PasswordInput) } else if d.Selection.Selected() == "注册" { fmt.Println("select register") fmt.Printf("show: %s\n", d.UsernameInput) fmt.Printf("show: %s\n", d.PasswordInput) fmt.Printf("show: %s\n", d.RepeatPasswordInput) } // others, 如果点击了登录按钮,注册按钮 } }
317,404
You are an expert in writing code in many different languages. Your goal is 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_oauth.go path of file: ./repos/grafana/pkg/login/social/connectors the code of the file until where you have to start completion: package connectors import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "net/mail" "strconv" "golang.org/x/oauth2" "github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/services/auth/identity" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/ssosettings" ssoModels "github.com/grafana/grafana/pkg/services/ssosettings/
func (s *SocialGenericOAuth) extractEmail(data *UserInfoJson) string { if data.Email != "" { return data.Email } if s.emailAttributePath != "" { email, err := util.SearchJSONForStringAttr(s.emailAttributePath, data.rawJSON) if err != nil { s.log.Error("Failed to search JSON for attribute", "error", err) } else if email != "" { return email } } emails, ok := data.Attributes[s.emailAttributeName] if ok && len(emails) != 0 { return emails[0] } if data.Upn != "" { emailAddr, emailErr := mail.ParseAddress(data.Upn) if emailErr == nil { return emailAddr.Address } s.log.Debug("Failed to parse e-mail address", "error", emailErr.Error()) } return "" }
343,632
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: builders.rs path of file: ./repos/aws-sdk-rust/sdk/lookoutmetrics/src/operation/get_anomaly_group 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, } }
770,660
You are an expert in writing code in many different languages. Your goal is 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_rules_parameters.go path of file: ./repos/oathkeeper/internal/httpclient/client/api the code of the file until where you have to start completion: // Code generated by go-swagger; DO NOT EDIT. package api // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) // NewListRulesParams creates a
func (o *ListRulesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.Limit != nil { // query param limit var qrLimit int64 if o.Limit != nil { qrLimit = *o.Limit } qLimit := swag.FormatInt64(qrLimit) if qLimit != "" { if err := r.SetQueryParam("limit", qLimit); err != nil { return err } } } if o.Offset != nil { // query param offset var qrOffset int64 if o.Offset != nil { qrOffset = *o.Offset } qOffset := swag.FormatInt64(qrOffset) if qOffset != "" { if err := r.SetQueryParam("offset", qOffset); err != nil { return err } } } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
209,857
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: hash_test.go path of file: ./repos/beam/sdks/go/pkg/beam/testing/passert the code of the file until where you have to start completion: // Licensed to the Apache Software Foundation (ASF) under one or more
func TestHash_Bad(t *testing.T) { p, s := beam.NewPipelineWithRoot() col := beam.CreateList(s, []string{}) Hash(s, col, "empty collection", "", 0) if err := ptest.Run(p); err == nil { t.Errorf("pipeline SUCCEEDED but should have failed") } }
463,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: _object_not_in_active_tier_error.rs path of file: ./repos/aws-sdk-rust/sdk/s3/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 NOT EDIT. /// <p>The source object of the COPY action is n
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ::std::write!(f, "ObjectNotInActiveTierError")?; if let ::std::option::Option::Some(inner_1) = &self.message { { ::std::write!(f, ": {}", inner_1)?; } } Ok(()) }
812,101
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: stubs_test.go path of file: ./repos/go-sqlmock the code of the file until where you have to start completion: package sqlmock import ( "database/sql/driver" "errors" "fmt" "strconv" "time" ) type NullTime struct { Time time.T
func (ni *NullInt) Scan(value interface{}) error { switch v := value.(type) { case nil: ni.Integer, ni.Valid = 0, false case int64: const maxUint = ^uint(0) const maxInt = int(maxUint >> 1) const minInt = -maxInt - 1 if v > int64(maxInt) || v < int64(minInt) { return errors.New("value out of int range") } ni.Integer, ni.Valid = int(v), true case []byte: n, err := strconv.Atoi(string(v)) if err != nil { return err } ni.Integer, ni.Valid = n, true case string: n, err := strconv.Atoi(v) if err != nil { return err } ni.Integer, ni.Valid = n, true default: return fmt.Errorf("can't convert %T to integer", value) } return nil }
730,895
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: select.rs path of file: ./repos/amp/src/presenters/modes the code of the file until where you have to start completion: use crate::errors::*; use crate::models::application::modes::SelectMode; use crate::presenters::current_buffer_status_line_data; use crate::view::{Colors, CursorType, StatusLineData, Style, View}; use scribe::buffer::Range; use scribe::Workspace; pub fn display(workspace: &mut Workspace, mode: &SelectMode, view: &mut View) -> Result<()> { let mut presenter = view.build_presenter()?; let buffer_status = current_buffer_status_line_data(workspace); let buf = workspace.current_buffer.as_ref().ok_or(BUFFER_MISSING)?; let selected_range = Range::new(mode.anchor, *buf.cursor.clone()); let data = buf.data(); // Draw the visible set of tokens to the terminal. presenter.print_buffer( buf, &data, &workspace.syntax_set, Some(&[selected_range]), None, )?; presenter.print_status_line(&[ StatusLineData { content: " SELECT "
pub fn display(workspace: &mut Workspace, mode: &SelectMode, view: &mut View) -> Result<()> { let mut presenter = view.build_presenter()?; let buffer_status = current_buffer_status_line_data(workspace); let buf = workspace.current_buffer.as_ref().ok_or(BUFFER_MISSING)?; let selected_range = Range::new(mode.anchor, *buf.cursor.clone()); let data = buf.data(); // Draw the visible set of tokens to the terminal. presenter.print_buffer( buf, &data, &workspace.syntax_set, Some(&[selected_range]), None, )?; presenter.print_status_line(&[ StatusLineData { content: " SELECT ".to_string(), style: Style::Default, colors: Colors::SelectMode, }, buffer_status, ]); // Show a vertical bar to allow unambiguous/precise selection. presenter.set_cursor_type(CursorType::Bar); // Render the changes to the screen. presenter.present()?; Ok(()) }
463,821
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: safer_rails_console.rb path of file: ./repos/safer_rails_console/lib the code of the file until where you have to start completion: # frozen_string_literal: true require 'safer_rails_console/version' require 'safer_rails_console/railtie' require 'safer_rails_console/colors' require 'safer_rails_console/rails_version' require 'safer_rails_console/console' require 'acti
def prompt_color if ENV.key?('SAFER_RAILS_CONSOLE_PROMPT_COLOR') SaferRailsConsole::Colors.const_get(ENV['SAFER_RAILS_CONSOLE_PROMPT_COLOR'].upcase) elsif config.environment_prompt_colors.key?(::Rails.env.downcase) config.environment_prompt_colors[::Rails.env.downcase] else SaferRailsConsole::Colors::NONE end
609,408
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: image_format.go path of file: ./repos/podman/pkg/machine/define the code of the file until where you have to start completion: package define import "fmt" type ImageFormat int64 const ( Qcow ImageFormat = iota Vhd
func (imf ImageFormat) KindWithCompression() string { // Tar uses xz; all others use zstd if imf == Tar { return "tar.xz" } return fmt.Sprintf("%s.zst", imf.Kind()) }
107,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: _frame_options_list.rs path of file: ./repos/aws-sdk-rust/sdk/cloudfront/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 writ
fn from(s: &str) -> Self { match s { "DENY" => FrameOptionsList::Deny, "SAMEORIGIN" => FrameOptionsList::Sameorigin, other => FrameOptionsList::Unknown(crate::primitives::sealed_enum_unknown::UnknownVariantValue(other.to_owned())), } }
809,801
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: parallel.go path of file: ./repos/go-zero/core/fx the code of the file until where you have to start completion: package fx import "github.com/
func Parallel(fns ...func()) { group := threading.NewRoutineGroup() for _, fn := range fns { group.RunSafe(fn) } group.Wait() }
258,360
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sbsection.rs path of file: ./repos/FireDBG.for.Rust/codelldb/adapter/crates/lldb/src/sb the code of the file until where you have to start completion: use super::*; cpp_class!(pub unsafe struct SBSection as "SBSection"); unsafe impl Send for
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_descr(f, |descr| { cpp!(unsafe [self as "SBSection*", descr as "SBStream*"] -> bool as "bool" { return self->GetDescription(*descr); }) }) }
577,593
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: v2s.m path of file: ./repos/fieldtrip/external/iso2mesh the code of the file until where you have to start completion: function [no,el,regions,holes]=v2s(img,isovalues,opt,method) % % [no,el,regions,holes]=v2s(img,isovalues,opt,method) % % surface mesh generation from binary or gray-scale volumetric images % shortcut for vol2surf % % author: Qianqian Fang (fangq <at> nmr.mgh.harvard.edu) %
function [no,el,regions,holes]=v2s(img,isovalues,opt,method) % % [no,el,regions,holes]=v2s(img,isovalues,opt,method) % % surface mesh generation from binary or gray-scale volumetric images % shortcut for vol2surf % % author: Qianqian Fang (fangq <at> nmr.mgh.harvard.edu) % % inputs and outputs are similar to those defined in vol2surf; In v2s, % method can be set to 'cgalmesh' in addition to those allowed by vol2surf. % % -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net) % if(nargin==3) method='cgalsurf'; end
684,423
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: fill_in_empty.rb path of file: ./repos/zammad/app/models/core_workflow/result the code of the file until where you have to start completion: # Copyright (C) 2012-2024 Zamm
def run return if skip? @result_object.result[:fill_in][field] = fill_in_value @result_object.payload['params'][field] = @result_object.result[:fill_in][field] set_rerun true end
253,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: zc_storage_error.go path of file: ./repos/buildkit/vendor/github.com/Azure/azure-sdk-for-go/sdk/storage/azblob the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package azblob import ( "bytes" "encoding/xml" "errors" "fmt" "net/http" "sort" "strings" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" ) // InternalError is an internal error type that all errors get wrapped in. type InternalError struct
func (e *StorageError) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) { tokName := "" var t xml.Token for t, err = d.Token(); err == nil; t, err = d.Token() { switch tt := t.(type) { case xml.StartElement: tokName = tt.Name.Local case xml.EndElement: tokName = "" case xml.CharData: switch tokName { case "": continue case "Message": e.description = string(tt) default: if e.details == nil { e.details = map[string]string{} } e.details[tokName] = string(tt) } } } return nil }
653,938
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: builders.rs path of file: ./repos/aws-sdk-rust/sdk/connectparticipant/src/operation/complete_attachment_upload 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, } }
783,284
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: diode_test.go path of file: ./repos/zerolog/diode the code of the file until where you have to start completion: package diode_test import ( "bytes" "fmt" "io" "log" "os" "os/exec" "testing" "time" "github.com/rs/zerolog" "github.com/rs/zerolog/diode" "github.com/rs/zerolog/internal/cbor" ) func TestNewWriter(t *testing.T) { buf := bytes.Buffer{} w := diode.NewWriter(&buf, 1000, 0, func(missed int) { fmt.Printf("Dropped %d messages\n", missed) }) log := zerolog.New(w) log.Print("test") w.Close() want := "{\"level\":\"debug\",\"message\":\"test\"}\n"
func Benchmark(b *testing.B) { log.SetOutput(io.Discard) defer log.SetOutput(os.Stderr) benchs := map[string]time.Duration{ "Waiter": 0, "Pooler": 10 * time.Millisecond, } for name, interval := range benchs { b.Run(name, func(b *testing.B) { w := diode.NewWriter(io.Discard, 100000, interval, nil) log := zerolog.New(w) defer w.Close() b.SetParallelism(1000) b.RunParallel(func(pb *testing.PB) { for pb.Next() { log.Print("test") } }) }) } }
68,756
You are an expert in writing code in many different languages. Your goal is 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_openbsd_amd64.go path of file: ./repos/kubeedge/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // go run mksyscall.go -openbsd -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go // Code generated by the command above;
func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return }
420,321
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: pstore.rb path of file: ./repos/metasploit-framework/lib/anemone/storage the code of the file until where you have to start completion: require 'pstore
def each @keys.each_key do |key| value = nil @store.transaction { |s| value = s[key] } yield key, value end end
738,000
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: compiler.go path of file: ./repos/cockroach/pkg/sql/opt/optgen/lang/langbootstrap the code of the file until where you have to start completion: // Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package lang import ( "bytes" "fmt" "github.com/cockroachdb/errors" ) // CompiledExpr is the result of Optgen scanning, parsing, and semantic // analysis. It contains the set of definitions and rules that were compiled // from the Optgen
func (c *Compiler) compileDefines(defines DefineSetExpr) bool { c.compiled.Defines = defines unique := make(map[TagExpr]bool) for _, define := range defines { // Record the define in the index for fast lookup. name := string(define.Name) _, ok := c.compiled.defineIndex[name] if ok { c.addErr(define.Source(), fmt.Errorf("duplicate '%s' define statement", name)) } c.compiled.defineIndex[name] = define // Determine unique set of tags. for _, tag := range define.Tags { if !unique[tag] { c.compiled.DefineTags = append(c.compiled.DefineTags, string(tag)) unique[tag] = true } } } return true }
704,170
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: backend.go path of file: ./repos/streamdal/apps/server/vendor/github.com/DataDog/appsec-internal-go/log the code of the file until where you have to start completion: // Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.
func defaultWithLevel(level logLevel) func(string, ...any) { if defaultBackendLogLevel < level { return noopLogger } return func(format string, args ...any) { log.Printf(fmt.Sprintf("[%s] %s\n", level, format), args...) } }
206,616
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: docker.go path of file: ./repos/ipsw/internal/commands/docker the code of the file until where you have to start completion: package docker import ( "context" "fmt" "io" "os" "github.com/blacktop/ipsw/internal/utils" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" "github.com/docker/docker/pkg/stdcopy" "github.com/google/uuid" specs "github.com/opencontainers/image-spec/specs-go/v1" ) type Client struct { ID string `yaml:"id,omitempty" json:"id,omitempty"` Image string `yaml:"image,omitempty" json:"image,omitempty"` Entrypoint []string `yaml:"entrypoint,omitempty" json:"entrypoint,omitempty"` Cmd []string `yaml:"cmd,omitempty" json:"cmd,omitempty"` Env []string `yaml:"env,omitempty" json:"env,omitempty"` Mounts []HostMounts `yaml:"mounts,omitempty" json:"mounts,omitempty"` } type HostMounts struct { Source string Target string ReadOnly bool } func NewClient(id, image string, entry []string, cmd []string, env []string, mounts []HostMounts) *Client { return &Client{ ID: id, Image: image, Entrypoint: entry, Cmd: cmd, Env: env, Mounts: mounts, } } func (c *Client) Run(ctx context.Context) error { cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { return fmt.Errorf("failed to create docker client: %w", err) } images, err := cli.ImageList(ctx, types.ImageListOptions{}) if err != nil { return fmt.Errorf("failed to list images: %w", err) } found := false for _, image := range images { if utils.StrSliceContains(image.RepoTags, c.Image) { found = true break } } if !found { reader, err := cli.ImagePull(ctx, c.Image
func (c *Client) Run(ctx context.Context) error { cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { return fmt.Errorf("failed to create docker client: %w", err) } images, err := cli.ImageList(ctx, types.ImageListOptions{}) if err != nil { return fmt.Errorf("failed to list images: %w", err) } found := false for _, image := range images { if utils.StrSliceContains(image.RepoTags, c.Image) { found = true break } } if !found { reader, err := cli.ImagePull(ctx, c.Image, types.ImagePullOptions{ // Platform: "linux/amd64", }) if err != nil { return err } defer reader.Close() io.Copy(os.Stdout, reader) } var mounts []mount.Mount for _, m := range c.Mounts { mounts = append(mounts, mount.Mount{ Type: mount.TypeBind, Source: m.Source, Target: m.Target, ReadOnly: m.ReadOnly, BindOptions: &mount.BindOptions{ CreateMountpoint: true, }, }) } resp, err := cli.ContainerCreate(ctx, &container.Config{ Image: c.Image, Entrypoint: c.Entrypoint, Cmd: c.Cmd, Env: c.Env, Tty: true, AttachStdout: true, AttachStderr: true, NetworkDisabled: true, }, &container.HostConfig{ AutoRemove: true, // Resources: container.Resources{Memory: 1 << 30, MemorySwap: 1 << 30}, Mounts: mounts, }, &network.NetworkingConfig{}, &specs.Platform{ OS: "linux", Architecture: "amd64", }, "ipsw-idapro-"+uuid.New().String()) if err != nil { return fmt.Errorf("failed to create container: %w", err) } if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { return fmt.Errorf("failed to start container: %w", err) } go func() { out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: true, Timestamps: false, }) if err != nil { panic(fmt.Errorf("failed to get container logs: %w", err)) } stdcopy.StdCopy(os.Stdout, os.Stderr, out) }() statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning) select { case err := <-errCh: if err != nil { return fmt.Errorf("error waiting for container: %w", err) } case <-statusCh: } return nil }
241,377
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: kernelcache.go path of file: ./repos/ipsw/pkg/kernelcache the code of the file until where you have to start completion: package kernelcache import ( "archive/zip" "bytes" "encoding/asn1" "encoding/binary" "fmt" "io" "os" "path/filepath" "regexp" "slices" "strings" "time" "github.com/apex/log" // lzfse "github.com/blacktop/go-lzfse" "github.com/blacktop/go-macho" "github.com/blacktop/go-macho/types" "github.com/blacktop/ipsw/internal/utils" "gi
func Decompress(kcache, outputDir string) error { content, err := os.ReadFile(kcache) if err != nil { return errors.Wrap(err, "failed to read Kernelcache") } kc, err := ParseImg4Data(content) if err != nil { return errors.Wrap(err, "failed parse compressed kernelcache Img4") } utils.Indent(log.Debug, 2)("Decompressing Kernelcache") dec, err := DecompressData(kc) if err != nil { return fmt.Errorf("failed to decompress kernelcache %s: %v", kcache, err) } kcache = filepath.Join(outputDir, kcache+".decompressed") os.MkdirAll(filepath.Dir(kcache), 0755) err = os.WriteFile(kcache, dec, 0660) if err != nil { return errors.Wrap(err, "failed to write kernelcache") } utils.Indent(log.Info, 2)("Created " + kcache) return nil }
241,682
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: time_rfc3339.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/iotsecurity/armiotsecurity the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights r
func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { layout := utcDateTimeJSON if tzOffsetRegex.Match(data) { layout = dateTimeJSON } return t.Parse(layout, string(data)) }
272,997
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: migrate_to_data_stream.go path of file: ./repos/go-elasticsearch/typedapi/indices/migratetodatastream the code of the file until where you have to start completion: // Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See t
func (r MigrateToDataStream) Perform(providedCtx context.Context) (*http.Response, error) { var ctx context.Context if instrument, ok := r.instrument.(elastictransport.Instrumentation); ok { if r.spanStarted == false { ctx := instrument.Start(providedCtx, "indices.migrate_to_data_stream") defer instrument.Close(ctx) } } if ctx == nil { ctx = providedCtx } req, err := r.HttpRequest(ctx) if err != nil { if instrument, ok := r.instrument.(elastictransport.Instrumentation); ok { instrument.RecordError(ctx, err) } return nil, err } if instrument, ok := r.instrument.(elastictransport.Instrumentation); ok { instrument.BeforeRequest(req, "indices.migrate_to_data_stream") if reader := instrument.RecordRequestBody(ctx, "indices.migrate_to_data_stream", r.raw); reader != nil { req.Body = reader } } res, err := r.transport.Perform(req) if instrument, ok := r.instrument.(elastictransport.Instrumentation); ok { instrument.AfterRequest(req, "elasticsearch", "indices.migrate_to_data_stream") } if err != nil { localErr := fmt.Errorf("an error happened during the MigrateToDataStream query execution: %w", err) if instrument, ok := r.instrument.(elastictransport.Instrumentation); ok { instrument.RecordError(ctx, localErr) } return nil, localErr } return res, nil }
671,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: api.pb.go path of file: ./repos/kubernetes/vendor/github.com/gogo/protobuf/types the code of the file until where you have to start completion: // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: google/protobuf/ap
func (m *Mixin) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Name) if l > 0 { n += 1 + l + sovApi(uint64(l)) } l = len(m.Root) if l > 0 { n += 1 + l + sovApi(uint64(l)) } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n }
352,114
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: chat_prompt_template_test.go path of file: ./repos/langchaingo/prompts the code of the file until where you have to start completion: package prompts import ( "testing" "github.com/stretchr/testify/require" "github.com/tmc/langchaingo/schema" ) func TestChatPromptTemplate(t *testing.T) { t.Parallel() template := NewChatPromptTemplate([]MessageFormatter{ NewSystemMessagePromptTemplate( "You are a translation engine that can only translate text and cannot interpret it.", nil, ), NewHumanMessagePromptTemplate( `translate this text from {{.inputLang}} to {{.outputLang}}:\n{{.input}}`,
func TestChatPromptTemplate(t *testing.T) { t.Parallel() template := NewChatPromptTemplate([]MessageFormatter{ NewSystemMessagePromptTemplate( "You are a translation engine that can only translate text and cannot interpret it.", nil, ), NewHumanMessagePromptTemplate( `translate this text from {{.inputLang}} to {{.outputLang}}:\n{{.input}}`, []string{"inputLang", "outputLang", "input"}, ), }) value, err := template.FormatPrompt(map[string]interface{}{ "inputLang": "English", "outputLang": "Chinese", "input": "I love programming", }) require.NoError(t, err) expectedMessages := []schema.ChatMessage{ schema.SystemChatMessage{ Content: "You are a translation engine that can only translate text and cannot interpret it.", }, schema.HumanChatMessage{ Content: `translate this text from English to Chinese:\nI love programming`, }, } require.Equal(t, expectedMessages, value.Messages()) _, err = template.FormatPrompt(map[string]interface{}{ "inputLang": "English", "outputLang": "Chinese", }) require.Error(t, err) }
476,849
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: utils.go path of file: ./repos/go-zero/tools/goctl/model/sql/test the code of the file until where you have to start completion: // copy from core/stores/sqlx/utils.go package mocksql import ( "database/sql" "fmt" "strings" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/mapping" ) // ErrNotFound is the alias of sql.ErrNoRows var ErrNotFound = sql.ErrNoRows func escape(input string) string { var b strings.Builder for _, ch := range input { switch ch { case '\x00': b.WriteString(`\x00`) case '\r': b.WriteString(`\r`) case '\n': b.WriteString(`\n`) case '\\': b.WriteString(`\\`) case '\'': b.WriteSt
func format(query string, args ...any) (string, error) { numArgs := len(args) if numArgs == 0 { return query, nil } var b strings.Builder argIndex := 0 for _, ch := range query { if ch == '?' { if argIndex >= numArgs { return "", fmt.Errorf("%d ? in sql, but less arguments provided", argIndex) } arg := args[argIndex] argIndex++ switch v := arg.(type) { case bool: if v { b.WriteByte('1') } else { b.WriteByte('0') } case string: b.WriteByte('\'') b.WriteString(escape(v)) b.WriteByte('\'') default: b.WriteString(mapping.Repr(v)) } } else { b.WriteRune(ch) } } if argIndex < numArgs { return "", fmt.Errorf("%d ? in sql, but more arguments provided", argIndex) } return b.String(), nil }
258,693
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: bridge_test.go path of file: ./repos/chainlink/core/web/resolver the code of the file until where you have to start completion: package resolver import ( "database/sql" "encoding/json" "net/url" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/assets" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/store/models" ) func Test_Bridges(t *testing.T) { t.Parallel() var ( query = ` query GetBridges { bridges { results { id name url confirmations outgoingToken minimumContractPayment createdAt } metadata { total } } }` ) bridgeURL, err := url.Parse("https://external.adapter") require.NoError(t, err) testCases := []GQLTestCase{ unauthorizedTestCase(GQLTestCase{query: query}, "bridges"), { name: "success", authenticated: true, before: func(f *gqlTestFramework) { f.App.On("BridgeORM").Return(f.Mocks.bridgeORM) f.Mocks.bridgeORM.On("BridgeTypes", PageDefaultOffset, PageDefaultLimit).Return([]bridges.BridgeType{ { Name: "bridge1", URL: models.WebURL(*bridgeURL), Confirmations: uint32(1), OutgoingToken: "outgoingToken", MinimumContractPayment: assets.NewLinkFromJuels(1), CreatedAt: f.Timestamp(), }, }, 1, nil) }, query: query, result: ` { "bridges": { "results": [{ "id": "bridge1", "name": "bridge1", "url": "https://external.adapter", "
func Test_CreateBridge(t *testing.T) { t.Parallel() var ( name = bridges.BridgeName("bridge1") mutation = ` mutation createBridge($input: CreateBridgeInput!) { createBridge(input: $input) { ... on CreateBridgeSuccess { bridge { id name url confirmations outgoingToken minimumContractPayment createdAt } } } }` variables = map[string]interface{}{ "input": map[string]interface{}{ "name": "bridge1", "url": "https://external.adapter", "confirmations": 1, "minimumContractPayment": "1", }, } ) bridgeURL, err := url.Parse("https://external.adapter") require.NoError(t, err) testCases := []GQLTestCase{ unauthorizedTestCase(GQLTestCase{query: mutation, variables: variables}, "createBridge"), { name: "success", authenticated: true, before: func(f *gqlTestFramework) { f.App.On("BridgeORM").Return(f.Mocks.bridgeORM) f.Mocks.bridgeORM.On("FindBridge", name).Return(bridges.BridgeType{}, sql.ErrNoRows) f.Mocks.bridgeORM.On("CreateBridgeType", mock.IsType(&bridges.BridgeType{})). Run(func(args mock.Arguments) { arg := args.Get(0).(*bridges.BridgeType) *arg = bridges.BridgeType{ Name: name, URL: models.WebURL(*bridgeURL), Confirmations: uint32(1), OutgoingToken: "outgoingToken", MinimumContractPayment: assets.NewLinkFromJuels(1), CreatedAt: f.Timestamp(), } }). Return(nil) }, query: mutation, variables: variables, // We should test equality for the generated token but since it is // generated by a non mockable object, we can't do this right now. result: ` { "createBridge": { "bridge": { "id": "bridge1", "name": "bridge1", "url": "https://external.adapter", "confirmations": 1, "outgoingToken": "outgoingToken", "minimumContractPayment": "1", "createdAt": "2021-01-01T00:00:00Z" } } } `, }, } RunGQLTests(t, testCases) }
493,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: getfiledate.m path of file: ./repos/Image-Harmonization-Dataset-iHarmony4/Lalonde and Efros/utils/3rd_party/multicore the code of the file until where you have to start completion: function fileDateVector = getfiledate(fileNameIn) %GETFILEDATE Get file modification date as serial date number. % FILEDATE = GETFILEDATE(FILENAME) returns the modification date of the % given file as a serial number. %
function fileDateVector = getfiledate(fileNameIn) %GETFILEDATE Get file modification date as serial date number. % FILEDATE = GETFILEDATE(FILENAME) returns the modification date of the % given file as a serial number. % % FILEDATES = GETFILEDATE(FILENAMECELL) works on the cell FILENAMECELL of % file names and returns a vector of file dates. % % Markus Buehren % Last modified 09.10.2008 % % See also DIR, DATENUM2, GETFILESIZE. if ischar(fileNameIn) fileNameCell = {fileNameIn}; else fileNameCell = fileNameIn; end
570,602
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 20120129211750_add_lockable_to_users.rb path of file: ./repos/PasswordPusher/db/migrate the code of the file until where you have to start completion: # frozen_string_literal: true class AddLockableToUsers < ActiveRecord::Migration[4.2] def change change_table :users do |t| t.integer :failed_attempts, default: 0 # Only if lock strategy is :fai
def change change_table :users do |t| t.integer :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts t.string :unlock_token # Only if unlock strategy is :email or :both t.datetime :locked_at end add_index :users, :unlock_token, unique: true end
532,671
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: server.go path of file: ./repos/linkerd2/controller/gen/client/clientset/versioned/typed/server/v1beta2 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 complia
func (c *servers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.Server, err error) { result = &v1beta2.Server{} err = c.client.Get(). Namespace(c.ns). Resource("servers"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return }
333,637
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.go path of file: ./repos/google-cloud-go/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateReservation the code of the file until where you have to start completion: // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under 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
func main() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in: // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &reservationpb.CreateReservationRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/cloud.google.com/go/bigquery/reservation/apiv1/reservationpb#CreateReservationRequest. } resp, err := c.CreateReservation(ctx, req) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp }
275,609
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: designsim.m path of file: ./repos/CanlabCore/CanlabCore/OptimizeDesign11/other_functions the code of the file until where you have to start completion: function [t,conse,allt,glm] = designsim(noisetype,dmodel,HRF,ISI,TR,noise_var,c,beta,S,varargin) % function [t,modelse,allt,glm] = designsim(noisetype,dmodel,HRF,ISI,TR,noise_var,c,betas,S,xcfunction [if using 'myxc'],num2avgover) % [t,modelse,allt,glm] = designsim('myxc',M.modelatTR,HRF,ISI,TR,noise_var,c,beta,fullS,xc) % % noisetype: % '1overf' : use Luis Hernandez' 1/f model with your specified noise variance
function [t,conse,allt,glm] = designsim(noisetype,dmodel,HRF,ISI,TR,noise_var,c,beta,S,varargin) % function [t,modelse,allt,glm] = designsim(noisetype,dmodel,HRF,ISI,TR,noise_var,c,betas,S,xcfunction [if using 'myxc'],num2avgover) % [t,modelse,allt,glm] = designsim('myxc',M.modelatTR,HRF,ISI,TR,noise_var,c,beta,fullS,xc) % % noisetype: % '1overf' : use Luis Hernandez' 1/f model with your specified noise variance % 'myxc' : use your own autocorrelation function and noise variance % % model = matrix of regressors (cols) sampled at frequency of ISI % noise_var = variance of 1/f noise from your scanner % c = a contrast across the regressors % beta = a list of betas to test % each beta should be a row vector, and you can have multiple rows % % S: smoothing matrix, or 0 for no smoothing. % _______________________________________________________________________ % Output is a distribution of t-scores in a vector and the maximum correlation between predictors % t-scores are in a column vector, one for each set of betas. % % Special mode: if 4 output arguments specified, 'plot mode'. Produces graph and extend
560,505
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tbx_cfg_fieldmap.m path of file: ./repos/spm12/toolbox/FieldMap the code of the file until where you have to start completion: function fieldmap = tbx_cfg_fieldmap % MATLABBATCH Configurat
function dep = vout_applyvdm(job) for k=1:numel(job.data) if job.roptions.which(1) > 0 cdep(1) = cfg_dep; cdep(1).sname = sprintf('VDM corrected images (Sess %d)', k); cdep(1).src_output = substruct('.','sess', '()',{k}, '.','rfiles'); cdep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end
331,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: common.go path of file: ./repos/go-git the code of the file until where you have to start completion: package git import "strings" // countLines returns the num
func countLines(s string) int { if s == "" { return 0 } nEOL := strings.Count(s, "\n") if strings.HasSuffix(s, "\n") { return nEOL } return nEOL + 1 }
321,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: acl_describe_response.go path of file: ./repos/fabio/vendor/github.com/Shopify/sarama the code of the file until where you have to start completion: package sarama import "time" type DescribeAclsResponse struct { ThrottleTime time.Duration Err KError ErrMsg *string ResourceAcls []*ResourceAcls } func (d *DescribeAclsResponse) encode(pe packetEncoder) error { pe.putInt32(int32(d.ThrottleTime / time.Mil
func (d *DescribeAclsResponse) decode(pd packetDecoder, version int16) (err error) { throttleTime, err := pd.getInt32() if err != nil { return err } d.ThrottleTime = time.Duration(throttleTime) * time.Millisecond kerr, err := pd.getInt16() if err != nil { return err } d.Err = KError(kerr) errmsg, err := pd.getString() if err != nil { return err } if errmsg != "" { d.ErrMsg = &errmsg } n, err := pd.getArrayLength() if err != nil { return err } d.ResourceAcls = make([]*ResourceAcls, n) for i := 0; i < n; i++ { d.ResourceAcls[i] = new(ResourceAcls) if err := d.ResourceAcls[i].decode(pd, version); err != nil { return err } } return nil }
596,675
You are an expert in writing code in many different languages. Your goal is 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.go path of file: ./repos/easegress/pkg/api the code of the file until where you have to start completion: /* * Copyright (c) 2017, The Easegress Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); *
func HandleAPIError(w http.ResponseWriter, r *http.Request, code int, err error) { w.WriteHeader(code) buff, err := codectool.MarshalJSON(Err{ Code: code, Message: err.Error(), }) if err != nil { panic(err) } w.Write(buff) }
85,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: b.go path of file: ./repos/codeforces-go/leetcode/weekly/295/b the code of the file until where you have to start completion: package main import ( "fmt" "strconv" "strings" ) // https://space.bilibili.com/206214/dynamic func discountPrices(sentence string, discount int) string { sp := strings.Split(sentence, " ") for i, s := range sp { if s[0] == '$' { if v, err :
func discountPrices(sentence string, discount int) string { sp := strings.Split(sentence, " ") for i, s := range sp { if s[0] == '$' { if v, err := strconv.Atoi(s[1:]); err == nil { sp[i] = fmt.Sprintf("$%.2f", float64(v*(100-discount))/100) } } } return strings.Join(sp, " ") }
131,063
You are an expert in writing code in many different languages. Your goal is 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/pg_trunk/lib/pg_trunk/operations/materialized_views the code of the file until where you have to start completion: # frozen_string_literal: true module PGTrunk::O
def to_h @to_h ||= attributes .symbolize_keys .transform_values(&:presence) .compact end
66,291
You are an expert in writing code in many different languages. Your goal is 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/telexide/telexide_proc_macros/src the code of the file until where you have to start completion: //! macros for subscribing to events in [telexide] //! //! [telexide]: https://crates.io/crates/telexide mod structs; mod utils; #[allow(unused_extern_cr
pub fn prepare_listener(_attr: TokenStream, item: TokenStream) -> TokenStream { let listener = parse_macro_input!(item as ListenerFunc); (quote! { #listener }) .into() }
455,794
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: string_value.go path of file: ./repos/buildkit/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil the code of the file until where you have to start completion: package awsutil import ( "bytes" "fmt" "reflect" "strings" ) // StringValue returns the string representation of a value. func StringValue(i interface{}) string { var buf bytes.Buffer stringValue(reflect.ValueOf(i), 0, &buf) return buf.String() } func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { for v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Struct: buf.WriteString("{\n") for i := 0; i < v.Type().NumField(); i++ { ft := v.Type().Field(i) fv := v.Field(i) if ft.Name[0:1] == strings.ToLower(ft.Name[0:1]) { continue // ignore unexported fields } if (fv.Kind() == reflect.Ptr || fv.K
func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { for v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Struct: buf.WriteString("{\n") for i := 0; i < v.Type().NumField(); i++ { ft := v.Type().Field(i) fv := v.Field(i) if ft.Name[0:1] == strings.ToLower(ft.Name[0:1]) { continue // ignore unexported fields } if (fv.Kind() == reflect.Ptr || fv.Kind() == reflect.Slice) && fv.IsNil() { continue // ignore unset fields } buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(ft.Name + ": ") if tag := ft.Tag.Get("sensitive"); tag == "true" { buf.WriteString("<sensitive>") } else { stringValue(fv, indent+2, buf) } buf.WriteString(",\n") } buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") case reflect.Slice: nl, id, id2 := "", "", "" if v.Len() > 3 { nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) } buf.WriteString("[" + nl) for i := 0; i < v.Len(); i++ { buf.WriteString(id2) stringValue(v.Index(i), indent+2, buf) if i < v.Len()-1 { buf.WriteString("," + nl) } } buf.WriteString(nl + id + "]") case reflect.Map: buf.WriteString("{\n") for i, k := range v.MapKeys() { buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(k.String() + ": ") stringValue(v.MapIndex(k), indent+2, buf) if i < v.Len()-1 { buf.WriteString(",\n") } } buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") default: format := "%v" switch v.Interface().(type) { case string: format = "%q" } fmt.Fprintf(buf, format, v.Interface()) } }
653,550
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: provider_cmd_myrasec.go path of file: ./repos/terraformer/cmd the code of the file until where you have to start completion: package cmd import ( myrasec_terraforming "github.com/GoogleCloudPlatform/terraformer/providers/myrasec" "github.com/GoogleCloudPlatform/terraformer/terraformutils" "github.com/spf13/cob
func newCmdMyrasecImporter(options ImportOptions) *cobra.Command { cmd := &cobra.Command{ Use: "myrasec", Short: "Import current state to Terraform configuration from Myra Security", Long: "Import current state to Terraform configuration from Myra Security", RunE: func(cmd *cobra.Command, args []string) error { provider := newMyrasecProvider() err := Import(provider, options, []string{}) if err != nil { return err } return nil }, } cmd.AddCommand(listCmd(newMyrasecProvider())) baseProviderFlags(cmd.PersistentFlags(), &options, "domain", "") return cmd }
531,521
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: retry.go path of file: ./repos/moby/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry the code of the file until where you have to start completion: // Code created by gotmpl. DO NOT MODIFY. // source: internal/shared/otlp/retry/retry.go.tmpl // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package retry provides request retry functionality that can perform // configurable exponential backoff for transient errors and honor any // explicit throttle responses received. package retry // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry"
func (c Config) RequestFunc(evaluate EvaluateFunc) RequestFunc { if !c.Enabled { return func(ctx context.Context, fn func(context.Context) error) error { return fn(ctx) } } return func(ctx context.Context, fn func(context.Context) error) error { // Do not use NewExponentialBackOff since it calls Reset and the code here // must call Reset after changing the InitialInterval (this saves an // unnecessary call to Now). b := &backoff.ExponentialBackOff{ InitialInterval: c.InitialInterval, RandomizationFactor: backoff.DefaultRandomizationFactor, Multiplier: backoff.DefaultMultiplier, MaxInterval: c.MaxInterval, MaxElapsedTime: c.MaxElapsedTime, Stop: backoff.Stop, Clock: backoff.SystemClock, } b.Reset() for { err := fn(ctx) if err == nil { return nil } retryable, throttle := evaluate(err) if !retryable { return err } bOff := b.NextBackOff() if bOff == backoff.Stop { return fmt.Errorf("max retry time elapsed: %w", err) } // Wait for the greater of the backoff or throttle delay. var delay time.Duration if bOff > throttle { delay = bOff } else { elapsed := b.GetElapsedTime() if b.MaxElapsedTime != 0 && elapsed+throttle > b.MaxElapsedTime { return fmt.Errorf("max retry time would elapse: %w", err) } delay = throttle } if ctxErr := waitFunc(ctx, delay); ctxErr != nil { return fmt.Errorf("%w: %s", ctxErr, err) } } } }
660,241
You are an expert in writing code in many different languages. Your goal is 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_link.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::{ network::{ actions::query::{query, QueryMethod}, query::{ GetLinksNetworkQuery, GetLinksNetworkResult, GetLinksQueryConfiguration, NetworkQueryResult, }, }, wasm_engine::{api::ZomeApiResult, Runtime}, workflows::author_entry::author_entry, }; use holochain_core_types::{ entry::Entry, error::HolochainError, link::{link_data::LinkData, LinkActionKind}, time::Timeout, }; use holochain_wasm_utils::api_serialization::{ get_links::{GetLinksArgs, GetLinksOptions}, link_entries::LinkEntriesArgs, }; use std::convert::TryFrom; use wasmi::{RuntimeArgs, RuntimeValue}; /// ZomeApiFunction::GetLinks function code /// args: [0] encoded MemoryAllocation as u64 /// Expected complex argument: GetLinksArgs /// Returns an HcApiReturnCode as I64 #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn invoke_remove_link(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { let context = runtime.context()?; // deserialize args let args_str = runtime.load_j
pub fn invoke_remove_link(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { let context = runtime.context()?; // deserialize args let args_str = runtime.load_json_string_from_args(&args); let input = match LinkEntriesArgs::try_from(args_str.clone()) { Ok(entry_input) => entry_input, // Exit on error Err(_) => { log_error!( context, "zome: invoke_remove_link failed to deserialize LinkEntriesArgs: {:?}", args_str ); return ribosome_error_code!(ArgumentDeserializationFailed); } }; let top_chain_header_option = context.state().unwrap().agent().top_chain_header(); let top_chain_header = match top_chain_header_option { Some(top_chain) => top_chain, None => { log_error!( context, "zome: invoke_link_entries failed to deserialize LinkEntriesArgs: {:?}", args_str ); return ribosome_error_code!(ArgumentDeserializationFailed); } }; let link = input.to_link(); let link_remove = LinkData::from_link( &link, LinkActionKind::REMOVE, top_chain_header, context.agent_id.clone(), ); let get_links_args = GetLinksArgs { entry_address: link.base().clone(), link_type: Some(link.link_type().clone()), tag: Some(link.tag().clone()), options: GetLinksOptions::default(), }; let config = GetLinksQueryConfiguration::default(); let method = QueryMethod::Link(get_links_args, GetLinksNetworkQuery::Links(config)); let response_result = context.block_on(query(context.clone(), method, Timeout::default())); if response_result.is_err() { log_error!("zome : Could not get links for remove_link method."); ribosome_error_code!(WorkflowFailed) } else { let response = response_result.expect("Could not get response"); let links_result = match response { NetworkQueryResult::Links(query, _, _) => Ok(query), NetworkQueryResult::Entry(_) => Err(HolochainError::ErrorGeneric( "Could not get links for type".to_string(), )), }; if links_result.is_err() { log_error!(context, "zome : Could not get links for remove_link method"); ribosome_error_code!(WorkflowFailed) } else { let links = links_result.expect("This is supposed to not fail"); let links = match links { GetLinksNetworkResult::Links(links) => links, _ => return ribosome_error_code!(WorkflowFailed), }; let filtered_links = links .into_iter() .filter(|link_for_filter| &link_for_filter.target == link.target()) .map(|s| s.address) .collect::<Vec<_>>(); let entry = Entry::LinkRemove((link_remove, filtered_links)); // Wait for future to be resolved let result: Result<(), HolochainError> = context .block_on(author_entry(&entry, None, &context, &vec![])) .map(|_| ()); runtime.store_result(result) } } }
150,702
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: issubfield.m path of file: ./repos/malini/Codes/deconvolution - model/spm8/external/fieldtrip/utilities the code of the file until where you have to start completion: function [r] = issubfield(s, f) % ISSUBFIELD tests for the presence of a field in a structure just like the standard % Matlab ISFIELD function, except that you can also specify nested fields % using a '.' in the fieldname. The nesting can be arbitrary deep. % % Use as % f = issubfield(s, 'fieldname') % or as % f = issubfield(s, 'fieldname.subfieldname') % % This function returns true if the field is present and false if the field % is not present. % % See also ISFIELD, GETSUBFIELD, SETSUBFIELD % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version.
function [r] = issubfield(s, f) % ISSUBFIELD tests for the presence of a field in a structure just like the standard % Matlab ISFIELD function, except that you can also specify nested fields % using a '.' in the fieldname. The nesting can be arbitrary deep. % % Use as % f = issubfield(s, 'fieldname') % or as % f = issubfield(s, 'fieldname.subfieldname') % % This function returns true if the field is present and false if the field % is not present. % % See also ISFIELD, GETSUBFIELD, SETSUBFIELD % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: issubfield.m 7123 2012-12-06 21:21:38Z roboos $ try getsubfield(s, f); % if this works, then the subfield must be present r = true; catch r = false; % apparently the subfield is not present end
387,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: mod.rs path of file: ./repos/tokio/tokio/src/time the code of the file until where you have to start completion: //! Utilities for track
//! # async fn dox() { //! let res = timeout(Duration::from_secs(1), long_future()).await; //! //! if res.is_err() { //! println!("operation timed out"); //! } //! # }
157,994
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: listener.go path of file: ./repos/IOC-golang/aop/common the code of the file until where you have to start completion: package common import ( "net" "strconv" "github.com/alibaba/ioc-golang/logger" ) func GetTCPListener(port stri
func GetTCPListener(port string) (net.Listener, error) { lst, err := net.Listen("tcp", ":"+port) for err != nil { portInt, iToAError := strconv.Atoi(port) if iToAError != nil { logger.Blue("[Debug] Debug server listening with invalid port :%s, error = %s", port, iToAError) return nil, iToAError } logger.Blue("[Debug] Debug server listening port :%s failed with error = %s, try to bind %d", port, err, portInt+1) port = strconv.Itoa(portInt + 1) lst, err = net.Listen("tcp", ":"+port) } return lst, nil }
504,452
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: wingCreateAeroelasticity.m path of file: ./repos/LADAC/aerodynamics/vlm_wing/aeroelasticity the code of the file until where you have to start completion: function aeroelasticity = wingCreateAeroelasticity( n_panels, n_structure_eig ) % wingCreateAeroelasticity defince and initialize aeroelasticity struct of % wing struct % % Inputs: % n_panels number of wing panels (scalar) % n_structure_eig number of structure eigenmodes (scalar) % % Outputs: % aeroelasticity aeroelasticity struct as defined by this function % % See also: % wingCreate, wingSetAeroelasticity % % Disclamer: % SPDX-License-Identifier: GPL-3.0-only %
function aeroelasticity = wingCreateAeroelasticity( n_panels, n_structure_eig ) % wingCreateAeroelasticity defince and initialize aeroelasticity struct of % wing struct % % Inputs: % n_panels number of wing panels (scalar) % n_structure_eig number of structure eigenmodes (scalar) % % Outputs: % aeroelasticity aeroelasticity struct as defined by this function % % See also: % wingCreate, wingSetAeroelasticity % % Disclamer: % SPDX-License-Identifier: GPL-3.0-only % % Copyright (C) 2020-2022 Yannic Beyer % Copyright (C) 2022 TU Braunschweig, Institute of Flight Guidance % ************************************************************************* % transformation matrix that maps from structure deformation state to wing % vortex position deformation (see wingSetGeometryState) aeroelasticity.T_vs = zeros( 3 * (n_panels+1), n_structure_eig ); % transformation matrix that maps from structure deformation state to wing % control point deformation (see wingSetGeometryState) aeroelasticity.T_cs = zeros( 4 * n_panels, n_structure_eig ); % transformation matrix that maps from load vector for each control point % (note that the load is applied at c/4 which is important for the pitching % moment) to structure generalized load vector aeroelasticity.T_sc = zeros( n_structure_eig, 4 * n_panels ); end
490,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: reslicing.go path of file: ./repos/the-way-to-go_ZH_CN/eBook/examples/chapter_7 the code of the file until where you have to start completion: package main import "fmt" func main() { //var slice1 []int = make([]int, 0, 10) slice1 := make([]int, 0, 10) // load the slice, cap(slice1) is 10: for i := 0; i < cap(slice1); i++ { slice1 = slice1[0 : i+1] // reslice slice1[i] = i fmt.Printf("The length of s
func main() { //var slice1 []int = make([]int, 0, 10) slice1 := make([]int, 0, 10) // load the slice, cap(slice1) is 10: for i := 0; i < cap(slice1); i++ { slice1 = slice1[0 : i+1] // reslice slice1[i] = i fmt.Printf("The length of slice is %d\n", len(slice1)) } // print the slice: for i := 0; i < len(slice1); i++ { fmt.Printf("Slice at %d is %d\n", i, slice1[i]) } }
260,668
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: proc_snmp.go path of file: ./repos/faas-netes/vendor/github.com/prometheus/procfs the code of the file until where you have to start completion: // Copyright 2022 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this fi
func (p Proc) Snmp() (ProcSnmp, error) { filename := p.path("net/snmp") data, err := util.ReadFileNoStat(filename) if err != nil { return ProcSnmp{PID: p.PID}, err } procSnmp, err := parseSnmp(bytes.NewReader(data), filename) procSnmp.PID = p.PID return procSnmp, err }
425,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: register.go path of file: ./repos/minicron/client/vendor/golang.org/x/crypto/blake2s the code of the file until where you have to start completion: // Copyright 2
func init() { newHash256 := func() hash.Hash { h, _ := New256(nil) return h } crypto.RegisterHash(crypto.BLAKE2s_256, newHash256) }
350,062
You are an expert in writing code in many different languages. Your goal is 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.go path of file: ./repos/awesome-golang-algorithm/leetcode/901-1000/0904.Fruit-Into-Baskets the code of the file until where you have to start completion: package Solution func totalFruit_1(fruits []int) int { ans, left, win := 0, 0, map[int]int{} for right, v := range fruits { win[v]++ f
func totalFruit_1(fruits []int) int { ans, left, win := 0, 0, map[int]int{} for right, v := range fruits { win[v]++ for len(win) > 2 { win[fruits[left]]-- if win[fruits[left]] == 0 { delete(win, fruits[left]) } left++ } ans = max(ans, right-left+1) } return ans }
186,216
You are an expert in writing code in many different languages. Your goal is 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_PutEmailIdentityFeedbackAttributes.go path of file: ./repos/aws-sdk-go-v2/service/pinpointemail the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package pinpointemail import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Used to enable or disable feedback forwarding for an identity. This setting // determines what happens when an identity is used to send an email that results // in a bounce or complaint event. When you enable feedback forwarding, Amazon // Pinpoint sends you email notifications when bounce or complaint events occur. // Amazon Pinpoint sends this notification to the address that you specified in the // Return-Path header of the original email. When you disable feedback forwarding, // Amazon Pinpoint sends notifications through other mechanisms, such as by // notifying an Amazon SNS topic. You're required to have a method of tracking // bounces and complaints. If you haven't set up another mechanism for receiving // bounce or complaint notifications, Amazon Pinpoint sends an email notification // when these events occur (even if this setting is disabled). func (c *Client) PutEmailIdentityFeedbackAttributes(ctx context.Context, params *PutEmailIdentityFeedbackAttributesInput, optFns ...func(*Options)) (*PutEmailIdentityFeedbackAttributesOutput, error) { if params == nil { params = &PutEmailIdentityFeedbackAttributesInput{} } result, metadata, err := c.invokeOperation(ctx, "PutEmailIdentityFeedbackAttributes", params, optFns, c.addOperationPutEmailIdentityFeedbackAttributesMiddlewares) if err != nil { return nil, err } out := result.(*PutEmailIdentityFeedbackAttributesOutput) out.ResultMetadata = metadata return out, nil } // A request to set the attributes that control how bounce and complaint events // are processed. typ
func (c *Client) addOperationPutEmailIdentityFeedbackAttributesMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsRestjson1_serializeOpPutEmailIdentityFeedbackAttributes{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpPutEmailIdentityFeedbackAttributes{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "PutEmailIdentityFeedbackAttributes"); err != nil { return fmt.Errorf("add protocol finalizers: %v", err) } if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = addClientRequestID(stack); err != nil { return err } if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addComputePayloadSHA256(stack); err != nil { return err } if err = addRetry(stack, options); err != nil { return err } if err = addRawResponseToMetadata(stack); err != nil { return err } if err = addRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { return err } if err = addOpPutEmailIdentityFeedbackAttributesValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutEmailIdentityFeedbackAttributes(options.Region), middleware.Before); err != nil { return err } if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } if err = addDisableHTTPSMiddleware(stack, options); err != nil { return err } return nil }
215,832
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: find_models_by_access.rb path of file: ./repos/hyrax/app/services/hyrax/custom_queries the code of the file until where you have to start completion: # frozen_string_literal: true module Hyrax module CustomQueries ## # @see https://github.com/samvera/valkyrie/wiki/Queries#custom-queries class FindModelsByAccess def self.queries [:find_models_by_access] end
def find_models_by_access(mode:, models: nil, agent:, group: nil) agent = "group/#{agent}" if group.present? internal_array = "{\"permissions\": [{\"mode\": \"#{mode}\", \"agent\": \"#{agent}\"}]}" if models.present? query_service.run_query(find_models_by_access_query, internal_array, models) else query_service.run_query(find_by_access_query, internal_array) end
237,480
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: oci_delete.go path of file: ./repos/podman/vendor/github.com/containers/image/v5/oci/layout the code of the file until where you have to start completion: package layout import ( "context" "encoding/json" "fmt" "io/fs" "os" "github.com/containers/image/v5/internal/set" "github.com/containers/image/v5/types" digest "github.com/opencontainers/go-digest" imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/sirupsen/logrus" "golang.org/x/exp/slices" ) // DeleteImage deletes the named image from the directory, if supported. func (ref ociReference) DeleteImag
func saveJSON(path string, content any) error { // If the file already exists, get its mode to preserve it var mode fs.FileMode existingfi, err := os.Stat(path) if err != nil { if !os.IsNotExist(err) { return err } else { // File does not exist, use default mode mode = 0644 } } else { mode = existingfi.Mode() } file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode) if err != nil { return err } defer file.Close() return json.NewEncoder(file).Encode(content) }
104,235
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _graph_status.rs path of file: ./repos/aws-sdk-rust/sdk/neptunegraph/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 `GraphStatus`, 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 not been represented as an enum /// variant in a
fn from(s: &str) -> Self { match s { "AVAILABLE" => GraphStatus::Available, "CREATING" => GraphStatus::Creating, "DELETING" => GraphStatus::Deleting, "FAILED" => GraphStatus::Failed, "RESETTING" => GraphStatus::Resetting, "SNAPSHOTTING" => GraphStatus::Snapshotting, "UPDATING" => GraphStatus::Updating, other => GraphStatus::Unknown(crate::primitives::sealed_enum_unknown::UnknownVariantValue(other.to_owned())), } }
797,942
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: interceptor_test.go path of file: ./repos/temporal/common/authorization the code of the file until where you have to start completion: // The MIT License // // Copyright (c) 2020 Temporal Technologies Inc. All rights reserved. // // Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to de
func (s *authorizerInterceptorSuite) TestIsUnauthorized() { s.mockAuthorizer.EXPECT().Authorize(ctx, nil, describeNamespaceTarget). Return(Result{Decision: DecisionDeny}, nil) s.mockMetricsHandler.EXPECT().Counter(metrics.ServiceErrUnauthorizedCounter.Name()).Return(metrics.NoopCounterMetricFunc) res, err := s.interceptor.Intercept(ctx, describeNamespaceRequest, describeNamespaceInfo, s.handler) s.Nil(res) s.Error(err) }
200,580
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: delete_policy.rs path of file: ./repos/aws-sdk-rust/sdk/mediaconvert/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 `DeletePolicy`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct DeletePolicy; impl DeletePolicy { /// Creates a new `DeletePolicy` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins, input: crate::operation::delete_policy:
pub fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::BadRequestException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::ConflictException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::ForbiddenException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::InternalServerErrorException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::NotFoundException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::TooManyRequestsException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::Unhandled(e) => &e.meta, } }
783,192
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: spm_get_defaults.m path of file: ./repos/spm12 the code of the file until where you have to start completion: function varargout = spm_get_defaults(defstr, varargin) % Get/set the defaults values associated with an identifier % FORMAT defaults = spm_get_defaults % Return the global "defaults" variable defined in spm_defaults.m. % % FORMAT defval = spm_get_defaults(defstr) % Return the defaults value associated with identifier "defstr". % Currently, this is a '.' subscript reference into the global % "defaults" variable defined in spm_defaults.m. % % FORMAT spm_get_defaults(defstr, defval) % Set the defaults value associated with identifier "defstr" to defval.
function varargout = spm_get_defaults(defstr, varargin) % Get/set the defaults values associated with an identifier % FORMAT defaults = spm_get_defaults % Return the global "defaults" variable defined in spm_defaults.m. % % FORMAT defval = spm_get_defaults(defstr) % Return the defaults value associated with identifier "defstr". % Currently, this is a '.' subscript reference into the global % "defaults" variable defined in spm_defaults.m. % % FORMAT spm_get_defaults(defstr, defval) % Set the defaults value associated with identifier "defstr" to defval. % The new defaults value applies immediately to: % * new modules in batch jobs % * modules in batch jobs that have not been saved yet % This value will not be saved for future sessions of SPM. To make % persistent changes, see help section in spm_defaults.m. %__________________________________________________________________________ % Copyright (C) 2008-2014 Wellcome Trust Centre for Neuroimaging % Volkmar Glauche % $Id: spm_get_defaults.m 6157 2014-09-05 18:17:54Z guillaume $ global defaults; if isempty(defaults) spm_defaults; end
329,433
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: latest.go path of file: ./repos/sealer/vendor/k8s.io/client-go/tools/clientcmd/api/latest the code of the file until where you have to start completion: /* Copyright 2014 The Kubernetes Authors. L
func init() { Scheme = runtime.NewScheme() utilruntime.Must(api.AddToScheme(Scheme)) utilruntime.Must(v1.AddToScheme(Scheme)) yamlSerializer := json.NewYAMLSerializer(json.DefaultMetaFactory, Scheme, Scheme) Codec = versioning.NewDefaultingCodecForScheme( Scheme, yamlSerializer, yamlSerializer, schema.GroupVersion{Version: Version}, runtime.InternalGroupVersioner, ) }
724,306
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: utils.rs path of file: ./repos/rustful/src the code of the file until where you have to start completion: use std::io::Write; use url::percent_encoding::percent_decode; use context::Parameters; pub fn parse_parameters(source: &[u8]) -> Parameters { let mut parameters = Parameters::new(); let source: Vec<u8> = so
fn parsing_strange_parameters() { let parameters = parse_parameters(b"a=1=2&=2&ab="); let a = "1".to_owned().into(); let aa = "2".to_owned().into(); let ab = "".to_owned().into(); assert_eq!(parameters.get_raw("a"), Some(&a)); assert_eq!(parameters.get_raw(""), Some(&aa)); assert_eq!(parameters.get_raw("ab"), Some(&ab)); }
324,208
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _prediction_time_range.rs path of file: ./repos/aws-sdk-rust/sdk/devopsguru/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>The time range during which anomalous behavior in a proactive anomaly or an insight is expected to occur.</p> #[non_
pub fn build(self) -> ::std::result::Result<crate::types::PredictionTimeRange, ::aws_smithy_types::error::operation::BuildError> { ::std::result::Result::Ok(crate::types::PredictionTimeRange { start_time: self.start_time.ok_or_else(|| { ::aws_smithy_types::error::operation::BuildError::missing_field( "start_time", "start_time was not specified but it is required when building PredictionTimeRange", ) })?, end_time: self.end_time, }) }
793,400
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: env.go path of file: ./repos/rules_go/go/tools/builders the code of the file until where you have to start completion: // Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the L
func envFlags(flags *flag.FlagSet) *env { env := &env{} flags.StringVar(&env.sdk, "sdk", "", "Path to the Go SDK.") flags.Var(&tagFlag{}, "tags", "List of build tags considered true.") flags.StringVar(&env.installSuffix, "installsuffix", "", "Standard library under GOROOT/pkg") flags.BoolVar(&env.verbose, "v", false, "Whether subprocess command lines should be printed") flags.BoolVar(&env.shouldPreserveWorkDir, "work", false, "if true, the temporary work directory will be preserved") return env }
65,381
You are an expert in writing code in many different languages. Your goal is 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_dem_ERP.m path of file: ./repos/spm12/toolbox/DEM the code of the file until where you have to start completion: function [R] = spm_dem_ERP(varargin) % simulated electrophysiological response based on conditional estimates % FORMAT [R] = spm_dem_ERP(qU,qU,...) % qU - conditional estimates of states % R - summed response over peri-stimulus time % % These simulated response assume that LFPs are generated by superficial % pyramidal cells that correspond to units encoding prediction error. % Peristimulus time histograms (PSTH) assume that states (U) are encoded % using a non-negative firing rate that is proportional to exp(U), using % an opponent system %__________________________________________________________________________ % loop over ERPs %-------------------------------------------------------------------------- clf N = length(varargin); color = {'r','b','g','y','c','m'}; for i = 1:N % loop over ERPs %----------------------------------------------------------------------
function [R] = spm_dem_ERP(varargin) % simulated electrophysiological response based on conditional estimates % FORMAT [R] = spm_dem_ERP(qU,qU,...) % qU - conditional estimates of states % R - summed response over peri-stimulus time % % These simulated response assume that LFPs are generated by superficial % pyramidal cells that correspond to units encoding prediction error. % Peristimulus time histograms (PSTH) assume that states (U) are encoded % using a non-negative firing rate that is proportional to exp(U), using % an opponent system %__________________________________________________________________________ % loop over ERPs %-------------------------------------------------------------------------- clf N = length(varargin); color = {'r','b','g','y','c','m'}; for i = 1:N % loop over ERPs %---------------------------------------------------------------------- qU = varargin{i}; n = length(qU.z); for j = 1:n % PST (assuming 8ms times bins) %------------------------------------------------------------------ try EEG = qU.Z{j}; catch EEG = qU.z{j}; end
331,740
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: contest_problem.rs path of file: ./repos/AtCoderProblems/atcoder-problems-backend/sql-client/src the code of the file until where you have to start completion: use crate::models::ContestProblem; use crate::PgPool; use anyhow::Result; use async_trait::async_
async fn load_contest_problem(&self) -> Result<Vec<ContestProblem>> { let problems = sqlx::query_as("SELECT contest_id, problem_id, problem_index FROM contest_problem") .fetch_all(self) .await?; Ok(problems) }
41,455
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.go path of file: ./repos/google-cloud-go/internal/generated/snippets/parallelstore/apiv1beta/Client/GetInstance the code of the file until where you have to start completion: // Copyright 2
func main() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in: // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options c, err := parallelstore.NewClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &parallelstorepb.GetInstanceRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/cloud.google.com/go/parallelstore/apiv1beta/parallelstorepb#GetInstanceRequest. } resp, err := c.GetInstance(ctx, req) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp }
280,240
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: gb_abs.m path of file: ./repos/SuiteSparse/GraphBLAS/GraphBLAS/@GrB/private the code of the file until where you have to start completion: function C = gb_abs (G) %GB_ABS Absolute value of a GraphBLAS matrix. % Implements C = abs (G) % SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2023, All Rights Reserved. % SPDX-License-Identifier: Apache-2.0 if (gb_issigned (gbtype (G)))
function C = gb_abs (G) %GB_ABS Absolute value of a GraphBLAS matrix. % Implements C = abs (G) % SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2023, All Rights Reserved. % SPDX-License-Identifier: Apache-2.0 if (gb_issigned (gbtype (G))) C = gbapply ('abs', G) ; else C = G ; end
192,816
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: exec.rb path of file: ./repos/truffleruby/lib/mri/bundler/cli the code of the file until where you have to start completion: # frozen_string_literal: true require_relative "../current_ruby" module Bundler class CLI::Exec attr_reader :options, :args, :cmd TRAPPED_SIGNALS = %w[INT].freeze def initialize
def ruby_shebang?(file) possibilities = [ "#!/usr/bin/env ruby\n", "#!/usr/bin/env jruby\n", "#!/usr/bin/env truffleruby\n", "#!#{Gem.ruby}\n", ] if File.zero?(file) Bundler.ui.warn "#{file} is empty" return false end
176,604
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: chats.go path of file: ./repos/govcl/samples/drawchart the code of the file until where you have to start completion: //---------------------------------------- // // Copyright © ying32. All Rights Reserved. // // Licensed under Apache License 2.0 // //---------------------------------------- package main import ( "fmt" "image" "image/color" "image/draw" "math" "math/rand" "sort" "time" "github.com/vdobler/chart" "github.com/vdobler
func timeRange() { factors := []int64{1, 2, 3, 5, 7, 9, 11, 15} magnitudes := []int64{1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9} steps := make([]float64, 0, len(factors)*len(magnitudes)) for _, f := range factors { for _, m := range magnitudes { steps = append(steps, float64(f)*float64(m)) } } sort.Float64s(steps) now := float64(time.Now().Unix()) for _, step := range steps { fmt.Printf("\nStep %d seconds (approx %d hours or %d weeks or %d years)\n", int64(step), int64(step/3600+0.5), int64(step/(3600*24*7)+0.5), int(step/(3600*24*365.25)+0.5)) rng := chart.Range{Time: true} rng.Init() rng.DataMin, rng.DataMax = now, now+step rng.Setup(7, 9, 90, 5, false) tg := txtg.New(120, 4) tg.XAxis(rng, 1, 0, nil) fmt.Printf("%s\n", tg.String()) } }
88,232
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: stat_bsd.go path of file: ./repos/teller/vendor/github.com/docker/docker/pkg/system the code of the file until where you have to start completion: // +build freebsd netbsd package system // import "github.com/docker/docker/pkg/system" import "syscall
func fromStatT(s *syscall.Stat_t) (*StatT, error) { return &StatT{size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), mtim: s.Mtimespec}, nil }
525,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: cartesian_tree.go path of file: ./repos/codeforces-go/copypasta the code of the file until where you have to start completion: package copypasta /* 笛卡尔树 Cartesian tree https://en.wikipedia.org/wiki/Cartesian_tree https://oi-wiki.org/ds/cartesian-tree/ todo 一些题目 https://www.luogu.com.cn/blog/AAAbbb123/di-ka-er-shu-xue-xi-bi-ji 另见单调栈 monotone_stack.go 模板题 https://www.luogu.com.cn/problem/P5
func buildCartesianTree2(a []int) [][2]int { n := len(a) lr := make([][2]int, n) for i := range lr { lr[i] = [2]int{-1, -1} } s := []int{} for i, v := range a { for len(s) > 0 { topI := s[len(s)-1] if a[topI] < v { lr[topI][1] = i break } lr[i][0] = topI s = s[:len(s)-1] } s = append(s, i) } return lr }
138,429
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: zz_generated.deepcopy.go path of file: ./repos/kuma/pkg/plugins/policies/donothingpolicy/k8s/v1alpha1 the code of the file until where you have to start completion: //go:build !ignore_autogenerated // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 i
func (in *DoNothingPolicy) DeepCopyInto(out *DoNothingPolicy) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) if in.Spec != nil { in, out := &in.Spec, &out.Spec *out = new(apiv1alpha1.DoNothingPolicy) (*in).DeepCopyInto(*out) } }
55,368
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: wmic.rb path of file: ./repos/metasploit-framework/lib/msf/core/post/windows the code of the file until where you have to start completion: # -*- coding: binary -*- module Msf class Post module Win
def initialize(info = {}) super( update_info( info, 'Compat' => { 'Meterpreter' => { 'Commands' => %w[ extapi_clipboard_get_data extapi_clipboard_set_data stdapi_railgun_api stdapi_sys_process_execute ] } } ) ) register_options([ OptString.new('SMBUser', [ false, 'The username to authenticate as' ], fallbacks: ['USERNAME']), OptString.new('SMBPass', [ false, 'The password for the specified username' ], fallbacks: ['PASSWORD']), OptString.new('SMBDomain', [ false, 'The Windows domain to use for authentication' ], fallbacks: ['DOMAIN']), OptAddress.new("RHOST", [ true, "Target address range", "localhost" ]), OptInt.new("TIMEOUT", [ true, "Timeout for WMI command in seconds", 10 ]) ], self.class) end def wmic_query(query, server=datastore['RHOST']) result_text = "" if datastore['SMBUser'] if server.downcase == "localhost" || server.downcase.starts_with?('127.') raise RuntimeError, "WMIC: User credentials cannot be used for local connections" end end
738,268
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: http_callback.rb path of file: ./repos/lita/lib/lita the code of the file until where you have to start completion: # frozen_string_literal: true require "rack" module Lita # A wrapper around a handler's HTTP route callbacks that sets up the request and response. # @api private # @since 4.0.0 class HTTPCallback # @param handler_class [Handler] The handler defining the callback. # @param callback [Proc] The callba
def call(env) request = Rack::Request.new(env) response = Rack::Response.new if request.head? response.status = 204 else begin handler = @handler_class.new(env["lita.robot"]) @callback.call(handler, request, response) rescue StandardError => e robot = env["lita.robot"] error_handler = robot.config.robot.error_handler if error_handler.arity == 2 error_handler.call(e, rack_env: env, robot: robot) else error_handler.call(e) end
111,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: gogs_test.go path of file: ./repos/gitea/services/migrations the code of the file until where you have to start completion: // Copyright 2019 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package migrations import ( "context" "net/http" "os" "testing" "time" base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" ) func TestGogsDownloadRepo(t *testing.T) { // Skip tests if Gogs token is not found gogsPersonalAccessToken := os.Getenv("GOGS_READ_TOKEN") if len(gogsPersonalAccessToken) == 0 { t.Skip("skipped test because GOGS_READ_TOKEN was not in the environment") } resp, err := http.Get("https://try.gogs.io/lunnytest/TESTREPO") if err != nil || resp.StatusCode/100 != 2 { // skip and don't run test t.Skipf("visit test repo failed, ignored") return } downloader := NewGogsDownloader(context.Background(), "https://try.gogs.io", "", "", gogsPersonalAccessToken, "lunnytest", "TESTREPO") repo, err := downloader.GetRepoInfo() assert.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "TESTREPO", Owner: "lunnytest", Description: "", CloneURL: "https://try.gogs.io/lunnytest/TESTREPO.git", OriginalURL: "https://try.gogs.io/lunnytest/TESTREPO", DefaultBranch: "master", }, repo) milestones, err := downloader.GetMilesto
func TestGogsDownloadRepo(t *testing.T) { // Skip tests if Gogs token is not found gogsPersonalAccessToken := os.Getenv("GOGS_READ_TOKEN") if len(gogsPersonalAccessToken) == 0 { t.Skip("skipped test because GOGS_READ_TOKEN was not in the environment") } resp, err := http.Get("https://try.gogs.io/lunnytest/TESTREPO") if err != nil || resp.StatusCode/100 != 2 { // skip and don't run test t.Skipf("visit test repo failed, ignored") return } downloader := NewGogsDownloader(context.Background(), "https://try.gogs.io", "", "", gogsPersonalAccessToken, "lunnytest", "TESTREPO") repo, err := downloader.GetRepoInfo() assert.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "TESTREPO", Owner: "lunnytest", Description: "", CloneURL: "https://try.gogs.io/lunnytest/TESTREPO.git", OriginalURL: "https://try.gogs.io/lunnytest/TESTREPO", DefaultBranch: "master", }, repo) milestones, err := downloader.GetMilestones() assert.NoError(t, err) assertMilestonesEqual(t, []*base.Milestone{ { Title: "1.0", State: "open", }, }, milestones) labels, err := downloader.GetLabels() assert.NoError(t, err) assertLabelsEqual(t, []*base.Label{ { Name: "bug", Color: "ee0701", }, { Name: "duplicate", Color: "cccccc", }, { Name: "enhancement", Color: "84b6eb", }, { Name: "help wanted", Color: "128a0c", }, { Name: "invalid", Color: "e6e6e6", }, { Name: "question", Color: "cc317c", }, { Name: "wontfix", Color: "ffffff", }, }, labels) // downloader.GetIssues() issues, isEnd, err := downloader.GetIssues(1, 8) assert.NoError(t, err) assert.False(t, isEnd) assertIssuesEqual(t, []*base.Issue{ { Number: 1, PosterID: 5331, PosterName: "lunny", PosterEmail: "xiaolunwen@gmail.com", Title: "test", Content: "test", Milestone: "", State: "open", Created: time.Date(2019, 6, 11, 8, 16, 44, 0, time.UTC), Updated: time.Date(2019, 10, 26, 11, 7, 2, 0, time.UTC), Labels: []*base.Label{ { Name: "bug", Color: "ee0701", }, }, }, }, issues) // downloader.GetComments() comments, _, err := downloader.GetComments(&base.Issue{Number: 1, ForeignIndex: 1}) assert.NoError(t, err) assertCommentsEqual(t, []*base.Comment{ { IssueIndex: 1, PosterID: 5331, PosterName: "lunny", PosterEmail: "xiaolunwen@gmail.com", Created: time.Date(2019, 6, 11, 8, 19, 50, 0, time.UTC), Updated: time.Date(2019, 6, 11, 8, 19, 50, 0, time.UTC), Content: "1111", }, { IssueIndex: 1, PosterID: 15822, PosterName: "clacplouf", PosterEmail: "test1234@dbn.re", Created: time.Date(2019, 10, 26, 11, 7, 2, 0, time.UTC), Updated: time.Date(2019, 10, 26, 11, 7, 2, 0, time.UTC), Content: "88888888", }, }, comments) // downloader.GetPullRequests() _, _, err = downloader.GetPullRequests(1, 3) assert.Error(t, err) }
649,531
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: unlock_keychain.rb path of file: ./repos/fastlane/fastlane/lib/fastlane/actions the code of the file until where you have to start completion: module Fastlane module Actions class UnlockKeychainAction < Action def self.run(params) keychain_path = FastlaneCore::Helper.keychain_path
def self.add_keychain_to_search_list(keychain_path) keychains = Fastlane::Actions.sh("security list-keychains -d user", log: false).shellsplit # add the keychain to the keychain list unless keychains.include?(keychain_path) keychains << keychain_path Fastlane::Actions.sh("security list-keychains -s #{keychains.shelljoin}", log: false) end
261,055
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: quick_sort_3_ways.rs path of file: ./repos/Rust/src/sorting the code of the file until where you have to start completion: use std::cmp::{Ord, Ordering}; use rand::Rng; fn _quick_sort_3_ways<T: Ord>(arr: &mut [T], lo: usize, hi: usize) { if lo >= hi { return; } let mut rng = ran
fn pre_sorted() { let mut res = sort_utils::generate_nearly_ordered_vec(300000, 0); let cloned = res.clone(); sort_utils::log_timed("pre sorted", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); }
368,707
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 803A_test.go path of file: ./repos/codeforces-go/main/800-899 the code of the file until where you have to start completion: // Code generated by copypasta/template/generator_test.go package main import ( "github.com/EndlessCheng/codeforces-go/main/testutil" "testing" ) //
func Test_cf803A(t *testing.T) { testCases := [][2]string{ { `2 1`, `1 0 0 0`, }, { `3 2`, `1 0 0 0 1 0 0 0 0`, }, { `2 5`, `-1`, }, } testutil.AssertEqualStringCase(t, testCases, 0, cf803A) }
133,019
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: displayData.m path of file: ./repos/machine_learning_from_scratch_matlab_python/algorithms_in_matlab/week_8/ex7 the code of the file until where you have to start completion: function [h, display_array] = displayData(X, example_width) %DISPLAYDATA Display 2D data in a nice grid % [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data % stored in X in a nice grid. It returns the figure handle h and the
function [h, display_array] = displayData(X, example_width) %DISPLAYDATA Display 2D data in a nice grid % [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data % stored in X in a nice grid. It returns the figure handle h and the % displayed array if requested. % Set example_width automatically if not passed in if ~exist('example_width', 'var') || isempty(example_width) example_width = round(sqrt(size(X, 2))); end
676,693
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: check_test.go path of file: ./repos/dep-tree/internal/check the code of the file until where you have to start completion: package check import ( "strings" "testing" "github.com/gabotechs/dep-tree/internal/graph" "github.com/stretchr/testify/require" ) func TestCheck(t *testing.T) { tests := []struct { Name string Spec [][]int Config *Config Failures []string }{ { Name: "Simple", Spec: [][]int{ 0: {1, 2, 3}, 1: {2, 4}, 2: {3, 4}, 3: {4}, 4: {3}, }, Config: &Config{ Entrypoints: []string{"0"}, WhiteList: map[string][]string{ "4": {}, }, BlackList: map[string][]string{ "0": {"3"}, }, }, Failures: []string{ "0 -> 3", "4 -> 3", "detected circular dependency: 4 -> 3 -> 4", }, }, } for _, tt := range tests { t.Run(tt.Name, func(t *testing.T) { a := require.New(t) err := Check[[]int]( &graph.TestParser{Spec: tt.Spec}, func(node *graph.Node[[]int]) string { return node.Id }, tt.Config, nil, ) if tt.Failures
func TestCheck(t *testing.T) { tests := []struct { Name string Spec [][]int Config *Config Failures []string }{ { Name: "Simple", Spec: [][]int{ 0: {1, 2, 3}, 1: {2, 4}, 2: {3, 4}, 3: {4}, 4: {3}, }, Config: &Config{ Entrypoints: []string{"0"}, WhiteList: map[string][]string{ "4": {}, }, BlackList: map[string][]string{ "0": {"3"}, }, }, Failures: []string{ "0 -> 3", "4 -> 3", "detected circular dependency: 4 -> 3 -> 4", }, }, } for _, tt := range tests { t.Run(tt.Name, func(t *testing.T) { a := require.New(t) err := Check[[]int]( &graph.TestParser{Spec: tt.Spec}, func(node *graph.Node[[]int]) string { return node.Id }, tt.Config, nil, ) if tt.Failures != nil { msg := err.Error() failures := strings.Split(msg, "\n") failures = failures[1:] a.Equal(tt.Failures, failures) } }) } }
122,989