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: countries_controller.rb path of file: ./repos/beer.db/beerdb-admin/engine/app/controllers/beer_db_admin the code of the file until where you have to start completion: # encoding: utf-8 module BeerDbAdmin class Countries
def shortcut order = params[:order] || 'title' if order == 'key' @order_clause = 'key' elsif order == 'hl' @order_clause = 'prod desc, title' elsif order == 'adr' @order_clause = 'address, title' else # by_title @order_clause = 'title' end
8,211
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: pointwise_KM_STP_optimization.m path of file: ./repos/OPEN_FPE_IFT/.previousVersions/V4 Functions the code of the file until where you have to start completion: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This function performs the pointwise optimization of Kramers-Moyal coefficients % $D^{(1,2)}\left(u_r,r\right)$ at each scale and value of velocity increment to minimize possible % uncertainties in the absolute values of the Kramers-Moyal coefficients. The object of this % optimization is to find the best Fokker-Planck equation to reproduce the conditional PDF's as % these are the essential part of the Markov process. This optimization procedure is proposed in % \cite{kleinhans2005iterative,Nawroth2007,Reinke2018} and it includes the reconstruction of the % conditional probability density functions $p\left(u_{r'} | u_r \right)$ via the short time % propagator \cite{Risken}. The optimization procedure systematically changes % $D^{(1,2)}\left(u_r,r\right)$ until the error function is minimized. % % Arguments IN % evaluated = struct array calculated in the function 'conditional_moment' % scal = A scale number which needs to be optimized % increment_bin = number of bins % markov = markov length in number of samples % data = filtered data % Fs = Acquisition/Sampling Frequency in Hz % tol = Optimization: Tolerance of the range of Kramers-Moyal coefficients in % % It is the percentage(For Ex: 0.1 for 10 percent or 0.2 for 20 percent)of D1 or D2 % within these limit which you want to optimize these coeffcients D
function performs the pointwise optimization of Kramers-Moyal coefficients % $D^{(1,2)}\left(u_r,r\right)$ at each scale and value of velocity increment to minimize possible % uncertainties in the absolute values of the Kramers-Moyal coefficients. The object of this % optimization is to find the best Fokker-Planck equation to reproduce the conditional PDF's as % these are the essential part of the Markov process. This optimization procedure is proposed in % \cite{kleinhans2005iterative,Nawroth2007,Reinke2018} and it includes the reconstruction of the % conditional probability density functions $p\left(u_{r'} | u_r \right)$ via the short time % propagator \cite{Risken}. The optimization procedure systematically changes % $D^{(1,2)}\left(u_r,r\right)$ until the error function is minimized. % % Arguments IN % evaluated = struct array calculated in the function 'conditional_moment' % scal = A scale number which needs to be optimized % increment_bin = number of bins % markov = markov length in number of samples % data = filtered data % Fs = Acquisition/Sampling Frequency in Hz % tol = Optimization: Tolerance of the range of Kramers-Moyal coefficients in % % It is the percentage(For Ex: 0.1 for 10 percent or 0.2 for 20 percent)of D1 or D2 % within these limit which you want to optimize these coeffcients D1 & D2 % m_data = mean of the data % taylor_L = Taylor length scale in meters % test_opti = weather to plot or not ==> 'Plot? 1=Yes, 0=No' % multi_point = weather to do multi-point analysis or not 1=Yes, 0=No % condition = condition for multi-point analysis % tol_point = This input is for multipoint statistics % min_events = minimum number of events % k = Multi-point number of point condition % % Arguments OUT % evaluated = a modified/updated struct 'evaluated' array after the optimization at each scale and at each bin for D1 & D2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [evaluated]=pointwise_KM_STP_optimization(evaluated,scal,increment_bin,markov,data,Fs,tol,m_data,taylor_L,test_opti,multi_point,condition,tol_point,min_events,k,norm_ur,norm_r,save_path) % Initial D1 and D2 before optimization clear x0 x0(1,1:2*sum(evaluated(scal).x_bin_not_nan))=[(evaluated(scal).D1(evaluated(scal).x_bin_not_nan)),(abs(evaluated(scal).D2(evaluated(scal).x_bin_not_nan)))]; tau1 = evaluated(scal).r_short_sample; tau2 = evaluated(scal).r_samp; x_bin_not_nan = evaluated(scal).x_bin_not_nan; D1 = evaluated(scal).D1; D2 = evaluated(scal).D2; eD1 = evaluated(scal).eD1; eD2 = evaluated(scal).eD2; x_mean_bin = evaluated(scal).x_mean_bin; y_mean_bin = evaluated(scal).y_mean_bin; if multi_point==1 [incr1,incr2] = Increment_point(tau1,tau2,data,condition(k),tol_point); elseif multi_point==0 [incr1,incr2] = Increment(tau1,tau2,data); end
662,598
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: request_review_service.rb path of file: ./repos/gitlabhq/app/services/merge_requests the code of the file until where you have to start completion: # frozen_string_literal: true module MergeRequests class RequestReviewService < MergeRequests::BaseService def execute(merge_request, user) return error("Invalid permissions") unless can?(current_user, :update_merge_request, merge_request) reviewer = merge_request.find_reviewer(user) if reviewer return error("Failed to update reviewer") unless reviewer.update(state: :unreviewed) notify_reviewer(merge_request, user)
def execute(merge_request, user) return error("Invalid permissions") unless can?(current_user, :update_merge_request, merge_request) reviewer = merge_request.find_reviewer(user) if reviewer return error("Failed to update reviewer") unless reviewer.update(state: :unreviewed) notify_reviewer(merge_request, user) trigger_merge_request_reviewers_updated(merge_request) create_system_note(merge_request, user) remove_approval(merge_request) success else error("Reviewer not found") end
301,804
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: file_test.go path of file: ./repos/google-cloud-go/bigquery the code of the file until where you have to start completion: // Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License i
func TestFileConfigPopulateExternalDataConfig(t *testing.T) { testcases := []struct { description string fileConfig *FileConfig want *bq.ExternalDataConfiguration }{ { description: "json defaults", fileConfig: &FileConfig{ SourceFormat: JSON, }, want: &bq.ExternalDataConfiguration{ SourceFormat: "NEWLINE_DELIMITED_JSON", }, }, { description: "csv fileconfig", fileConfig: &fc, want: &bq.ExternalDataConfiguration{ SourceFormat: "CSV", Autodetect: true, MaxBadRecords: 7, IgnoreUnknownValues: true, Schema: &bq.TableSchema{ Fields: []*bq.TableFieldSchema{ bqStringFieldSchema(), bqNestedFieldSchema(), }}, CsvOptions: &bq.CsvOptions{ AllowJaggedRows: true, AllowQuotedNewlines: true, Encoding: "UTF-8", FieldDelimiter: "\t", Quote: &hyphen, SkipLeadingRows: 8, NullMarker: "marker", PreserveAsciiControlCharacters: true, }, }, }, { description: "parquet", fileConfig: &FileConfig{ SourceFormat: Parquet, ParquetOptions: &ParquetOptions{ EnumAsString: true, EnableListInference: true, }, }, want: &bq.ExternalDataConfiguration{ SourceFormat: "PARQUET", ParquetOptions: &bq.ParquetOptions{ EnumAsString: true, EnableListInference: true, }, }, }, } for _, tc := range testcases { got := &bq.ExternalDataConfiguration{} tc.fileConfig.populateExternalDataConfig(got) if diff := testutil.Diff(got, tc.want); diff != "" { t.Errorf("case %s, got=-, want=+:\n%s", tc.description, diff) } } }
275,324
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: install_command.rb path of file: ./repos/ruby-packer/ruby/lib/rubygems/commands the code of the file until where you have to start completion: # frozen_string_literal: true require 'rubygems/command' require 'rubygems/install_update_options' require 'rubygems/dependency_installer' require 'rub
def initialize defaults = Gem::DependencyInstaller::DEFAULT_OPTIONS.merge({ :format_executable => false, :lock => true, :suggest_alternate => true, :version => Gem::Requirement.default, :without_groups => [], }) super 'install', 'Install a gem into the local repository', defaults add_install_update_options add_local_remote_options add_platform_option add_version_option add_prerelease_option "to be installed. (Only for listed gems)" @installed_specs = [] end
750,132
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _1176_diet_plan_performance.rs path of file: ./repos/rustgym/leetcode/src/d11 the code of the file until where you have to start completion: struct Solution; impl Solution { fn update(sum: i32, lower: i32, upper: i32, point: &mut i32) { if sum < lower { *point -= 1; } if sum > upper { *point += 1; } }
fn test() { let calories: Vec<i32> = vec![1, 2, 3, 4, 5]; let k = 1; let lower = 3; let upper = 3; let res = 0; assert_eq!( Solution::diet_plan_performance(calories, k, lower, upper), res ); let calories: Vec<i32> = vec![3, 2]; let k = 2; let lower = 0; let upper = 1; let res = 1; assert_eq!( Solution::diet_plan_performance(calories, k, lower, upper), res ); let calories: Vec<i32> = vec![6, 5, 0, 0]; let k = 2; let lower = 1; let upper = 5; let res = 0; assert_eq!( Solution::diet_plan_performance(calories, k, lower, upper), res ); }
71,911
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tl_report_reason_gen.go path of file: ./repos/td/tg the code of the file until where you have to start completion: // Code generated by gotdgen, DO NOT EDIT. package tg import ( "context" "errors" "fmt" "sort" "strings" "go.uber.org/multierr" "github.com/gotd/td/bin" "
func (i *InputReportReasonChildAbuse) Decode(b *bin.Buffer) error { if i == nil { return fmt.Errorf("can't decode inputReportReasonChildAbuse#adf44ee3 to nil") } if err := b.ConsumeID(InputReportReasonChildAbuseTypeID); err != nil { return fmt.Errorf("unable to decode inputReportReasonChildAbuse#adf44ee3: %w", err) } return i.DecodeBare(b) }
480,847
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_matcher.rs path of file: ./repos/ripgrep/crates/matcher/tests the code of the file until where you have to start completion: use { grep_matcher::{Captures, Match, Matcher}, regex::bytes::Regex, }; use crate::util::{RegexMatcher, RegexMatcherNoCaps}; fn matcher(pattern: &str) -> RegexMatcher { RegexMatcher::new(Regex::new(pattern).unwrap()) } fn matcher_no_caps(pattern: &str) -> RegexMatcherNoCaps { RegexMatcherNoCaps(Regex::new(pattern).unwrap()) } fn m(start: usize, end: usize) -> Match { Match::new(start, end) } #[test] fn find() { let matcher = matcher(r"(\w+)\s+(\w+)"); assert_eq!(matcher.find(b" homer simpson ").unwrap(), Some(m(1, 14))); } #[test] fn find_iter() { let matcher
fn replace_with_captures() { let matcher = matcher(r"(\w+)\s+(\w+)"); let haystack = b"aa bb cc dd"; let mut caps = matcher.new_captures().unwrap(); let mut dst = vec![]; matcher .replace_with_captures(haystack, &mut caps, &mut dst, |caps, dst| { caps.interpolate( |name| matcher.capture_index(name), haystack, b"$2 $1", dst, ); true }) .unwrap(); assert_eq!(dst, b"bb aa dd cc"); // Test that replacements respect short circuiting. dst.clear(); matcher .replace_with_captures(haystack, &mut caps, &mut dst, |caps, dst| { caps.interpolate( |name| matcher.capture_index(name), haystack, b"$2 $1", dst, ); false }) .unwrap(); assert_eq!(dst, b"bb aa cc dd"); }
85,618
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: view_catalog.rs path of file: ./repos/risingwave/src/frontend/src/catalog the code of the file until where you have to start completion: // Copyright 2024 RisingWave Labs // // Licensed under the
fn from(view: &PbView) -> Self { ViewCatalog { id: view.id, name: view.name.clone(), owner: view.owner, properties: WithOptions::new(view.properties.clone()), sql: view.sql.clone(), columns: view.columns.iter().map(|f| f.into()).collect(), } }
405,015
You are an expert in writing code in many different languages. Your goal is 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_client_test.go path of file: ./repos/aws-sdk-go-v2/service/emr the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package emr import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "io/ioutil" "net/http" "strings" "testing" ) func TestClient_resolveRetryOptions(t *testing.T) { nopClient := smithyhttp.ClientDoFunc(func(_ *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, Header: http.Header{}, Body: ioutil.NopCloser(strings.NewReader("")), }, nil }) cases := map[string]struct { defaultsMode aws.DefaultsMode retryer aws.Retryer retryMaxAttempts int opRetryMaxAttempts *int retryMode aws.RetryMode expectClientRetryMode aws.RetryMode expectClientMaxAttempts int expectOpMaxAttempts int }{ "defaults": { defaultsMode: aws.DefaultsModeStandard, expectClientRetryMode: aws.RetryModeStandard, expectClientMaxAttempts: 3, expectOpMaxAttempts: 3, }, "custom default retry": { retryMode: aws.RetryModeAdaptive, retryMaxAttempts: 10, expec
func TestClient_resolveRetryOptions(t *testing.T) { nopClient := smithyhttp.ClientDoFunc(func(_ *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, Header: http.Header{}, Body: ioutil.NopCloser(strings.NewReader("")), }, nil }) cases := map[string]struct { defaultsMode aws.DefaultsMode retryer aws.Retryer retryMaxAttempts int opRetryMaxAttempts *int retryMode aws.RetryMode expectClientRetryMode aws.RetryMode expectClientMaxAttempts int expectOpMaxAttempts int }{ "defaults": { defaultsMode: aws.DefaultsModeStandard, expectClientRetryMode: aws.RetryModeStandard, expectClientMaxAttempts: 3, expectOpMaxAttempts: 3, }, "custom default retry": { retryMode: aws.RetryModeAdaptive, retryMaxAttempts: 10, expectClientRetryMode: aws.RetryModeAdaptive, expectClientMaxAttempts: 10, expectOpMaxAttempts: 10, }, "custom op max attempts": { retryMode: aws.RetryModeAdaptive, retryMaxAttempts: 10, opRetryMaxAttempts: aws.Int(2), expectClientRetryMode: aws.RetryModeAdaptive, expectClientMaxAttempts: 10, expectOpMaxAttempts: 2, }, "custom op no change max attempts": { retryMode: aws.RetryModeAdaptive, retryMaxAttempts: 10, opRetryMaxAttempts: aws.Int(10), expectClientRetryMode: aws.RetryModeAdaptive, expectClientMaxAttempts: 10, expectOpMaxAttempts: 10, }, "custom op 0 max attempts": { retryMode: aws.RetryModeAdaptive, retryMaxAttempts: 10, opRetryMaxAttempts: aws.Int(0), expectClientRetryMode: aws.RetryModeAdaptive, expectClientMaxAttempts: 10, expectOpMaxAttempts: 10, }, } for name, c := range cases { t.Run(name, func(t *testing.T) { client := NewFromConfig(aws.Config{ DefaultsMode: c.defaultsMode, Retryer: func() func() aws.Retryer { if c.retryer == nil { return nil } return func() aws.Retryer { return c.retryer } }(), HTTPClient: nopClient, RetryMaxAttempts: c.retryMaxAttempts, RetryMode: c.retryMode, }, func(o *Options) { if o.Retryer == nil { t.Errorf("retryer must not be nil in functional options") } }) if e, a := c.expectClientRetryMode, client.options.RetryMode; e != a { t.Errorf("expect %v retry mode, got %v", e, a) } if e, a := c.expectClientMaxAttempts, client.options.Retryer.MaxAttempts(); e != a { t.Errorf("expect %v max attempts, got %v", e, a) } _, _, err := client.invokeOperation(context.Background(), "mockOperation", struct{}{}, []func(*Options){ func(o *Options) { if c.opRetryMaxAttempts == nil { return } o.RetryMaxAttempts = *c.opRetryMaxAttempts }, }, func(s *middleware.Stack, o Options) error { s.Initialize.Clear() s.Serialize.Clear() s.Build.Clear() s.Finalize.Clear() s.Deserialize.Clear() if e, a := c.expectOpMaxAttempts, o.Retryer.MaxAttempts(); e != a { t.Errorf("expect %v op max attempts, got %v", e, a) } return nil }) if err != nil { t.Fatalf("expect no operation error, got %v", err) } }) } }
216,493
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: model_attempt_statistics_response.go path of file: ./repos/svix-webhooks/go/internal/openapi the code of the file until where you have to start completion: /* * Svix API * * No description provided (generated by Openapi Generator https://github.com/op
func (o *AttemptStatisticsResponse) GetStartDate() time.Time { if o == nil { var ret time.Time return ret } return o.StartDate }
663,711
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mssql.go path of file: ./repos/scan4all/vendor/github.com/denisenkom/go-mssqldb the code of the file until where you have to start completion: package mssql import ( "context" "database/sql" "database/sql
func (d *Driver) OpenConnector(dsn string) (*Connector, error) { params, _, err := msdsn.Parse(dsn) if err != nil { return nil, err } return &Connector{ params: params, driver: d, }, nil }
143,641
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _target_description.rs path of file: ./repos/aws-sdk-rust/sdk/elasticloadbalancingv2/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Information a
pub fn build(self) -> crate::types::TargetDescription { crate::types::TargetDescription { id: self.id, port: self.port, availability_zone: self.availability_zone, } }
768,193
You are an expert in writing code in many different languages. Your goal is 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/transcribe/src/operation/update_vocabulary the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
757,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: node_update.go path of file: ./repos/docker-ce/components/engine/client the code of the file until where you have to start completion: package client // import "github.com/docker/docker/client" import ( "context" "net/url" "strconv" "github.com/docker/docker/api/types/swarm" ) // NodeUpdate updates a Node. func (cli *Client) Nod
func (cli *Client) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error { query := url.Values{} query.Set("version", strconv.FormatUint(version.Index, 10)) resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, node, nil) ensureReaderClosed(resp) return err }
563,730
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: pay_test.go path of file: ./repos/gopay/allinpay the code of the file until where you have to start completion: package allinpay import ( "testing" "github.com/go-pay/gopay" "github.com/go-pay/xlog" ) func TestClient_ScanPay(t *testing.T) { // 扫码支付 // 请求参数 bm := make(gopay.BodyMap) bm.S
func TestClient_Cancel(t *testing.T) { // 订单退款 bm := make(gopay.BodyMap) bm.Set("trxamt", "1"). Set("reqsn", "cclarry01"). Set("remark", "支付测试取消"). Set("oldreqsn", "larry01") // 取消订单 resp, err := client.Cancel(ctx, bm) xlog.Debugf("allRsp:%+v", resp) if err != nil { xlog.Errorf("%+v", err) return } }
113,518
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tcp_server.rs path of file: ./repos/mio/examples the code of the file until where you have to start completion: // You can run this example from the root of the mio repo: // cargo run --example tcp_
fn main() -> io::Result<()> { env_logger::init(); // Create a poll instance. let mut poll = Poll::new()?; // Create storage for events. let mut events = Events::with_capacity(128); // Setup the TCP server socket. let addr = "127.0.0.1:9000".parse().unwrap(); let mut server = TcpListener::bind(addr)?; // Register the server with poll we can receive events for it. poll.registry() .register(&mut server, SERVER, Interest::READABLE)?; // Map of `Token` -> `TcpStream`. let mut connections = HashMap::new(); // Unique token for each incoming connection. let mut unique_token = Token(SERVER.0 + 1); println!("You can connect to the server using `nc`:"); println!(" $ nc 127.0.0.1 9000"); println!("You'll see our welcome message and anything you type will be printed here."); loop { if let Err(err) = poll.poll(&mut events, None) { if interrupted(&err) { continue; } return Err(err); } for event in events.iter() { match event.token() { SERVER => loop { // Received an event for the TCP server socket, which // indicates we can accept an connection. let (mut connection, address) = match server.accept() { Ok((connection, address)) => (connection, address), Err(e) if e.kind() == io::ErrorKind::WouldBlock => { // If we get a `WouldBlock` error we know our // listener has no more incoming connections queued, // so we can return to polling and wait for some // more. break; } Err(e) => { // If it was any other kind of error, something went // wrong and we terminate with an error. return Err(e); } }; println!("Accepted connection from: {}", address); let token = next(&mut unique_token); poll.registry().register( &mut connection, token, Interest::READABLE.add(Interest::WRITABLE), )?; connections.insert(token, connection); }, token => { // Maybe received an event for a TCP connection. let done = if let Some(connection) = connections.get_mut(&token) { handle_connection_event(poll.registry(), connection, event)? } else { // Sporadic events happen, we can safely ignore them. false }; if done { if let Some(mut connection) = connections.remove(&token) { poll.registry().deregister(&mut connection)?; } } } } } } }
320,689
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 1198B_test.go path of file: ./repos/codeforces-go/main/1100-1199 the code of the file until where you have to start completion: // Generated by copypasta/template/generator_test.go package main import ( "fmt" "github.com/EndlessCheng/codeforces-go/main/testutil" "io" "testing" ) // https://codeforces.com/problemset/problem/1198/B // https://codeforces.com/problemset/status/1198/problem/B func Test_cf1198B(t *testing.T) { testCases := [][2]string{ { `4 1 2 3 4 3 2 3 1 2 2 2 1`, `3 2 3 4`, }, { `5 3 50 2 1 10 3 1 2 0 2 8 1 3 20`, `8 8 20 8 10`, }, { `1 0 4 2 5 1 1 0 2 2 2 4`, `4`, }, } testutil.AssertEqualStringCase(t, testCases, 0, cf1198B) } func TestCompare_cf1198B(_t *testing.T) { return testutil.DebugTLE = 0 rg := testutil.NewRandGenerator() inputGenerator := func() string { //return `` rg.Clear() n := rg.Int(1, 9) rg.NewLine() rg.IntSlice(n, 0, 5) q := rg.Int(1,9) rg.NewLine() for i := 0; i < q; i++ { if rg.Int(1,2) ==1 { rg.Int(1,n) } rg.Int(0,5) rg.NewLine() } return rg.String() } // 暴力算法 runBF := func(in io.Reader, out io.Writer) { var n int fmt.Fscan(in, &n) a := make([]int, n) for i := range a { fmt.Fscan(in, &a[i]) } lastIdx := make([]int, n) for i := range lastIdx
func TestCompare_cf1198B(_t *testing.T) { return testutil.DebugTLE = 0 rg := testutil.NewRandGenerator() inputGenerator := func() string { //return `` rg.Clear() n := rg.Int(1, 9) rg.NewLine() rg.IntSlice(n, 0, 5) q := rg.Int(1,9) rg.NewLine() for i := 0; i < q; i++ { if rg.Int(1,2) ==1 { rg.Int(1,n) } rg.Int(0,5) rg.NewLine() } return rg.String() } // 暴力算法 runBF := func(in io.Reader, out io.Writer) { var n int fmt.Fscan(in, &n) a := make([]int, n) for i := range a { fmt.Fscan(in, &a[i]) } lastIdx := make([]int, n) for i := range lastIdx { lastIdx[i] = -1 } var q int fmt.Fscan(in, &q) events := make([]int, q) payouts := make([]int, q) for i := range events { var op int fmt.Fscan(in, &op) if op == 1 { var p, x int fmt.Fscan(in, &p) fmt.Fscan(in, &x) p-- lastIdx[p] = i a[p] = x } else if op == 2 { fmt.Fscan(in, &payouts[i]) } else { panic("impossible") } } accPayouts := make([]int, q+1) for i := q - 1; i >= 0; i-- { accPayouts[i] = max(accPayouts[i+1], payouts[i]) } for i := 0; i < n; i++ { li := lastIdx[i] fmt.Fprintf(out, "%d ", max(a[i], accPayouts[li+1])) } fmt.Fprintln(out) } testutil.AssertEqualRunResultsInf(_t, inputGenerator, runBF, cf1198B) }
134,971
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: version.go path of file: ./repos/vault/helper/versions the code of the file until where you have to start completion: // Copyright (c) HashiCorp, Inc. // SPD
func IsBuiltinVersion(v string) bool { semanticVersion, err := semver.NewSemver(v) if err != nil { return false } metadataIdentifiers := strings.Split(semanticVersion.Metadata(), ".") for _, identifier := range metadataIdentifiers { if identifier == BuiltinMetadata { return true } } return false }
314,185
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: dot.rs path of file: ./repos/argmin/crates/argmin-math/src/nalgebra_m the code of the file until where you have to start completion: // Copyright 2018-2024 argmin developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use crate::ArgminDot; u
fn [<test_primitive_mat_ $t>]() { let a = Matrix3::new( 1 as $t, 2 as $t, 3 as $t, 4 as $t, 5 as $t, 6 as $t, 3 as $t, 2 as $t, 1 as $t ); let res = Matrix3::new( 2 as $t, 4 as $t, 6 as $t, 8 as $t, 10 as $t, 12 as $t, 6 as $t, 4 as $t, 2 as $t ); let product: Matrix3<$t> = <$t as ArgminDot<Matrix3<$t>, Matrix3<$t>>>::dot(&(2 as $t), &a); for i in 0..3 { for j in 0..3 { assert_relative_eq!(res[(i, j)] as f64, product[(i, j)] as f64, epsilon = std::f64::EPSILON); } } }
15,842
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: vocabulary.go path of file: ./repos/arvados/sdk/go/arvados the code of the file until where you have to start completion: // Copyright (C) The Arvados Authors. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 package arvados import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strconv" "strings" ) type Vocabulary struct { reservedTagKeys m
func (v *Vocabulary) getLabelsToValues(key string) (labels map[string]string) { if v == nil { return } labels = make(map[string]string) if _, ok := v.Tags[key]; ok { for val := range v.Tags[key].Values { labels[strings.ToLower(val)] = val for _, tagLbl := range v.Tags[key].Values[val].Labels { label := strings.ToLower(tagLbl.Label) labels[label] = val } } } return labels }
52,107
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 20220526203356_copy_user_uploads_to_upload_references.rb path of file: ./repos/discourse/db/migrate the code of the file until where you have to start completion: # frozen_string_literal: true class CopyUserUploadsToUploadReferences < ActiveRecord::Migration[6.1] def up execute
def up execute <<~SQL INSERT INTO upload_references(upload_id, target_type, target_id, created_at, updated_at) SELECT users.uploaded_avatar_id, 'User', users.id, uploads.created_at, uploads.updated_at FROM users JOIN uploads ON uploads.id = users.uploaded_avatar_id WHERE users.uploaded_avatar_id IS NOT NULL ON CONFLICT DO NOTHING SQL end
615,560
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: record.go path of file: ./repos/kubernetes/staging/src/k8s.io/kubectl/pkg/cmd/edit/testdata the code of the file until where you have to start completion: /* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" yaml "gopkg.in/yaml.v2" ) type EditTestCase struct { Description string `yaml:"description"` // create or edit Mode string `yaml:"mode"` Args []string `yaml:"args"` Filename string `yaml:"filename"` Output string `yaml:"outputFormat"` Namespace string `yaml:"namespace"` ExpectedStdout []string `yaml:"expectedStdout"` ExpectedStderr []string `yaml:"expectedStderr"` ExpectedExitCode int `yaml:"expectedExitCode"` Steps []EditStep `yaml:"steps"` } type EditStep struct { // edit or request StepType string `yaml:"type"` // only applies to request RequestMethod string `yaml:"expectedMethod,omitempty"` RequestPath string `yaml:"expectedPath,omitempty"` RequestContentType string `yaml:"expectedContentType,omitempty"` Input string `yaml:"expectedInput"` // only applies to request ResponseStatusCode int `yaml:"resultingStatusCode,omitempty"`
func main() { tc := &EditTestCase{ Description: "add a testcase description", Mode: "edit", Args: []string{"set", "args"}, ExpectedStdout: []string{"expected stdout substring"}, ExpectedStderr: []string{"expected stderr substring"}, } var currentStep *EditStep fmt.Println(http.ListenAndServe(":8081", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // Record non-discovery things record := false switch segments := strings.Split(strings.Trim(req.URL.Path, "/"), "/"); segments[0] { case "api": // api, version record = len(segments) > 2 case "apis": // apis, group, version record = len(segments) > 3 case "callback": record = true } body, err := io.ReadAll(req.Body) checkErr(err) switch m, p := req.Method, req.URL.Path; { case m == "POST" && p == "/callback/in": if currentStep != nil { panic("cannot post input with step already in progress") } filename := fmt.Sprintf("%d.original", len(tc.Steps)) checkErr(os.WriteFile(filename, body, os.FileMode(0755))) currentStep = &EditStep{StepType: "edit", Input: filename} case m == "POST" && p == "/callback/out": if currentStep == nil || currentStep.StepType != "edit" { panic("cannot post output without posting input first") } filename := fmt.Sprintf("%d.edited", len(tc.Steps)) checkErr(os.WriteFile(filename, body, os.FileMode(0755))) currentStep.Output = filename tc.Steps = append(tc.Steps, *currentStep) currentStep = nil default: if currentStep != nil { panic("cannot make request with step already in progress") } urlCopy := *req.URL urlCopy.Host = "localhost:8080" urlCopy.Scheme = "http" proxiedReq, err := http.NewRequest(req.Method, urlCopy.String(), bytes.NewReader(body)) checkErr(err) proxiedReq.Header = req.Header resp, err := http.DefaultClient.Do(proxiedReq) checkErr(err) defer resp.Body.Close() bodyOut, err := io.ReadAll(resp.Body) checkErr(err) for k, vs := range resp.Header { for _, v := range vs { w.Header().Add(k, v) } } w.WriteHeader(resp.StatusCode) w.Write(bodyOut) if record { infile := fmt.Sprintf("%d.request", len(tc.Steps)) outfile := fmt.Sprintf("%d.response", len(tc.Steps)) checkErr(os.WriteFile(infile, tryIndent(body), os.FileMode(0755))) checkErr(os.WriteFile(outfile, tryIndent(bodyOut), os.FileMode(0755))) tc.Steps = append(tc.Steps, EditStep{ StepType: "request", Input: infile, Output: outfile, RequestContentType: req.Header.Get("Content-Type"), RequestMethod: req.Method, RequestPath: req.URL.Path, ResponseStatusCode: resp.StatusCode, }) } } tcData, err := yaml.Marshal(tc) checkErr(err) checkErr(os.WriteFile("test.yaml", tcData, os.FileMode(0755))) }))) }
358,237
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_context.rs path of file: ./repos/arrow-datafusion/datafusion/sqllogictest/src the code of the file until where you have to start completion: // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF lice
pub async fn try_new_for_test_file(relative_path: &Path) -> Option<Self> { let config = SessionConfig::new() // hardcode target partitions so plans are deterministic .with_target_partitions(4); let mut test_ctx = TestContext::new(SessionContext::new_with_config(config)); let file_name = relative_path.file_name().unwrap().to_str().unwrap(); match file_name { "information_schema_table_types.slt" => { info!("Registering local temporary table"); register_temp_table(test_ctx.session_ctx()).await; } "information_schema_columns.slt" => { info!("Registering table with many types"); register_table_with_many_types(test_ctx.session_ctx()).await; } "map.slt" => { info!("Registering table with map"); register_table_with_map(test_ctx.session_ctx()).await; } "avro.slt" => { #[cfg(feature = "avro")] { info!("Registering avro tables"); register_avro_tables(&mut test_ctx).await; } #[cfg(not(feature = "avro"))] { info!("Skipping {file_name} because avro feature is not enabled"); return None; } } "joins.slt" => { info!("Registering partition table tables"); let example_udf = create_example_udf(); test_ctx.ctx.register_udf(example_udf); register_partition_table(&mut test_ctx).await; } "metadata.slt" => { info!("Registering metadata table tables"); register_metadata_tables(test_ctx.session_ctx()).await; } _ => { info!("Using default SessionContext"); } }; Some(test_ctx) }
421,614
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: types_test.rs path of file: ./repos/rules_rust/proto/prost/private/tests/types the code of the file until where you have to start completion: use types_proto::Enum; use types_proto::{types, Types}; #[test] fn test_types() { Types { a_enum: Enum::C.into(), a_double: 2.0, a_float: 3.0, a_int32: 4, a_int64: 5, a_uint32: 6, a_uint64: 7, a_sint32: 8, a_sint64: 9, a_fixed32: 10, a_fixed64: 11, a_sfixed32: 12, a_sfixed64: 13, a_bool: true, a_string: "a".to_string(), a_bytes: vec![1, 2, 3], repeated_enum: vec![Enum::A.into(), Enum::B.into()], repeated_double: vec![2.0, 3.0], repeated_float: vec![3.0, 4.0], repeated_int32: vec![4, 5], repeated_int64: vec![5, 6], repeated_uint32: vec![6, 7], repeated_uint64: vec![7, 8], repeated_sint32: vec![8, 9], repeated_sint64: vec![9, 10], repeated_fixed32: vec![10, 11], repeated_fixed64: vec![11, 12], repeated_sfixed32: vec![12, 13], repeated_sfixed64: vec![13, 14], repeated_bool: vec![true, false], repeated_string: vec!["a".to_string(), "b".to_string()], repeated_bytes: vec![vec![1, 2, 3], vec![4, 5, 6]], map_string_enum: vec![ ("a".to_string(), Enum::A.into()), ("b".to_string(), Enum::B.into()), ] .into_iter() .collect(), map_string_double: vec![("a".to_string(), 2.0), ("b".to_string(), 3.0)] .into_iter() .collect(), map_string_float: vec![("a".to_string(), 3.0), ("b".to_string(), 4.0)] .into_iter() .collect(), map_string_int32: vec![("a".to_string(), 4), ("b".to_string(), 5)] .into_iter() .collect(), map_string_int64: vec![("a".to_string(), 5), ("b".to_string(), 6)] .into_iter() .collect(), map_string_uint32: vec![("a".to_string(), 6), ("b".to_string(), 7)] .into_iter() .collect(), map_string_uint64: vec![("a".to_string(), 7), ("b".to_string(), 8)] .into_iter() .collect(), map_string_sint32: vec![("a".to_string(), 8), ("b".to_string(), 9)] .into_iter() .collect(), map_string_sint64: vec![("a".to_string(), 9), ("b".to_string(), 10)] .into_iter() .collect(), map_string_fixed32: vec![("a".to_string(), 10), ("b".to_string(), 11)] .into_iter() .collect(), map_string_fixed64: vec![("a".to_string(), 11), ("b".to_string(), 12)] .into_iter() .collect(), map_string_sfixed32: vec![("a".to_string(), 12), ("b".to_string(), 13)] .into_iter() .collect(), map_string_sfixed64: vec![("a".to_string(), 13), ("b".to_string(), 14)] .into_iter() .collect(), map_string_bool: vec![("a".to_string(), true), ("b".to_st
fn test_types() { Types { a_enum: Enum::C.into(), a_double: 2.0, a_float: 3.0, a_int32: 4, a_int64: 5, a_uint32: 6, a_uint64: 7, a_sint32: 8, a_sint64: 9, a_fixed32: 10, a_fixed64: 11, a_sfixed32: 12, a_sfixed64: 13, a_bool: true, a_string: "a".to_string(), a_bytes: vec![1, 2, 3], repeated_enum: vec![Enum::A.into(), Enum::B.into()], repeated_double: vec![2.0, 3.0], repeated_float: vec![3.0, 4.0], repeated_int32: vec![4, 5], repeated_int64: vec![5, 6], repeated_uint32: vec![6, 7], repeated_uint64: vec![7, 8], repeated_sint32: vec![8, 9], repeated_sint64: vec![9, 10], repeated_fixed32: vec![10, 11], repeated_fixed64: vec![11, 12], repeated_sfixed32: vec![12, 13], repeated_sfixed64: vec![13, 14], repeated_bool: vec![true, false], repeated_string: vec!["a".to_string(), "b".to_string()], repeated_bytes: vec![vec![1, 2, 3], vec![4, 5, 6]], map_string_enum: vec![ ("a".to_string(), Enum::A.into()), ("b".to_string(), Enum::B.into()), ] .into_iter() .collect(), map_string_double: vec![("a".to_string(), 2.0), ("b".to_string(), 3.0)] .into_iter() .collect(), map_string_float: vec![("a".to_string(), 3.0), ("b".to_string(), 4.0)] .into_iter() .collect(), map_string_int32: vec![("a".to_string(), 4), ("b".to_string(), 5)] .into_iter() .collect(), map_string_int64: vec![("a".to_string(), 5), ("b".to_string(), 6)] .into_iter() .collect(), map_string_uint32: vec![("a".to_string(), 6), ("b".to_string(), 7)] .into_iter() .collect(), map_string_uint64: vec![("a".to_string(), 7), ("b".to_string(), 8)] .into_iter() .collect(), map_string_sint32: vec![("a".to_string(), 8), ("b".to_string(), 9)] .into_iter() .collect(), map_string_sint64: vec![("a".to_string(), 9), ("b".to_string(), 10)] .into_iter() .collect(), map_string_fixed32: vec![("a".to_string(), 10), ("b".to_string(), 11)] .into_iter() .collect(), map_string_fixed64: vec![("a".to_string(), 11), ("b".to_string(), 12)] .into_iter() .collect(), map_string_sfixed32: vec![("a".to_string(), 12), ("b".to_string(), 13)] .into_iter() .collect(), map_string_sfixed64: vec![("a".to_string(), 13), ("b".to_string(), 14)] .into_iter() .collect(), map_string_bool: vec![("a".to_string(), true), ("b".to_string(), false)] .into_iter() .collect(), map_string_string: vec![ ("a".to_string(), "a".to_string()), ("b".to_string(), "b".to_string()), ] .into_iter() .collect(), map_string_bytes: vec![ ("a".to_string(), vec![1, 2, 3]), ("b".to_string(), vec![4, 5, 6]), ] .into_iter() .collect(), one_of: Some(types::OneOf::OneofFloat(1.0)), }; }
22,866
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: votes_controller.rb path of file: ./repos/consuldemocracy/app/controllers/budgets/investments the code of the file until where you have to start completion: module Budgets module Investments class VotesController <
def destroy @investment.unliked_by(current_user) respond_to do |format| format.js { render :show } end end
111,028
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: login_test.go path of file: ./repos/docker-ce/components/engine/integration/system the code of the file until where you have to start completion: package system // import "github.com/docker/docker/integration/system" import ( "context" "testing" "github.com/docker/docker/api/types" "github.com/docker/docker/integration/internal/requirement" "gotest.tools/v3/assert" is "go
func TestLoginFailsWithBadCredentials(t *testing.T) { skip.If(t, !requirement.HasHubConnectivity(t)) defer setupTest(t)() client := testEnv.APIClient() config := types.AuthConfig{ Username: "no-user", Password: "no-password", } _, err := client.RegistryLogin(context.Background(), config) assert.Assert(t, err != nil) assert.Check(t, is.ErrorContains(err, "unauthorized: incorrect username or password")) assert.Check(t, is.ErrorContains(err, "https://registry-1.docker.io/v2/")) }
563,673
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: CBIG_KRR_example_check_result.m path of file: ./repos/CBIG/utilities/matlab/predictive_models/KernelRidgeRegression/example/script the code of the file until where you have to start completion: function CBIG_KRR_example_check_result(user_output_path)
function CBIG_KRR_example_check_result(user_output_path) % CBIG_KRR_example_check_result(user_output_path) % This fucntion compares the user-generated results with the reference % results for each split (3 splits in total). % If the optimal accuracies differ too much from the allowable threshold, % an error message will be generated. % Input: % - user_output_path: % the absolute path of the output directory containing user-generated % results % Written by Shaoshi Zhang and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md for split = 1:3 split = num2str(split); % load reference result ref_output_path = fullfile(getenv('CBIG_CODE_DIR'), 'utilities', 'matlab', 'predictive_models', ... 'KernelRidgeRegression', 'example', 'reference_output', split, ['final_result_CO_' split '.mat']); ref = load(ref_output_path); % load user-generated result user_output_final_result = fullfile(user_output_path, split, ['final_result_CO_' split '.mat']); load(user_output_final_result); % compare optimal accuracies diff = sum(abs(ref.optimal_acc - optimal_acc)); if diff >= 1e-15 fprintf('The optimal accuracies for split %s differs too much from the reference output.\n', split); else fprintf('The optimal accuracies for split %s agree with the reference output.\n', split) end
618,413
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: syscall_freebsd_riscv64.go path of file: ./repos/podman/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // lic
func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var writtenOut uint64 = 0 _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) written = int(writtenOut) if e1 != 0 { err = e1 } return }
106,991
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: iterator_inst.go path of file: ./repos/bk-cmdb/src/framework/core/output/module/inst the code of the file until where you have to start completion: /* * Tencent is pleased to support the open source community by making 蓝鲸 available. * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All
func NewIteratorInst(target model.Model, cond common.Condition) (Iterator, error) { iter := &iteratorInst{ targetModel: target, cond: cond, buffer: make([]types.MapStr, 0), } iter.cond.SetLimit(DefaultLimit) iter.cond.SetStart(iter.bufIdx) iter.cond.Field(model.ObjectID).Eq(target.GetID()) existItems, err := client.GetClient().CCV3(client.Params{SupplierAccount: target.GetSupplierAccount()}).CommonInst().SearchInst(cond) if nil != err { return nil, err } iter.buffer = append(iter.buffer, existItems...) return iter, nil }
371,341
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tc_cell.rb path of file: ./repos/caxlsx/test/workbook/worksheet the code of the file until where you have to start completion: # frozen_string_literal: true require 'tc_helper' class T
def test_time @c.type = :time now = DateTime.now @c.value = now assert_equal(@c.value, now.to_time) end
464,572
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: any.go path of file: ./repos/go-gin-example/vendor/github.com/json-iterator/go the code of the file until where you have to start completion: package jsoniter import ( "errors" "fmt" "github.com/modern-go/reflect2" "io" "reflect" "strconv" "unsafe" ) // Any generic object representation. // The lazy json implementation holds []byte and parse lazily. type Any interface { LastError() error ValueType() ValueType MustBeValid() Any ToBool() bool ToInt() int ToInt32() int32 ToInt64() int64 ToUint() uint ToUint32() uint32 ToUint64() uint64 ToFloat32() float32 ToFloat64() float64 ToString() string ToVal(val interface{}) Get(path ...interface{}) Any Size() int Keys() []
func Wrap(val interface{}) Any { if val == nil { return &nilAny{} } asAny, isAny := val.(Any) if isAny { return asAny } typ := reflect2.TypeOf(val) switch typ.Kind() { case reflect.Slice: return wrapArray(val) case reflect.Struct: return wrapStruct(val) case reflect.Map: return wrapMap(val) case reflect.String: return WrapString(val.(string)) case reflect.Int: if strconv.IntSize == 32 { return WrapInt32(int32(val.(int))) } return WrapInt64(int64(val.(int))) case reflect.Int8: return WrapInt32(int32(val.(int8))) case reflect.Int16: return WrapInt32(int32(val.(int16))) case reflect.Int32: return WrapInt32(val.(int32)) case reflect.Int64: return WrapInt64(val.(int64)) case reflect.Uint: if strconv.IntSize == 32 { return WrapUint32(uint32(val.(uint))) } return WrapUint64(uint64(val.(uint))) case reflect.Uintptr: if ptrSize == 32 { return WrapUint32(uint32(val.(uintptr))) } return WrapUint64(uint64(val.(uintptr))) case reflect.Uint8: return WrapUint32(uint32(val.(uint8))) case reflect.Uint16: return WrapUint32(uint32(val.(uint16))) case reflect.Uint32: return WrapUint32(uint32(val.(uint32))) case reflect.Uint64: return WrapUint64(val.(uint64)) case reflect.Float32: return WrapFloat64(float64(val.(float32))) case reflect.Float64: return WrapFloat64(val.(float64)) case reflect.Bool: if val.(bool) == true { return &trueAny{} } return &falseAny{} } return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)} }
698,202
You are an expert in writing code in many different languages. Your goal is 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/wafregional/src/operation/update_rate_based_rule the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
817,986
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: copyfig.m path of file: ./repos/DeepCO3/Lib/export_fig-master the code of the file until where you have to start completion: function fh = copyfig(fh) %COPYFIG Create a copy of a figure, without changing the figure % % Examples:
function fh = copyfig(fh) %COPYFIG Create a copy of a figure, without changing the figure % % Examples: % fh_new = copyfig(fh_old) % % This function will create a copy of a figure, but not change the figure, % as copyobj sometimes does, e.g. by changing legend
384,015
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 20151028213830_add_unaccent_extension.rb path of file: ./repos/consuldemocracy/db/migrate the code of the file until where you have to start completion: class AddUnaccentExtension < ActiveRecord::Migration[4.2] def chang
def change return if extension_enabled?("unaccent") begin enable_extension "unaccent" rescue StandardError => e raise "Could not create extension unaccent. Please contact with your system administrator: #{e}" end
110,701
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: feed.rb path of file: ./repos/forem/app/services/podcasts the code of the file until where you have to start completion: require "rss" require "rss/itunes" module Podcasts class Feed def initialize(podcast) @podcast = podcast end # @note While the limit might look generous, the callers are passing the value (which they # themselves receive elsewhere). In one case, the :limit is 5 # # @see Podcasts::EnqueueGetEpisodesWorker def get_episodes(limit: 1
def set_unreachable(status: :unreachable, force_update: false) # don't recheck if the podcast was already unreachable or force update is required need_refetching = podcast.reachable || force_update podcast.update_columns(reachable: false, status_notice: I18n.t(status, scope: "views.podcasts.statuses")) refetch_items if need_refetching true end # When setting podcast feed as unreachable, we need to re-check the episodes URLs. # If the episodes URLs are still reachable, the podcast will remain on the site. # If they are not, the podcast will be hidden. def refetch_items job_params = podcast.podcast_episodes.pluck(:id, :media_url) PodcastEpisodes::UpdateMediaUrlWorker.perform_bulk(job_params) end end
627,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: Solution_test.go path of file: ./repos/awesome-golang-algorithm/leetcode/2701-2800/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero the code of the file until where you have to start completion: package Solution import ( "reflect" "strconv" "testing" ) func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string inputs bool expect bool }{ {"TestCase", true, true}, {"TestCase", true, true}, {"TestCase", false, false}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { got :
func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string inputs bool expect bool }{ {"TestCase", true, true}, {"TestCase", true, true}, {"TestCase", false, false}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { got := Solution(c.inputs) if !reflect.DeepEqual(got, c.expect) { t.Fatalf("expected: %v, but got: %v, with inputs: %v", c.expect, got, c.inputs) } }) } }
185,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: source.rb path of file: ./repos/yacs/malg the code of the file until where you have to start completion: require 'o
def run @connection = Faraday.new(url: "#{@location}/#{@term_shortname}") loop do update sleep @polling_frequency end end
71,083
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: semver.go path of file: ./repos/sealer/vendor/golang.org/x/mod/semver the code of the file until where you have to start completion: // Copyright 2018 The Go Authors. All rights reserved. // Us
func Build(v string) string { pv, ok := parse(v) if !ok { return "" } return pv.build }
725,090
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: connect.rs path of file: ./repos/Rust-Full-Stack/yew/modal/src/components/buttons the code of the file until where you have to start completion: use yew::{html, Callback, Component, ComponentLink, Html, Renderable, ShouldRender}; pub struct Connect { disabled: bool, onsignal: Option<Callback<()>>, } pub enum Msg { Connect, } #[derive(PartialEq, Clone)] pub struct Props { pub
fn view(&self) -> Html<Self> { html! { <button id="connect", class=("margin-right-one", "white", "cursor-pointer", "hover", "transition", "theme-black"), onclick=|_| Msg::Connect, disabled={self.disabled}, title="Click this to connect to Rust chat app.", > { "Enter" } </button> } }
484,430
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: hello.pb.go path of file: ./repos/qt/internal/examples/grpc/hello_world the code of the file until where you have to start completion: // Code generated by protoc-gen-go. // source: hello.proto // DO NOT EDIT! /* Package helloworld is a generated protocol buffer package. It is generated from these files: hello.proto profile.proto It has these top-level messages: HelloRequest HelloResponse EmptyMessage IDMessage ProfileMessage */ package main import proto "github.com/golang/prot
func _HelloService_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(HelloRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(HelloServiceServer).SayHello(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/helloworld.HelloService/SayHello", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HelloServiceServer).SayHello(ctx, req.(*HelloRequest)) } return interceptor(ctx, in, info, handler) }
687,276
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: uninstall.rs path of file: ./repos/frum/src/commands the code of the file until where you have to start completion: use crate::config::FrumConfig; use crate::input_version::InputVersion; use crate::outln; use crate::symlink::remove_symlink_dir; use crate::version::Version; use anyhow::Result; use colored::Colorize; use log::debug; use std::ffi::OsStr; use std::io::prelude::*; use std::path::Component; use std::path::PathBuf; use thiserror::Error; #[derive(Error, Debug)] pub enum FrumError { #[error(transparent)] HttpError(#[from] reqwest::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error("Can't find the number of cores")] FromUtf8Error(#[from] st
fn apply(&self, config: &FrumConfig) -> Result<(), Self::Error> { let current_version = self.version.clone(); let version = match current_version.clone() { InputVersion::Full(Version::Semver(v)) => Version::Semver(v), InputVersion::Full(Version::System) => { return Err(FrumError::NotInstallableVersion { version: Version::System, }) } _ => unreachable!(), }; let installation_dir = PathBuf::from(&config.versions_dir()).join(version.to_string()); if !installation_dir.exists() { return Err(FrumError::VersionNotFound { version: current_version, }); } outln!(config#Info, "{} Uninstalling {}", "==>".green(), format!("Ruby {}", current_version).green()); if symlink_exists( config .frum_path .clone() .ok_or(FrumError::FrumPathNotFound)?, &version, )? { debug!("remove frum path symlink"); remove_symlink_dir( &config .frum_path .clone() .ok_or(FrumError::FrumPathNotFound)?, )?; } if symlink_exists(config.default_version_dir(), &version)? { debug!("remove default alias symlink"); remove_symlink_dir(&config.default_version_dir())?; } debug!("remove dir"); std::fs::remove_dir_all(&installation_dir)?; Ok(()) }
236,845
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ratelimit_test.go path of file: ./repos/discordgo the code of the file until where you have to start completion: package discordgo import ( "fmt" "net/http" "strconv" "testing" "time" ) // This test takes ~2 seconds to run func TestRatelimitReset(t *testing.T) { rl := NewRatelimiter() sen
func sendBenchReq(endpoint string, rl *RateLimiter) { bucket := rl.LockBucket(endpoint) headers := http.Header(make(map[string][]string)) headers.Set("X-RateLimit-Remaining", "10") headers.Set("X-RateLimit-Reset", fmt.Sprint(float64(time.Now().UnixNano())/1e9)) headers.Set("Date", time.Now().Format(time.RFC850)) bucket.Release(headers) }
126,722
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.go path of file: ./repos/gccrs/libgo/misc/cgo/testplugin/testdata/iface the code of the file until where you have to start completion: // Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license
func main() { a, err := plugin.Open("iface_a.so") if err != nil { log.Fatalf(`plugin.Open("iface_a.so"): %v`, err) } b, err := plugin.Open("iface_b.so") if err != nil { log.Fatalf(`plugin.Open("iface_b.so"): %v`, err) } af, err := a.Lookup("F") if err != nil { log.Fatalf(`a.Lookup("F") failed: %v`, err) } bf, err := b.Lookup("F") if err != nil { log.Fatalf(`b.Lookup("F") failed: %v`, err) } if af.(func() interface{})() != bf.(func() interface{})() { panic("empty interfaces not equal") } ag, err := a.Lookup("G") if err != nil { log.Fatalf(`a.Lookup("G") failed: %v`, err) } bg, err := b.Lookup("G") if err != nil { log.Fatalf(`b.Lookup("G") failed: %v`, err) } if ag.(func() iface_i.I)() != bg.(func() iface_i.I)() { panic("nonempty interfaces not equal") } }
748,606
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ft_connectivityplot.m path of file: ./repos/bspm/thirdparty/spm12/external/fieldtrip the code of the file until where you have to start completion: function [cfg] = ft_connectivityplot(cfg, varargin) % FT_CONNECTIVITYPLOT plots channel-level frequency resolved connectivity. The % data are rendered in a square grid of subplots, each subplot containing the % connectivity spectrum between the two respective channels. % % Use as % ft_connectivityplot(cfg, data) % % The input data is a structure containing the output to FT_CONNECTIVITYANALYSIS % using a frequency domain metric of connectivity. Consequently the input % data should have a dimord of 'chan_chan_freq', or 'chan_chan_freq_time'. %
function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble provenance varargin ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'color', 'graphcolor'}); % to make it consistent with ft_singleplotER % set the defaults cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.parameter = ft_getopt(cfg, 'parameter', 'cohspctrm'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.graphcolor = ft_getopt(cfg, 'graphcolor', 'brgkywrgbkywrgbkywrgbkyw'); if ischar(cfg.graphcolor), cfg.graphcolor = cfg.graphcolor(:); end
517,525
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: feed.rb path of file: ./repos/rgsoc-teams/lib the code of the file until where you have to start completion: # frozen_string_liter
def update_entries parse.entries.each do |data| item = Item.new(source.url, source.team_id, data) raise "can not find guid for item in source #{source.feed_url}" unless item.guid # logger.info "processing item #{item.guid}: #{item.title}" record = Activity.where(guid: item.guid).first attrs = item.attrs.merge(img_url: record.try(:img_url) || Image.new(item.url, logger: logger).store) record ? record.update_attributes!(attrs) : Activity.create!(attrs) end rescue => e ErrorReporting.call(e) logger.error "Could not update entries: #{e.message}" nil end
179,204
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: user.rb path of file: ./repos/SimpleAMS/spec/support/models the code of the file until where you have to start completion: require 'spec_helper' class User class << self def model_attributes @model_attributes ||= instance_methods(false) - relations.map(&:name) end def relation_names @relation_names ||= relations.map(&:name) end def relations [ OpenStruct.new( type: :has_many, name: :microposts, options: { serializer: MicropostSerializer } ),
def relations [ OpenStruct.new( type: :has_many, name: :microposts, options: { serializer: MicropostSerializer } ), OpenStruct.new( type: :has_many, name: :followers, options: { serializer: UserSerializer } ), OpenStruct.new( type: :has_many, name: :followings, options: { serializer: UserSerializer } ), OpenStruct.new( type: :has_one, name: :address, options: { serializer: AddressSerializer } ) ] end
259,281
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: greater_than.go path of file: ./repos/DocHub/vendor/github.com/smartystreets/assertions/internal/oglematchers the code of the file until where you have to start completion: // Copyright 2011 Aaron Jacobs. All Rights Reserved. // Author: aaronjjacobs@gmail.com
func GreaterThan(x interface{}) Matcher { desc := fmt.Sprintf("greater than %v", x) // Special case: make it clear that strings are strings. if reflect.TypeOf(x).Kind() == reflect.String { desc = fmt.Sprintf("greater than \"%s\"", x) } return transformDescription(Not(LessOrEqual(x)), desc) }
320,117
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: module_client_example_test.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/automation/armautomation the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project r
func ExampleModuleClient_Update() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armautomation.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewModuleClient().Update(ctx, "rg", "MyAutomationAccount", "MyModule", armautomation.ModuleUpdateParameters{ Properties: &armautomation.ModuleUpdateProperties{ ContentLink: &armautomation.ContentLink{ ContentHash: &armautomation.ContentHash{ Algorithm: to.Ptr("sha265"), Value: to.Ptr("07E108A962B81DD9C9BAA89BB47C0F6EE52B29E83758B07795E408D258B2B87A"), }, URI: to.Ptr("https://teststorage.blob.core.windows.net/mycontainer/MyModule.zip"), Version: to.Ptr("1.0.0.0"), }, }, }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Module = armautomation.Module{ // Name: to.Ptr("MyModule"), // Type: to.Ptr("Microsoft.Automation/AutomationAccounts/Modules"), // ID: to.Ptr("/subscriptions/subid/resourceGroups/rg/providers/Microsoft.Automation/automationAccounts/MyAutomationAccount/modules/MyModule"), // Location: to.Ptr("East US 2"), // Tags: map[string]*string{ // }, // Properties: &armautomation.ModuleProperties{ // ActivityCount: to.Ptr[int32](0), // CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-03-29T15:41:47.003Z"); return t}()), // Error: &armautomation.ModuleErrorInfo{ // }, // IsComposite: to.Ptr(false), // IsGlobal: to.Ptr(false), // LastModifiedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-03-29T15:42:10.567Z"); return t}()), // ProvisioningState: to.Ptr(armautomation.ModuleProvisioningStateSucceeded), // SizeInBytes: to.Ptr[int64](0), // }, // } }
271,571
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ipset_server.go path of file: ./repos/chaos-mesh/pkg/chaosdaemon the code of the file until where you have to start completion: // Copyright 2021 Chaos Mesh Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not
func flushIPSet(ctx context.Context, log logr.Logger, enterNS bool, pid uint32, set *pb.IPSet) error { name := set.Name // If the IP set already exists, it will be renamed to this temp name. tmpName := fmt.Sprintf("%sold", name) ipSetType := v1alpha1.IPSetType(set.Type) var values []string switch ipSetType { case v1alpha1.SetIPSet: values = set.SetNames case v1alpha1.NetIPSet: values = set.Cidrs case v1alpha1.NetPortIPSet: for _, cidrAndPort := range set.CidrAndPorts { values = append(values, fmt.Sprintf("%s,%d", cidrAndPort.Cidr, cidrAndPort.Port)) } default: return fmt.Errorf("unexpected IP set type: %s", ipSetType) } // IP sets can't be deleted if there are iptables rules referencing them. // Therefore, we create new sets and swap them. if err := createIPSet(ctx, log, enterNS, pid, tmpName, ipSetType); err != nil { return err } // Populate the IP set. for _, value := range values { if err := addToIPSet(ctx, log, enterNS, pid, tmpName, value); err != nil { return err } } // Finally, rename the IP set to target name. err := renameIPSet(ctx, log, enterNS, pid, tmpName, name) return err }
435,106
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: version.go path of file: ./repos/kubernetes/vendor/golang.org/x/tools/internal/gocommand the code of the file until where you have to start completion: // Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gocommand import ( "context" "fmt" "regexp" "strings" ) // GoVersion reports the minor version number of the highest release // tag built into the go command on the PATH. // // Note that this may be higher than the version of the go tool used // to build this application, and thus the versions of the standard // go/{scanner,parser,ast,types} packages that are linked into it. // In that case, callers should either downgrade to the version of // go used to build the application, or report an error that the // application is too old to use the go command on the PATH. func GoVersion(ctx cont
func GoVersion(ctx context.Context, inv Invocation, r *Runner) (int, error) { inv.Verb = "list" inv.Args = []string{"-e", "-f", `{{context.ReleaseTags}}`, `--`, `unsafe`} inv.BuildFlags = nil // This is not a build command. inv.ModFlag = "" inv.ModFile = "" inv.Env = append(inv.Env[:len(inv.Env):len(inv.Env)], "GO111MODULE=off") stdoutBytes, err := r.Run(ctx, inv) if err != nil { return 0, err } stdout := stdoutBytes.String() if len(stdout) < 3 { return 0, fmt.Errorf("bad ReleaseTags output: %q", stdout) } // Split up "[go1.1 go1.15]" and return highest go1.X value. tags := strings.Fields(stdout[1 : len(stdout)-2]) for i := len(tags) - 1; i >= 0; i-- { var version int if _, err := fmt.Sscanf(tags[i], "go1.%d", &version); err != nil { continue } return version, nil } return 0, fmt.Errorf("no parseable ReleaseTags in %v", tags) }
354,893
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: template.rb path of file: ./repos/odf-report/lib/odf-report the code of the file until where you have to start completion: module ODFReport class Template CONTENT_FILES = ['content.xml', 'styles.xml'] MANIFEST_FILE = "META-INF/manifest.xml" attr_accessor :output_stream def initialize(template = nil, io: nil) raise "You mus
def initialize(template = nil, io: nil) raise "You must provide either a filename or an io: string" unless template || io raise "Template [#{template}] not found." unless template.nil? || ::File.exist?(template) @template = template @io = io end
397,117
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: raft_list_members.go path of file: ./repos/ziti/controller/rest_server/operations/raft the code of the file until where you have to start completion: // Code generated by go-swagger; DO NOT EDIT. // // Copyright NetFoundry Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file 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 ap
func (o *RaftListMembers) ServeHTTP(rw http.ResponseWriter, r *http.Request) { route, rCtx, _ := o.Context.RouteInfo(r) if rCtx != nil { *r = *rCtx } var Params = NewRaftListMembersParams() if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params o.Context.Respond(rw, r, route.Produces, route, err) return } res := o.Handler.Handle(Params) // actually handle the request o.Context.Respond(rw, r, route.Produces, route, res) }
642,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: api_op_AddThingToBillingGroup.go path of file: ./repos/aws-sdk-go-v2/service/iot the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package iot 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" ) // Adds a thing to a billing group. Requires permission to access the // AddThingToBillingGroup (https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions) // action. func (c *Client) AddThingToBillingGroup(ctx context.Context, params *AddThingToBillingGroupInput, optFns ...func(*Options)) (*AddThingToBillingGroupOutput, error) { if params == nil { params = &AddThingToBillingGroupInput{} } result, metadata, err := c.invokeOperation(ctx, "AddThingToBillingGroup", params, optFns, c.addOperationAddThingToBillingGroupMiddlewares) if err != nil { return nil, err } out := result.(*AddThingToBillingGroupOutput) out.ResultMetadata = metadata return out, nil } type AddThingToBillingGroupInput struct {
func (c *Client) addOperationAddThingToBillingGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsRestjson1_serializeOpAddThingToBillingGroup{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpAddThingToBillingGroup{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "AddThingToBillingGroup"); err != nil { return fmt.Errorf("add protocol finalizers: %v", err) } if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = addClientRequestID(stack); err != nil { return err } if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addComputePayloadSHA256(stack); err != nil { return err } if err = addRetry(stack, options); err != nil { return err } if err = addRawResponseToMetadata(stack); err != nil { return err } if err = addRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAddThingToBillingGroup(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 }
226,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: _account_not_registered_exception.rs path of file: ./repos/aws-sdk-rust/sdk/cloudtrail/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>This exception is thrown when the specified
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ::std::write!(f, "AccountNotRegisteredException")?; if let ::std::option::Option::Some(inner_1) = &self.message { { ::std::write!(f, ": {}", inner_1)?; } } Ok(()) }
819,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: modify_db_subnet_group.rs path of file: ./repos/aws-sdk-rust/sdk/neptune/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 `ModifyDBSubnetGroup`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct ModifyDBSubnetGroup; impl ModifyDBSubnetGroup { /// Creates a new `ModifyDBSubnetGroup` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_r
fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::DbSubnetGroupDoesNotCoverEnoughAZs(_inner) => ::std::option::Option::Some(_inner), Self::DbSubnetGroupNotFoundFault(_inner) => ::std::option::Option::Some(_inner), Self::DbSubnetQuotaExceededFault(_inner) => ::std::option::Option::Some(_inner), Self::InvalidSubnet(_inner) => ::std::option::Option::Some(_inner), Self::SubnetAlreadyInUse(_inner) => ::std::option::Option::Some(_inner), Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } }
776,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: gen_MemoryAttributionContainer.rs path of file: ./repos/wasm-bindgen/crates/web-sys/src/features the code of the file until where you have to start completion: #![allow(unused_imports)] #![allow(clippy::all)] us
pub fn id(&mut self, val: &str) -> &mut Self { use wasm_bindgen::JsValue; let r = ::js_sys::Reflect::set(self.as_ref(), &JsValue::from("id"), &JsValue::from(val)); debug_assert!( r.is_ok(), "setting properties should never fail on our dictionary objects" ); let _ = r; self }
94,077
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _batch_get_commits_error.rs path of file: ./repos/aws-sdk-rust/sdk/codecommit/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy
pub fn build(self) -> crate::types::BatchGetCommitsError { crate::types::BatchGetCommitsError { commit_id: self.commit_id, error_code: self.error_code, error_message: self.error_message, } }
787,434
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: posix_test.go path of file: ./repos/gccrs/libgo/go/net/http/cgi the code of the file until where you have to start completion: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is g
func isProcessRunning(pid int) bool { p, err := os.FindProcess(pid) if err != nil { return false } return p.Signal(syscall.Signal(0)) == nil }
747,121
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: suffix_any.go path of file: ./repos/fabio/vendor/github.com/gobwas/glob/match the code of the file until where you have to start completion: package match import ( "fmt" "strings" sutil "gi
func (self SuffixAny) Index(s string) (int, []int) { idx := strings.Index(s, self.Suffix) if idx == -1 { return -1, nil } i := sutil.LastIndexAnyRunes(s[:idx], self.Separators) + 1 return i, []int{idx + len(self.Suffix) - i} }
596,412
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: client.go path of file: ./repos/kubeedge/vendor/golang.org/x/net/websocket the code of the file until where you have to start completion: // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be fou
func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) { br := bufio.NewReader(rwc) bw := bufio.NewWriter(rwc) err = hybiClientHandshake(config, br, bw) if err != nil { return } buf := bufio.NewReadWriter(br, bw) ws = newHybiClientConn(config, buf, rwc) return }
420,087
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: shape.rs path of file: ./repos/uiua/src the code of the file until where you have to start completion: use std::{ fmt, hash::Hash, ops::{Deref, DerefMut, RangeBounds}, }; use ser
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[")?; for (i, dim) in self.dims.iter().enumerate() { if i > 0 { write!(f, " × ")?; } write!(f, "{}", dim)?; } write!(f, "]") }
486,721
You are an expert in writing code in many different languages. Your goal is 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/imagebuilder/src/operation/list_workflow_executions the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
771,504
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: base_post.go path of file: ./repos/sonic/service/impl the code of the file until where you have to start completion: package impl import ( "context" "database/sql/driver" "regexp" "strconv" "strings" "time" "gorm.io/gen/field" "github.com/go-sonic/sonic/consts" "github.com/go-sonic/sonic/dal" "github.com/go-sonic/sonic/log" "github.com/go-sonic/sonic/model/entity" "github.com/go-sonic/sonic/model/param" "github.com/go-sonic/sonic/model/property" "github.com/go-sonic/sonic/service" "github.com/go-sonic/sonic/util" "github.com/go-sonic/sonic/util/xerr" ) type basePostServiceImpl struct { OptionService service.OptionService BaseCommentService service.BaseCommentService CounterCache *util.CounterCache[int32] } func NewBasePostService(optionService service.OptionService, baseCommentService service.BaseCommentService) service.BasePostService { counterCache := util.NewCo
func (b basePostServiceImpl) Delete(ctx context.Context, postID int32) error { err := dal.GetQueryByCtx(ctx).Transaction(func(tx *dal.Query) error { postDAL := tx.Post postTagDAL := tx.PostTag postCategoryDAL := tx.PostCategory postMetaDAL := tx.Meta postCommentDAL := tx.Comment deleteResult, err := postDAL.WithContext(ctx).Where(postDAL.ID.Eq(postID)).Delete() if err != nil { return WrapDBErr(err) } if deleteResult.RowsAffected != 1 { return xerr.NoType.New("").WithMsg("delete post failed") } _, err = postTagDAL.WithContext(ctx).Where(postTagDAL.PostID.Eq(postID)).Delete() if err != nil { return WrapDBErr(err) } _, err = postCategoryDAL.WithContext(ctx).Where(postCategoryDAL.PostID.Eq(postID)).Delete() if err != nil { return WrapDBErr(err) } _, err = postMetaDAL.WithContext(ctx).Where(postMetaDAL.PostID.Eq(postID)).Delete() if err != nil { return WrapDBErr(err) } _, err = postCommentDAL.WithContext(ctx).Where(postCommentDAL.PostID.Eq(postID)).Delete() if err != nil { return WrapDBErr(err) } return nil }) return err }
65,883
You are an expert in writing code in many different languages. Your goal is 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/volt/crates/package-spec/src the code of the file until where you have to start completion: use std::fmt; use std::path::PathBuf; use std::str::FromStr; use nom::combinator::all_consuming; use nom::Err; use oro_node_semver::{Version, VersionReq as Range}; pub use crate::error::{PackageSpecError, SpecErrorKind}; pub use crate::gitinfo::{GitHost, GitInfo}; use crate::parsers::package; mod error; mod gitinfo; mod parsers; #[deriv
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use PackageSpec::*; match self { Dir { path } => write!(f, "{}", path.display()), Git(info) => write!(f, "{}", info), Npm { ref scope, ref name, ref requested, } => { if let Some(scope) = scope { write!(f, "@{}/", scope)?; } write!(f, "{}", name)?; if let Some(req) = requested { write!(f, "{}", req)?; } Ok(()) } Alias { ref name, ref spec } => { write!(f, "{}@", name)?; if let Npm { .. } = **spec { write!(f, "npm:")?; } write!(f, "{}", spec) } } }
317,138
You are an expert in writing code in many different languages. Your goal is 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_DeleteVariable.go path of file: ./repos/aws-sdk-go-v2/service/frauddetector the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package frauddetector import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws
func newServiceMetadataMiddleware_opDeleteVariable(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "DeleteVariable", } }
215,939
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: variable.rs path of file: ./repos/probe-rs/probe-rs/src/debug the code of the file until where you have to start completion: use crate::debug::{language::Programming
pub fn is_deferred(&self) -> bool { match self { VariableNodeType::TypeOffset(_, _) | VariableNodeType::DirectLookup(_, _) | VariableNodeType::UnitsLookup => true, VariableNodeType::DoNotRecurse | VariableNodeType::RecurseToBaseType => false, } }
194,578
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sync_label_worker.rb path of file: ./repos/octobox/app/workers the code of the file until where you have to start completion: # frozen_string_literal: true class SyncLabelWorker include Sidekiq::Worker sidekiq_options q
def perform(payload) repository = Repository.find_by_github_id(payload['repository']['id']) return if repository.nil? return if payload['changes']['name'].nil? subjects = repository.subjects.label(payload['changes']['name']['from']) subjects.each do |subject| n = subject.notifications.first n.try(:update_subject, true) end end
39,701
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: discreteHalfPlane.m path of file: ./repos/matImage/matImage/imShapes the code of the file until where you have to start completion: function img = discreteHalfPlane(varargin) %DISCRETEHALFPLANE Discretize a half plane % % A Halfplane is the set of point delimited by a straight line. % Only the points located 'on the left' of the line belong to the % halfplane. % % IMG = discreteHalfPlane(DIM, LINE) % DIM is the size of image, with the format [x0 dx x1;y0 dy y1] % LINE is a 1x4 array of the form [x0 y0 dx dy], x0 and y0 being % coordinate of a point belonging to the boundary line, and dx and dy % being direction vectors of the boundary line of the halfplane. % % IMG = discreteHalfPlane(DIM, POINT, DIRECTION) % POINT is a point belonging to the boundary line % DIRECTION is a 2x1 vector containing direction vector of the boundary % line. % % IMG = discreteHalfPlane(LX, LY, ...); % Specifes the pixels coordinates with the two row vectors LX and LY. % % Example % img = discreteHalfPlane([1 1 100;1 1 100], [50 50], 30, 10); % % See Also % imShapes, discreteDisc, discreteSquare % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2006-10-12
function img = discreteHalfPlane(varargin) %DISCRETEHALFPLANE Discretize a half plane % % A Halfplane is the set of point delimited by a straight line. % Only the points located 'on the left' of the line belong to the % halfplane. % % IMG = discreteHalfPlane(DIM, LINE) % DIM is the size of image, with the format [x0 dx x1;y0 dy y1] % LINE is a 1x4 array of the form [x0 y0 dx dy], x0 and y0 being % coordinate of a point belonging to the boundary line, and dx and dy % being direction vectors of the boundary line of the halfplane. % % IMG = discreteHalfPlane(DIM, POINT, DIRECTION) % POINT is a point belonging to the boundary line % DIRECTION is a 2x1 vector containing direction vector of the boundary % line. % % IMG = discreteHalfPlane(LX, LY, ...); % Specifes the pixels coordinates with the two row vectors LX and LY. % % Example % img = discreteHalfPlane([1 1 100;1 1 100], [50 50], 30, 10); % % See Also % imShapes, discreteDisc, discreteSquare % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2006-10-12 % Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). % HISTORY % 04/01/2007: concatenate transforms before applying them % 04/03/2009: use meshgrid % 29/04/2009: update transforms % 29/05/2009: use more possibilities for specifying grid % 22/01/2010: fix auto center with odd image size % compute coordinate of image voxels [lx, ly, varargin] = parseGridArgs(varargin{:}); [x, y] = meshgrid(lx, ly); % default parameters center = [lx(ceil(end
443,127
You are an expert in writing code in many different languages. Your goal is 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_test.go path of file: ./repos/sliver/implant/sliver/proxy the code of the file until where you have to start completion: // Copyright 2018, Rapid7, Inc. // License: BSD-
func TestProvider_IsProxyBypass(t *testing.T) { for _, tt := range dataProviderIsProxyBypass { var tName string if tt.targetUrl == nil { tName = "nil" } else { tName = tt.targetUrl.String() } tName = tName + " " + tt.proxyBypass t.Run(tName, func(t *testing.T) { a := assert.New(t) p := newTestProvider("") a.Equal(tt.expect, p.isProxyBypass(tt.targetUrl, tt.proxyBypass, ",")) }) } }
450,979
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: middleware.go path of file: ./repos/goa/grpc/middleware/xray the code of the file until where you have to start completion: package xray import ( "context" "fmt" "io" "net" "sync" "time" grpcm "goa.design/goa/v3/grpc/middle
func (c *xrayStreamClientWrapper) RecvMsg(m any) error { if err := c.ClientStream.RecvMsg(m); err != nil { c.recordErrorAndClose(err) return err } return nil }
119,465
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: cmd_update.go path of file: ./repos/jupiter/pkg/core/cmd the code of the file until where you have to start completion: // Copyright 2022 Douyu // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License.
func Update(c *cli.Context) error { remote := c.String("remote") update := fmt.Sprintf("go install %s@latest\n", remote) if runtime.Version() < "go1.18" { fmt.Println("当前安装的golang版本小于1.18,请升级!") return nil } cmds := []string{update} for _, cmd := range cmds { fmt.Println(cmd) cmd := exec.Command("bash", "-c", cmd) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout err := cmd.Run() if err != nil { return err } } return nil }
598,088
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: FWT2_PO.m path of file: ./repos/CS_MoCo_LAB/reconstruction/matlab/CS_LAB_matlab/utils/utils_Wavelet the code of the file until where you have to start completion: function wc = FWT2_PO(x,L,qmf) % FWT2_PO -- 2-d MRA wavelet transform (periodized, orthogonal) % Usage % wc = FWT2_PO(x,L,qmf) % Inputs % x 2-d image (n by n array, n dyadic) % L coarse level % qmf quadrature mirror filter % Outputs % wc 2-d wavelet transform % % Description % A two-dimensional Wavelet Transform is computed for the % array x. To reconstruct, use IWT2_PO. % % See Also
function wc = FWT2_PO(x,L,qmf) % FWT2_PO -- 2-d MRA wavelet transform (periodized, orthogonal) % Usage % wc = FWT2_PO(x,L,qmf) % Inputs % x 2-d image (n by n array, n dyadic) % L coarse level % qmf quadrature mirror filter % Outputs % wc 2-d wavelet transform % % Description % A two-dimensional Wavelet Transform is computed for the % array x. To reconstruct, use IWT2_PO. % % See Also % IWT2_PO, MakeONFilter % [n,J] = quadlength(x); wc = x; nc = n; for jscal=J-1:-1:L, % from fine (J) to coarse (L) top = (nc/2+1):nc; bot = 1:(nc/2); for ix=1:nc, row = wc(ix,1:nc); wc(ix,bot) = DownDyadLo(row,qmf); wc(ix,top) = DownDyadHi(row,qmf); end
61,621
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: GetShapeOrtho.m path of file: ./repos/OpenFace/model_training/pdm_generation/PDM_helpers the code of the file until where you have to start completion: function [shape2D] = GetShapeOrtho(M, V, p, global_params) % M - mean shape vector % V - eigenvectors % p - parameters of non-rigid shape % V_exp % p_exp % global_params includes scale, euler rotation, translation,
function [shape2D] = GetShapeOrtho(M, V, p, global_params) % M - mean shape vector % V - eigenvectors % p - parameters of non-rigid shape % V_exp % p_exp % global_params includes scale, euler rotation, translation, % R - rotation matrix % T - translation vector (tx, ty) R = Euler2Rot(global_params(2:4)); T = [global_params(5:6); 0]; a = global_params(1); shape3D = GetShape3D(M, V, p); shape2D = bsxfun(@plus, a * R*shape3D', T); shape2D = shape2D'; end
338,121
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tx2.rs path of file: ./repos/holochain/crates/kitsune_p2p/proxy/src the code of the file until where you have to start completion: #![allow(clippy::new_ret_no_self)] #![allow(clippy::blocks_in_if_conditions)] //! Next-gen performance kitsune transport proxy use crate::*; use futures::future::BoxFuture; use futures::stream::{Stream, StreamExt}; use ghost_actor::dependencies::tracing; use kitsune_p2p_types::config::KitsuneP2pTuningParams; use kitsune_p2p_types::dependencies::serde_json; use kitsune_p2p_types::tx2::tx2_adapt
pub fn new(sub_fact: EpFactory, config: ProxyConfig) -> KitsuneResult<EpFactory> { let (tuning_params, allow_proxy_fwd, client_of_remote_proxy, proxy_from_bootstrap_cb) = config.split()?; let fact: EpFactory = Arc::new(ProxyEpFactory { tuning_params, allow_proxy_fwd, client_of_remote_proxy, proxy_from_bootstrap_cb, sub_fact, }); Ok(fact) }
167,151
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: buffer.go path of file: ./repos/corteza/server/vendor/github.com/golang/protobuf/proto the code of the file until where you have to start completion: // Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a
func (b *Buffer) DecodeVarint() (uint64, error) { v, n := protowire.ConsumeVarint(b.buf[b.idx:]) if n < 0 { return 0, protowire.ParseError(n) } b.idx += n return uint64(v), nil }
542,371
You are an expert in writing code in many different languages. Your goal is 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_DeleteResolver.go path of file: ./repos/aws-sdk-go-v2/service/appsync the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package appsync 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" ) // Deletes a Resolver object. func (c *Client) DeleteResolver(ctx context.Context, params *DeleteResolverInput, optFns ...func(*Options)) (*DeleteResolverOutput, error) { if params == nil { params = &DeleteResolverInput{} } result, metadata, err := c.invokeOperation(ctx, "DeleteResolver", params, optFns, c.addOperationDeleteResolverMiddlewares) if err != nil { return nil, err } out := result.(*DeleteResolverOutput) out.ResultMetadata = metadata return out, nil } type DeleteResolverInput struct { // The API ID. // // This member is required. ApiId *string // The resolver field name. // // This member is required. FieldName *string // The name of the resolver type. // // This member is required. TypeName *string noSmithyDocumentSerde } type DeleteResolverOutput struct { // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata noSmithyDocumentSerde } func (c *Client) addOperationDeleteResolverMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsRestjson1_serializeOpDeleteResolver{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpDeleteResolver{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteResolver"); err != nil { return fmt.Errorf("add protocol finalizers: %v", err) } if err = addlegacyEndpointContextSetter(stack, options); err !
func (c *Client) addOperationDeleteResolverMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsRestjson1_serializeOpDeleteResolver{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpDeleteResolver{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteResolver"); 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 = addOpDeleteResolverValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteResolver(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 }
230,238
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: diagnostic.rs path of file: ./repos/aws-sdk-rust/sdk/emrserverless/src/endpoint_lib 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. /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-Lic
pub(crate) fn capture<T, E: Into<Box<dyn Error + Send + Sync>>>(&mut self, err: Result<T, E>) -> Option<T> { match err { Ok(res) => Some(res), Err(e) => { self.report_error(e); None } } }
796,379
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _resource_already_exists_exception.rs path of file: ./repos/aws-sdk-rust/sdk/cloudwatchevents/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 resource you are trying to create already exists.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cm
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ::std::write!(f, "ResourceAlreadyExistsException")?; if let ::std::option::Option::Some(inner_1) = &self.message { { ::std::write!(f, ": {}", inner_1)?; } } Ok(()) }
756,407
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 20230608151123_add_validity_period_to_journals.rb path of file: ./repos/openproject/db/migrate the code of the file until where you have to start completion: class AddValidityPeriodToJournals < ActiveRecord::Migration[7.0] def change add_column :journals, :validity_period, :tstzrange reversible do |direction| direction.up do fix_all_journal_timestamps
def change add_column :journals, :validity_period, :tstzrange reversible do |direction| direction.up do fix_all_journal_timestamps write_validity_period add_validity_period_constraint end end add_check_constraint :journals, 'NOT isempty(validity_period) AND validity_period IS NOT NULL', name: "journals_validity_period_not_empty" end
666,349
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ar_region.rb path of file: ./repos/manageiq/lib/extensions the code of the file until where you have to start completion: module ArRegion extend ActiveSupport::Concern included do cache_with_timeout(:i
def inherited(other) if other == other.base_class other.class_eval do virtual_column :region_number, :type => :integer # This method is defined in ActiveRecord::IdRegions virtual_column :region_description, :type => :string end end
22,151
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: dirwalk_linux.go path of file: ./repos/sliver/vendor/tailscale.com/util/dirwalk the code of the file until where you have to start completion: // Copyright (c) Tailscale Inc & AUTHORS // SPDX-License-
func readDirent(fd int, buf []byte) (n int, err error) { for { nbuf, err := syscall.ReadDirent(fd, buf) if err != syscall.EINTR { return nbuf, err } } }
454,687
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tetris.m path of file: ./repos/jigsaw-matlab the code of the file until where you have to start completion: function [mesh] = tetris(opts,nlev) %TETRIS generate a mesh using a "multi-level" strategy. % MESH = TETRIS(OPTS,NLEV) generates MESH using a sequence % of bisection/refinement/optimisation operations. At each
function [mesh] = tetris(opts,nlev) %TETRIS generate a mesh using a "multi-level" strategy. % MESH = TETRIS(OPTS,NLEV) generates MESH using a sequence % of bisection/refinement/optimisation operations. At each % pass, the mesh from the preceeding level is bisected % uniformly, a "halo" of nodes associated with "irregular" % topology is removed and JIGSAW is called to perform % subsequent refinement/optimisation. % OPTS is the standard user-defined options struct. passed % to JIGSAW. % % See also JIGSAW %----------------------------------------------------------- % Darren Engwirda % github.com/dengwirda/jigsaw-matlab % 16-Apr-2021 % d.engwirda@gmail.com %----------------------------------------------------------- % if ( isempty(opts)) error('JIGSAW: insufficient inputs.'); end
503,298
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: frameintegrity_test.go path of file: ./repos/livekit/pkg/sfu/buffer the code of the file until where you have to start completion: // Copyright 2024 LiveKit, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // 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 buffer import ( "math/rand" "testing" "github.com/stretchr/testify/require" "github.com/livekit/livekit-server/pkg/sfu/dependencydescriptor" ) func TestFrameIntegrityChecker(t *testing.T) { fc := NewFrameIntegrityChecker(100, 1000) // first frame out of order fc.AddPacket(10, 10, &dependencydescriptor.DependencyDescriptor{}) require.False(t, fc.FrameIntegrity(10)) fc.AddPacket(9, 10, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true}) require.False(t, fc.FrameIntegrity(10)) fc.AddPacket(11, 10, &dependencydescriptor.DependencyDescriptor{LastPacketInFrame: true}) require.True(t, fc.FrameIntegrity(10)) // single packet frame fc.AddPacket(100, 100, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true, LastPacketInFrame: true}) require.True(t, fc.FrameIntegrity(100)) require.False(t, fc.FrameIntegrity(101)) require.False(t, fc.FrameIntegrity(99)) // frame too old than first frame fc.AddPacket(99, 99, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true, LastPacketInFrame: true}) // multiple packet frame, out of order fc.AddPacket(2001, 2001, &dependencydescriptor.DependencyDescriptor{}) require.False(t, fc.FrameIntegrity(2001)) require.False(t, fc.FrameIntegrity(1999)) // out of frame count(100) require.False(t, fc.FrameIntegrity(100)) require.False(t, fc.FrameIntegrity(1900)) fc.AddPacket(2000, 2001, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true}) require.False(t, fc.FrameIntegrity(2001)) fc.AddPacket(
func TestFrameIntegrityChecker(t *testing.T) { fc := NewFrameIntegrityChecker(100, 1000) // first frame out of order fc.AddPacket(10, 10, &dependencydescriptor.DependencyDescriptor{}) require.False(t, fc.FrameIntegrity(10)) fc.AddPacket(9, 10, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true}) require.False(t, fc.FrameIntegrity(10)) fc.AddPacket(11, 10, &dependencydescriptor.DependencyDescriptor{LastPacketInFrame: true}) require.True(t, fc.FrameIntegrity(10)) // single packet frame fc.AddPacket(100, 100, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true, LastPacketInFrame: true}) require.True(t, fc.FrameIntegrity(100)) require.False(t, fc.FrameIntegrity(101)) require.False(t, fc.FrameIntegrity(99)) // frame too old than first frame fc.AddPacket(99, 99, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true, LastPacketInFrame: true}) // multiple packet frame, out of order fc.AddPacket(2001, 2001, &dependencydescriptor.DependencyDescriptor{}) require.False(t, fc.FrameIntegrity(2001)) require.False(t, fc.FrameIntegrity(1999)) // out of frame count(100) require.False(t, fc.FrameIntegrity(100)) require.False(t, fc.FrameIntegrity(1900)) fc.AddPacket(2000, 2001, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true}) require.False(t, fc.FrameIntegrity(2001)) fc.AddPacket(2002, 2001, &dependencydescriptor.DependencyDescriptor{LastPacketInFrame: true}) require.True(t, fc.FrameIntegrity(2001)) // duplicate packet fc.AddPacket(2001, 2001, &dependencydescriptor.DependencyDescriptor{}) require.True(t, fc.FrameIntegrity(2001)) // frame too old fc.AddPacket(900, 1900, &dependencydescriptor.DependencyDescriptor{FirstPacketInFrame: true, LastPacketInFrame: true}) require.False(t, fc.FrameIntegrity(1900)) for frame := uint64(2002); frame < 2102; frame++ { // large frame (1000 packets) out of order / retransmitted firstFrame := uint64(3000 + (frame-2002)*1000) lastFrame := uint64(3999 + (frame-2002)*1000) frames := make([]uint64, 0, lastFrame-firstFrame+1) for i := firstFrame; i <= lastFrame; i++ { frames = append(frames, i) } require.False(t, fc.FrameIntegrity(frame)) rand.Seed(int64(frame)) rand.Shuffle(len(frames), func(i, j int) { frames[i], frames[j] = frames[j], frames[i] }) for i, f := range frames { fc.AddPacket(f, frame, &dependencydescriptor.DependencyDescriptor{ FirstPacketInFrame: f == firstFrame, LastPacketInFrame: f == lastFrame, }) require.Equal(t, i == len(frames)-1, fc.FrameIntegrity(frame), i) } require.True(t, fc.FrameIntegrity(frame)) } }
405,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: select-cost_test.go path of file: ./repos/go101/pages/optimizations/code/7-channel the code of the file until where you have to start completion: package channels import "testing" var ch1 = make(chan struct{}, 1) var ch2 = make(chan struct{}, 1) func Bench
func Benchmark_Select_FiveCases(b *testing.B) { for i := 0; i < b.N; i++ { select { case ch1 <- struct{}{}: <-ch1 case ch2 <- struct{}{}: <-ch2 case ch3 <- struct{}{}: <-ch3 case ch4 <- struct{}{}: <-ch4 case ch5 <- struct{}{}: <-ch5 } } }
584,108
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: fuzz_target.rs path of file: ./repos/s2n-quic/quic/s2n-quic-core/src/recovery/congestion_controller the code of the file until where you have to start completion: // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-L
fn on_packet_lost(&mut self, index: u8, rng: &mut dyn random::Generator) { let mut publisher = event::testing::Publisher::no_snapshot(); let mut publisher = PathPublisher::new(&mut publisher, path::Id::test_id()); let index = (index as usize).min(self.sent_packets.len().saturating_sub(1)); // Report the packet at the random `index` as lost if let Some(sent_packet_info) = self.sent_packets.remove(index) { if sent_packet_info.sent_bytes > 0 { // `recovery::Manager` does not call `on_packet_lost` if sent_bytes = 0 self.subject.on_packet_lost( sent_packet_info.sent_bytes as u32, sent_packet_info.cc_packet_info, false, false, rng, self.timestamp, &mut publisher, ); } } }
129,027
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: gen_EcKeyAlgorithm.rs path of file: ./repos/phaser/phaser/vendor/web-sys/src/features the code of the file until where you have to start completion: #![allow(unused_imports)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { # [wasm_bindgen (extends = :: js_sys :: Object , js_name = EcKeyAlgorithm)]
pub fn new(name: &str, named_curve: &str) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); ret.name(name); ret.named_curve(named_curve); ret }
622,195
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: close.rs path of file: ./repos/el_monitorro/src/bot/commands the code of the file until where you have to start completion: use super::Command; use super::Message; use super::Response; use frankenstein::InlineKeyboardButton; use typed_builder::Typ
fn execute(&self, message: &Message, command: &str) { info!( "{:?} wrote: closed a keyboard - {}", message.chat.id, command ); self.remove_message(&self.message); }
138,951
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: panic_matcher.go path of file: ./repos/plumber/vendor/github.com/onsi/gomega/matchers the code of the file until where you have to start completion: package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type PanicMatcher struct { Expected interface{} object interface{} } func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) { if actual == nil { return false, fmt.Errorf("PanicMatcher expects a non-nil actual.") } actualTyp
func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) { if matcher.Expected == nil { // We wanted any panic to occur, but none did. return format.Message(actual, "to panic") } if matcher.object == nil { // We wanted a panic with a specific value to occur, but none did. switch matcher.Expected.(type) { case omegaMatcher: return format.Message(actual, "to panic with a value matching", matcher.Expected) default: return format.Message(actual, "to panic with", matcher.Expected) } } // We got a panic, but the value isn't what we expected. switch matcher.Expected.(type) { case omegaMatcher: return format.Message( actual, fmt.Sprintf( "to panic with a value matching\n%s\nbut panicked with\n%s", format.Object(matcher.Expected, 1), format.Object(matcher.object, 1), ), ) default: return format.Message( actual, fmt.Sprintf( "to panic with\n%s\nbut panicked with\n%s", format.Object(matcher.Expected, 1), format.Object(matcher.object, 1), ), ) } }
458,035
You are an expert in writing code in many different languages. Your goal is 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.go path of file: ./repos/moby/vendor/github.com/containerd/containerd/archive the code of the file until where you have to start completion: /* Copyright The containerd Authors. Licensed under the A
func init() { if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { // This is a 64 bit timespec // os.Chtimes limits time to the following maxTime = time.Unix(0, 1<<63-1) } else { // This is a 32 bit timespec maxTime = time.Unix(1<<31-1, 0) } }
658,088
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: webhook_slack.go path of file: ./repos/gogs/internal/database the code of the file until where you have to start completion: // Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a M
func SlackTextFormatter(s string) string { // replace & < > s = strings.ReplaceAll(s, "&", "&amp;") s = strings.ReplaceAll(s, "<", "&lt;") s = strings.ReplaceAll(s, ">", "&gt;") return s }
691,096
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _update_action_type.rs path of file: ./repos/aws-sdk-rust/sdk/clouddirectory/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 `UpdateActionType`, it is important to ensure /
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self { UpdateActionType::CreateOrUpdate => write!(f, "CREATE_OR_UPDATE"), UpdateActionType::Delete => write!(f, "DELETE"), UpdateActionType::Unknown(value) => write!(f, "{}", value), } }
816,420
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: kubelet.rs path of file: ./repos/krustlet/crates/kubelet/src the code of the file until where you have to start completion: ///! This library contains code for running a kubelet. Use this to create a new ///! Kubelet with a specific handler (called a `Provider`) use crate::conf
async fn start_node_updater(client: kube::Client, node_name: String) -> anyhow::Result<()> { let sleep_interval = std::time::Duration::from_secs(10); loop { node::update(&client, &node_name).await; tokio::time::sleep(sleep_interval).await; } }
390,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: post_cwf_network_id_subscriber_config_base_names_base_name_responses.go path of file: ./repos/magma/orc8r/cloud/api/v1/go/client/carrier_wifi_networks the code of the file until where you have to start completion: // Code generated by go-swagger; DO NOT EDIT. package carrier_wifi_networks // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" models "magma/orc8r/cloud/api/v1/go/models" ) // PostCwfNetworkIDSubscriberConfigBaseNamesBaseNameReader is a Reader for the PostCwfNetworkIDSubscriberConfigBaseNamesBaseName structure. type PostCwfNetworkIDSubscriberConfigBaseNamesBaseNameReader struct { fo
func (o *PostCwfNetworkIDSubscriberConfigBaseNamesBaseNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 201: result := NewPostCwfNetworkIDSubscriberConfigBaseNamesBaseNameCreated() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: result := NewPostCwfNetworkIDSubscriberConfigBaseNamesBaseNameDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } }
573,277
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: csidriverspec.go path of file: ./repos/kubeedge/vendor/k8s.io/client-go/applyconfigurations/storage/v1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/license
func (b *CSIDriverSpecApplyConfiguration) WithTokenRequests(values ...*TokenRequestApplyConfiguration) *CSIDriverSpecApplyConfiguration { for i := range values { if values[i] == nil { panic("nil value passed to WithTokenRequests") } b.TokenRequests = append(b.TokenRequests, *values[i]) } return b }
418,394
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: spm_dcm_batch.m path of file: ./repos/PsPM/src/ext/VBA/stats&plots the code of the file until where you have to start completion: function [err,F,DCMnames] = spm_dcm_batch(DCM0dir,newVOIdir,newSPMdir,Unames,Ynames,est) % replicates one single subject DCM analysis over a set of subjects % function [err,F] = spm_dcm_batch(DCM0dir,newVOIdir,newSPMdir,Unames,Ynames) % IN: % - DCM0dir: directory where the original DCM files to be cloned are % stored % - newVOIdir: nsX1 cell-array of directories where the VOI files are % stored
function [err,F,DCMnames] = spm_dcm_batch(DCM0dir,newVOIdir,newSPMdir,Unames,Ynames,est) % replicates one single subject DCM analysis over a set of subjects % function [err,F] = spm_dcm_batch(DCM0dir,newVOIdir,newSPMdir,Unames,Ynames) % IN: % - DCM0dir: directory where the original DCM files to be cloned are % stored % - newVOIdir: nsX1 cell-array of directories where the VOI files are % stored % - newSPMdir: nsX1 cell-array of directories where the SPM files are % stored % - Unames: nsX1 cell array of ndcmX1 cell arrays of input names. For % each of the ns subjects, the function will look for each one of them in % the SPM file. NB: the order should match the original DCM structure. If % empty or unspecified, these will be set to the names of the inputs in % the original DCM structure % - Ynames: nsX1 cell array of ndcmX1 cell arrays of ROI names. For % each of the ns subjects, the function will look for each one of them in % the VOI files. NB: the order should match the original DCM structure. % If empty or unspecified, these will be set to the names of the ROIs in % the original DCM structure. % - est: flag for DCM estimation (1: estimate, 0: do not estimate) % OUT: % - err: nsXndcm array of error flags. It is 0 if DCM appropriately % cloned, 1 problem with ROIs, 2 if problem with inputs, 3 if problem % with the original DCM and 4 if problem when saving the DCM structure, 5 % if DCM could not be inverted and 6 if it could not be saved. % - F: nsXndcmX2 array of free energies. % - DCMnames: ndcmX1 cell array of DCM names ns = length(newVOIdir); if ~exist('Unames','var') || isempty(Unames) for i=1:ns Unames{i} = []; end
412,091
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: util.go path of file: ./repos/cointop/vendor/github.com/jeandeaual/go-locale the code of the file until where you have to start completion: //go:build !android // +build !android package loc
func splitLocale(locale string) (string, string) { // Remove the encoding, if present formattedLocale := strings.Split(locale, ".")[0] // Normalize by replacing the hyphens with underscores formattedLocale = strings.Replace(formattedLocale, "-", "_", -1) // Split at the underscore split := strings.Split(formattedLocale, "_") language := split[0] territory := "" if len(split) > 1 { territory = split[1] } return language, territory }
76,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: roundtrip.go path of file: ./repos/evcc/util/request the code of the file until where you have to start completion: package request import ( "bytes" "io" "net/http" "net/http/httputil" "strconv" "strings" "time" "github.com/evcc-io/evcc/util" "github.com/prometheus/client_golang/prometheus" ) type roundTripper struct { log *util.Logger base http.RoundTripper } var ( LogHeaders bool LogMaxLen = 1024 * 8 reqMetric *prometheus.SummaryVec resMetric *prometheus.CounterVec ) func init() { labels := []string{"host"} reqMetric = prometheus.NewSummaryVec(prometheus.SummaryOpts{ Namespace: "evcc", Subsystem: "http", Name: "request_duration_seconds", Help: "A summary of HTTP reques
func init() { labels := []string{"host"} reqMetric = prometheus.NewSummaryVec(prometheus.SummaryOpts{ Namespace: "evcc", Subsystem: "http", Name: "request_duration_seconds", Help: "A summary of HTTP request durations", Objectives: map[float64]float64{ 0.5: 0.05, // 50th percentile with a max. absolute error of 0.05 0.9: 0.01, // 90th percentile with a max. absolute error of 0.01 0.99: 0.001, // 99th percentile with a max. absolute error of 0.001 }, }, labels) resMetric = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: "evcc", Subsystem: "http", Name: "request_total", Help: "Total count of HTTP requests", }, append(labels, "status")) prometheus.MustRegister(reqMetric, resMetric) }
290,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: test_serde.rs path of file: ./repos/grafbase/engine/crates/engine/value/tests the code of the file until where you have to start completion: #![allow(unused_crate_dependencies)] use std::{collections::BTreeMap, fmt::Debug}; use bytes::Bytes; use engine_value::*; use serde::{de::DeserializeOwned, Deserialize, Serialize}; fn test_value<T: Serialize + DeserializeOwned + Clone + Partial
fn test_serde() { test_value(true); test_value(100i32); test_value(1.123f64); test_value(Some(100i32)); test_value(ConstValue::Null); test_value(vec![0i32, 1, 2, 3, 4, 5, 6, 7, 8, 9]); test_value(b"123456".to_vec()); #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] struct NewType(i32); test_value(NewType(100i32)); #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Hash, Copy, Clone, Ord, PartialOrd)] enum Enum { A, B, } test_value(Enum::A); test_value(Enum::B); let mut obj = BTreeMap::<Name, ConstValue>::new(); obj.insert(Name::new("A"), ConstValue::Number(10.into())); obj.insert(Name::new("B"), ConstValue::Number(20.into())); test_value(obj); let mut obj = BTreeMap::<Enum, ConstValue>::new(); obj.insert(Enum::A, ConstValue::Number(10.into())); obj.insert(Enum::B, ConstValue::Number(20.into())); test_value(obj); #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] struct Struct { a: i32, b: Option<Enum>, } test_value(Struct { a: 100, b: Some(Enum::B), }); }
546,911
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: compare_test.go path of file: ./repos/hugo/tpl/compare the code of the file until where you have to start completion: // Copyright 2017 The Hugo 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 License. // You may obtain a copy of the Licen
func TestLessEqualExtend(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) for _, test := range []struct { first any others []any expect bool }{ {1, []any{2, 3}, true}, {1, []any{1, 2}, true}, {2, []any{1, 2}, false}, {3, []any{2, 4}, false}, } { result := ns.Le(test.first, test.others...) c.Assert(result, qt.Equals, test.expect) } }
154,141