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: config.go
path of file: ./repos/v2ray-core/app/router
the code of the file until where you have to start completion: // +build !confonly
package router
import (
"v2ray.com/core/common/net"
"v2ray.com/core/f
| func (br *BalancingRule) Build(ohm outbound.Manager) (*Balancer, error) {
return &Balancer{
selectors: br.OutboundSelector,
strategy: &RandomStrategy{},
ohm: ohm,
}, nil
} | 674,120 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: ply_read.m
path of file: ./repos/gift/GroupICAT/icatb/@gifti/private
the code of the file until where you have to start completion: function M = ply_read(filename)
% Read PLY-formatted data from disk
% FORMAT M = ply_read(filename)
%
% filename - PLY-formatted file name
% M - data structure
| function M = ply_read(filename)
% Read PLY-formatted data from disk
% FORMAT M = ply_read(filename)
%
% filename - PLY-formatted file name
% M - data structure
%__________________________________________________________________________
%
% Stanford Triangle Format Specification:
% https://en.wikipedia.org/wiki/PLY_%28file_format%29
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: ply_read.m 7239 2017-12-15 17:14:33Z guillaume $
fid = fopen(filename,'rt');
if fid == -1
error('Cannot open %s.',filename);
end | 347,902 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: info.go
path of file: ./repos/sliver/client/command/info
the code of the file until where you have to start completion: package info
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU
| func PIDCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
session, beacon := con.ActiveTarget.GetInteractive()
if session == nil && beacon == nil {
return
}
if session != nil {
con.Printf("%d\n", session.PID)
} else if beacon != nil {
con.Printf("%d\n", beacon.PID)
}
} | 450,348 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: cli_base.rb
path of file: ./repos/kuby-core/lib/kuby
the code of the file until where you have to start completion: # typed: strict
require 'open3'
require 'thread'
module K
| def systemm_open3(cmd)
run_before_callbacks(cmd)
cmd_s = cmd.join(' ')
Open3.popen3(cmd_s) do |p_stdin, p_stdout, p_stderr, wait_thread|
Thread.new(stdout) do |t_stdout|
begin
p_stdout.each { |line| t_stdout.puts(line) }
rescue IOError
end
end
Thread.new(stderr) do |t_stderr|
begin
p_stderr.each { |line| t_stderr.puts(line) }
rescue IOError
end
end | 292,561 |
You are an expert in writing code in many different languages. Your goal is 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_SetAlarmState.go
path of file: ./repos/aws-sdk-go-v2/service/cloudwatch
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package cloudwatch
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/a
| func newServiceMetadataMiddleware_opSetAlarmState(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
OperationName: "SetAlarmState",
}
} | 218,307 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: range-v3.rb
path of file: ./repos/homebrew-core/Formula/r
the code of the file until where you have to start completion: class RangeV3 < Formula
desc "Experimental range library for C++14/17/20"
homep
| def install
system "cmake", ".",
"-DRANGE_V3_TESTS=OFF",
"-DRANGE_V3_HEADER_CHECKS=OFF",
"-DRANGE_V3_EXAMPLES=OFF",
"-DRANGE_V3_PERF=OFF",
*std_cmake_args
system "make", "install"
end | 696,463 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: typo_options.rb
path of file: ./repos/ronin/lib/ronin/cli
the code of the file until where you have to start completion: # frozen_string_literal: true
#
# Copyright (c) 2006-2023 Hal Brodigan (postmodern.mod3 at gmail.com)
#
# Ronin is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ronin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY;
| def self.included(command)
command.option :omit_chars, desc: 'Toggles whether to omit repeated characters' do
@typo_kwargs[:emit_chars] = true
end
command.option :repeat_chars, desc: 'Toggles whether to repeat single characters' do
@typo_kwargs[:repeat_chars] = true
end
command.option :swap_chars, desc: 'Toggles whether to swap certain common character pairs' do
@typo_kwargs[:swap_chars] = true
end
command.option :change_suffix, desc: 'Toggles whether to change the suffix of words' do
@typo_kwargs[:change_suffix] = true
end
end | 462,169 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: plugin.rs
path of file: ./repos/bevy_xpbd/crates/bevy_xpbd_3d/examples/kinematic_character_3d
the code of the file until where you have to start completion: use bevy::{ecs::query::Has, prelude::*};
use bevy_xpbd_3d::{math::*, prelude::*, SubstepSchedule, SubstepSet};
pub struct CharacterControllerPlugin;
impl Plugin for CharacterControllerPlugin {
fn build(&self, app: &mut App) {
app.add_event::<MovementAction>()
.add_systems(
Update,
(
keyboard_input,
gamepad_input,
update_grounded,
apply_gravity,
movement,
apply_movement_damping,
| pub fn new(collider: Collider, gravity: Vector) -> Self {
// Create shape caster as a slightly smaller version of collider
let mut caster_shape = collider.clone();
caster_shape.set_scale(Vector::ONE * 0.99, 10);
Self {
character_controller: CharacterController,
rigid_body: RigidBody::Kinematic,
collider,
ground_caster: ShapeCaster::new(
caster_shape,
Vector::ZERO,
Quaternion::default(),
Direction3d::NEG_Y,
)
.with_max_time_of_impact(0.2),
gravity: ControllerGravity(gravity),
movement: MovementBundle::default(),
}
} | 534,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: shutdown.go
path of file: ./repos/go-zero/core/proc
the code of the file until where you have to start completion: //go:build linux || darwin
package proc
import (
"os"
"os/s
| func (lm *listenerManager) notifyListeners() {
lm.lock.Lock()
defer lm.lock.Unlock()
group := threading.NewRoutineGroup()
for _, listener := range lm.listeners {
group.RunSafe(listener)
}
group.Wait()
lm.listeners = nil
} | 258,447 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: corrcoefslices.m
path of file: ./repos/acycle/code/corrcoef
the code of the file until where you have to start completion: function [corrCI,corr_h0,corry] = corrcoefslices(dat,target,orbit7,dt,pad,sr1,sr2,srstep,adjust,red,nsim,plotn,slices)
% Modify from corrcoefsig.m, but replace display with a function of slices
% INPUT
| function [corrCI,corr_h0,corry] = corrcoefslices(dat,target,orbit7,dt,pad,sr1,sr2,srstep,adjust,red,nsim,plotn,slices)
% Modify from corrcoefsig.m, but replace display with a function of slices
% INPUT
% dat: 2 column time series of depth and value. Unit of depth must be m
% The first column must be evenly spaced
% target: target series, generated from gentarget.m
% orbit7: 7 orbital target frequencies
% dt: sample rates of input series (the dat)
% pad: zero-padding of periodogram of input series: dat. default = 5000
% sr1: begining sedimentation rates to be estimated, unit must be cm/kyr
% sr2: end | 438,557 |
You are an expert in writing code in many different languages. Your goal is 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_manipulation.rb
path of file: ./repos/truffleruby/lib/mri/bundler/vendor/thor/lib/thor/actions
the code of the file until where you have to start completion: require "erb"
class Bundler::Thor
module Actions
# Copies the file from the relative source to the relative destination. If
# the destination is not given
| def template(source, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
destination = args.first || source.sub(/#{TEMPLATE_EXTNAME}$/, "")
source = File.expand_path(find_in_source_paths(source.to_s))
context = config.delete(:context) || instance_eval("binding")
create_file destination, nil, config do
match = ERB.version.match(/(\d+\.\d+\.\d+)/)
capturable_erb = if match && match[1] >= "2.2.0" # Ruby 2.6+
CapturableERB.new(::File.binread(source), :trim_mode => "-", :eoutvar => "@output_buffer")
else
CapturableERB.new(::File.binread(source), nil, "-", "@output_buffer")
end
content = capturable_erb.tap do |erb|
erb.filename = source
end.result(context)
content = yield(content) if block
content
end
end | 176,664 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: _capacity_reservation_preference.rs
path of file: ./repos/aws-sdk-rust/sdk/ec2/src/types
the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NO
| fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self {
CapacityReservationPreference::None => write!(f, "none"),
CapacityReservationPreference::Open => write!(f, "open"),
CapacityReservationPreference::Unknown(value) => write!(f, "{}", value),
}
} | 805,115 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: authkeys_test.go
path of file: ./repos/juju/cmd/juju/common
the code of the file until where you have to start completion: // Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
| func (s *AuthKeysSuite) TestReadAuthorizedKeysErrors(c *gc.C) {
ctx := cmdtesting.Context(c)
_, err := common.ReadAuthorizedKeys(ctx, "")
c.Assert(err, gc.ErrorMatches, "no public ssh keys found")
c.Assert(err, gc.Equals, common.ErrNoAuthorizedKeys)
_, err = common.ReadAuthorizedKeys(ctx, filepath.Join(s.dotssh, "notthere.pub"))
c.Assert(err, gc.ErrorMatches, "no public ssh keys found")
c.Assert(err, gc.Equals, common.ErrNoAuthorizedKeys)
} | 614,790 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: commit_walker.go
path of file: ./repos/awless/vendor/gopkg.in/src-d/go-git.v4/plumbing/object
the code of the file until where you have to start completion: package object
import (
"io"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
)
type commitPreIterator struct {
seen map[plumbing.Hash]bool
stack []CommitIt
| func filteredParentIter(c *Commit, seen map[plumbing.Hash]bool) CommitIter {
var hashes []plumbing.Hash
for _, h := range c.ParentHashes {
if !seen[h] {
hashes = append(hashes, h)
}
}
return NewCommitIter(c.s,
storer.NewEncodedObjectLookupIter(c.s, plumbing.CommitObject, hashes),
)
} | 335,962 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: simpleEVD.m
path of file: ./repos/lrslibrary/algorithms/st/MEDRoP
the code of the file until where you have to start completion: function P_hat = simpleEVD(X, r)
%%%Function to implement the Simple-EVD algorithm and returns a basis
%%%matrix for the new subspace -- edit these comments before Gitting
%%% Inputs %%%
%%% X - Emperical Covariance data matrix (m X m) %%%
%%% r - Target rank of output %%%
| function P_hat = simpleEVD(X, r)
%%%Function to implement the Simple-EVD algorithm and returns a basis
%%%matrix for the new subspace -- edit these comments before Gitting
%%% Inputs %%%
%%% X - Emperical Covariance data matrix (m X m) %%%
%%% r - Target rank of output %%%
%%% Outputs %%%
%%% P_hat - Basis matrix for output (m X r) %%%
[P_hat, ~] = svds(X, r);
end | 370,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: builders.rs
path of file: ./repos/aws-sdk-rust/sdk/connect/src/operation/update_queue_hours_of_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.
pub use crate::operation::update_qu
| 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,
}
} | 755,462 |
You are an expert in writing code in many different languages. Your goal is 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/appstream/src/operation/create_image_builder_streaming_url
the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub use crate::
| pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self {
Self {
handle,
inner: ::std::default::Default::default(),
config_override: ::std::option::Option::None,
}
} | 785,972 |
You are an expert in writing code in many different languages. Your goal is 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_omap.rb
path of file: ./repos/artichoke/artichoke-backend/vendor/ruby/test/psych
the code of the file until where you have to start completion: # frozen_string_li
| def test_dump
map = Psych::Omap['a', 'b', 'c', 'd']
yaml = Psych.dump(map)
assert_match('!omap', yaml)
assert_match('- a: b', yaml)
assert_match('- c: d', yaml)
end | 312,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: 240. Search a 2D Matrix II_test.go
path of file: ./repos/LeetCode-Go/leetcode/0240.Search-a-2D-Matrix-II
the code of the file until where you have to start completion: package leetcode
import (
"fmt"
"testing"
)
type question240 struct {
para240
ans240
}
// para 是参数
// one 代表第一个参数
type para240 struct {
matrix [][]int
target int
}
// ans 是答案
// one 代表第一个答案
type ans240 s
| func Test_Problem240(t *testing.T) {
qs := []question240{
{
para240{[][]int{{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}}, 5},
ans240{true},
},
{
para240{[][]int{{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}}, 20},
ans240{false},
},
}
fmt.Printf("------------------------Leetcode Problem 240------------------------\n")
for _, q := range qs {
_, p := q.ans240, q.para240
fmt.Printf("【input】:%v 【output】:%v\n", p, searchMatrix240(p.matrix, p.target))
}
fmt.Printf("\n\n\n")
} | 510,404 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: b3_test.go
path of file: ./repos/opencensus-go/plugin/ochttp/propagation/b3
the code of the file until where you have to start completion: // Copyright 2018, OpenCensus 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 b3
import (
"net/http"
"reflect"
"testing"
"go.opencensus.io/trace"
)
func TestHTTPFormat_FromRequest(t *testing.T) {
tests := []struct {
name string
makeReq func() *http.Request
wantSc trace.SpanContext
wantOk bool
}{
{
name: "128-bit trace ID + 64-bit span ID; sampled=1",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "0020000000000001")
req.Header.Set(SampledHeader, "1")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{70, 58, 195, 92, 159, 100, 19, 173, 72, 72, 90, 57, 83, 187, 97, 36},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(1),
},
wantOk: true,
},
{
name: "short trace ID + short span ID; sampled=1",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "000102")
req.Header.Set(SpanIDHeader, "000102")
req.Header.Set(SampledHeader, "1")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2},
SpanID: trace.SpanID{0, 0, 0, 0, 0, 0, 1, 2},
TraceOptions: trace.TraceOptions(1),
},
wantOk: true,
},
{
name: "64-bit trace ID + 64-bit span ID; sampled=0",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "0020000000000001")
req.Header.Set(SpanIDHeader, "0020000000000001")
req.Header.Set(SampledHeader, "0")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 1},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(0),
},
wantOk: true,
},
{
name: "128-bit trace ID + 64-bit span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "0020000000000001")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{70, 58, 195, 92, 159, 100, 19, 173, 72, 72, 90, 57, 83, 187, 97, 36},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(0),
},
wantOk: true,
},
{
name: "invalid trace ID + 64-bit span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "")
req.Header.Set(SpanIDHeader, "0020000000000001")
return req
},
wantSc: trace.SpanContext{},
wantOk: false,
},
{
name: "invalid >128-bit trace ID + 64-bit span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "0020000000000001002000000000000111")
req.Header.Set(SpanIDHeader, "0020000000000001")
return req
},
wantSc: trace.SpanContext{},
wantOk: false,
},
{
name: "128-bit trace ID; invalid span ID; no
| func TestHTTPFormat_FromRequest(t *testing.T) {
tests := []struct {
name string
makeReq func() *http.Request
wantSc trace.SpanContext
wantOk bool
}{
{
name: "128-bit trace ID + 64-bit span ID; sampled=1",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "0020000000000001")
req.Header.Set(SampledHeader, "1")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{70, 58, 195, 92, 159, 100, 19, 173, 72, 72, 90, 57, 83, 187, 97, 36},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(1),
},
wantOk: true,
},
{
name: "short trace ID + short span ID; sampled=1",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "000102")
req.Header.Set(SpanIDHeader, "000102")
req.Header.Set(SampledHeader, "1")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2},
SpanID: trace.SpanID{0, 0, 0, 0, 0, 0, 1, 2},
TraceOptions: trace.TraceOptions(1),
},
wantOk: true,
},
{
name: "64-bit trace ID + 64-bit span ID; sampled=0",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "0020000000000001")
req.Header.Set(SpanIDHeader, "0020000000000001")
req.Header.Set(SampledHeader, "0")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 1},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(0),
},
wantOk: true,
},
{
name: "128-bit trace ID + 64-bit span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "0020000000000001")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{70, 58, 195, 92, 159, 100, 19, 173, 72, 72, 90, 57, 83, 187, 97, 36},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(0),
},
wantOk: true,
},
{
name: "invalid trace ID + 64-bit span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "")
req.Header.Set(SpanIDHeader, "0020000000000001")
return req
},
wantSc: trace.SpanContext{},
wantOk: false,
},
{
name: "invalid >128-bit trace ID + 64-bit span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "0020000000000001002000000000000111")
req.Header.Set(SpanIDHeader, "0020000000000001")
return req
},
wantSc: trace.SpanContext{},
wantOk: false,
},
{
name: "128-bit trace ID; invalid span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "")
return req
},
wantSc: trace.SpanContext{},
wantOk: false,
},
{
name: "128-bit trace ID; invalid >64 bit span ID; no sampling header",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "002000000000000111")
return req
},
wantSc: trace.SpanContext{},
wantOk: false,
},
{
name: "128-bit trace ID + 64-bit span ID; sampled=true",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "0020000000000001")
req.Header.Set(SampledHeader, "true")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{70, 58, 195, 92, 159, 100, 19, 173, 72, 72, 90, 57, 83, 187, 97, 36},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(1),
},
wantOk: true,
},
{
name: "128-bit trace ID + 64-bit span ID; sampled=false",
makeReq: func() *http.Request {
req, _ := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(TraceIDHeader, "463ac35c9f6413ad48485a3953bb6124")
req.Header.Set(SpanIDHeader, "0020000000000001")
req.Header.Set(SampledHeader, "false")
return req
},
wantSc: trace.SpanContext{
TraceID: trace.TraceID{70, 58, 195, 92, 159, 100, 19, 173, 72, 72, 90, 57, 83, 187, 97, 36},
SpanID: trace.SpanID{0, 32, 0, 0, 0, 0, 0, 1},
TraceOptions: trace.TraceOptions(0),
},
wantOk: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &HTTPFormat{}
sc, ok := f.SpanContextFromRequest(tt.makeReq())
if ok != tt.wantOk {
t.Errorf("HTTPFormat.SpanContextFromRequest() got ok = %v, want %v", ok, tt.wantOk)
}
if !reflect.DeepEqual(sc, tt.wantSc) {
t.Errorf("HTTPFormat.SpanContextFromRequest() got span context = %v, want %v", sc, tt.wantSc)
}
})
}
} | 113,616 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: exportlayer.go
path of file: ./repos/docker-ce/components/engine/vendor/github.com/Microsoft/hcsshim/internal/wclayer
the code of the file until where you have to start completion: package wclayer
import (
"context"
"io/ioutil"
"os"
"strings"
"github.com/Microsoft/go-winio"
"github.com/Microsof
| func (r *legacyLayerReaderWrapper) Close() (err error) {
defer r.s.End()
defer func() { oc.SetSpanStatus(r.s, err) }()
err = r.legacyLayerReader.Close()
os.RemoveAll(r.root)
return err
} | 566,743 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: gitlab_migration_release_spec.rb
path of file: ./repos/gitlabhq/qa/qa/specs/features/api/1_manage/migration
the code of the file until where you have to start completion: # frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Gitlab migration', product_group: :import_and_integrate do
include_context 'with gitlab project migration'
context 'with release' do
let!(:tag) { 'v0.0.1' }
let!(:source_project_with_readme) { true }
let!(:milestone) { create(:project_milestone, project: source_project, api_client: source_admin_api_client) }
let(:source_release) { comparable_release(source_project.releases.find { |r| r[:tag_name] == tag }) }
le
| def comparable_release(release)
release&.except(:_links)&.merge(
{
author: release[:author].except(:web_url),
commit: release[:commit].except(:web_url),
commit_path: release[:commit_path].split("/-/").last,
tag_path: release[:tag_path].split("/-/").last,
assets: release[:assets].merge({
sources: release.dig(:assets, :sources).map do |source|
source.merge({ url: source[:url].split("/-/").last })
end
}),
milestones: release[:milestones].map do |milestone|
milestone.except(:id, :project_id).merge({ web_url: milestone[:web_url].split("/-/").last })
end,
# evidences are not directly migrated but rather recreated on the same releases,
# so we only check the json file is there
evidences: release[:evidences].map do |evidence|
evidence
.except(:collected_at, :sha)
.merge({ filepath: evidence[:filepath].split("/-/").last.gsub(/\d+\.json/, "*.json") })
end
}
)
end
before do
source_project.create_release(tag, milestones: [milestone.title])
end
it(
'successfully imports project release',
testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/360243'
) do
expect_project_import_finished_successfully
expect(imported_releases.size).to eq(1), "Expected to have 1 migrated release"
expect(imported_release).to eq(source_release)
end
end | 298,927 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: getMsgTypeAndOptions.m
path of file: ./repos/CellExplorer/toolboxes/umap1.3.3/util
the code of the file until where you have to start completion: % AUTHORSHIP
% Primary Developer: Stephen Meehan <swmeehan@stanford.edu>
% Math Lead & Secondary Developer: Connor Meehan <cgmeehan@alumni
| function [msgType, jsa, default, defaultIdx, isNumerics]=...
getMsgTypeAndOptions(msgType, args)
defaultIdx=1;
N=length(args);
isNumerics={};
if N>0 && iscell(args{1})
args=args{1};
N=length(args);
end | 149,047 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: json_value.rb
path of file: ./repos/rollbar-gem/lib/rollbar/middleware/js
the code of the file until where you have to start completion: # Allows a Ruby String to be
| def to_json(opts = {})
# Return the raw value if this is from the js middleware
return value if opts.class == Rollbar::JSON::JsOptionsState
# Otherwise convert to a string
%Q["#{value}"]
end | 719,079 |
You are an expert in writing code in many different languages. Your goal is 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.xpack.ml.delete_trained_model_alias.go
path of file: ./repos/go-elasticsearch/esapi
the code of the file until where you have to start completion: // Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V.
| func (f MLDeleteTrainedModelAlias) WithHeader(h map[string]string) func(*MLDeleteTrainedModelAliasRequest) {
return func(r *MLDeleteTrainedModelAliasRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
} | 672,056 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: terminal_panel.rs
path of file: ./repos/zed/crates/terminal_view/src
the code of the file until where you have to start completion: use std::{ops::ControlFlow, path::PathBuf, sync::Arc};
use crate::TerminalView;
use collections::{HashMap, HashSet};
use db::kvp::KEY_VALUE_STORE;
use futures::future::join_all;
use gpui::{
actions, AppContext, AsyncWindowContext, Entity, EventEmitter, ExternalPa
| pub fn init(cx: &mut AppContext) {
cx.observe_new_views(
|workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
workspace.register_action(TerminalPanel::new_terminal);
workspace.register_action(TerminalPanel::open_terminal);
workspace.register_action(|workspace, _: &ToggleFocus, cx| {
workspace.toggle_panel_focus::<TerminalPanel>(cx);
});
},
)
.detach();
} | 108,435 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: 20210126105837_create_active_storage_variant_records.active_storage.rb
path of file: ./repos/activestorage-aliyun/test/dummy/db/migrate
the code of the file until where you have to start completion: # This migration comes from active_storage (originally 20191206030411)
class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0]
def change
create_t
| def change
create_table :active_storage_variant_records do |t|
t.belongs_to :blob, null: false, index: false
t.string :variation_digest, null: false
t.index %i[blob_id variation_digest], name: "index_active_storage_variant_records_uniqueness", unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end | 349,426 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: fn_get_attr_test.go
path of file: ./repos/trivy/pkg/iac/scanners/cloudformation/parser
the code of the file until where you have to start completion: package parser
import (
"github.com/stretchr/testify/assert"
"github.com/s
| func Test_resolve_get_attr_value(t *testing.T) {
source := `---
Resources:
ElasticacheSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Elasticache Security Group
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 11211
ToPort: 11211
SourceSecurityGroupName: !Ref InstanceSecurityGroup
ElasticacheCluster:
Type: 'AWS::ElastiCache::CacheCluster'
Properties:
Engine: memcached
CacheNodeType: cache.t2.micro
NumCacheNodes: '1'
VpcSecurityGroupIds:
- !GetAtt
- ElasticacheSecurityGroup
- GroupId
`
ctx := createTestFileContext(t, source)
require.NotNil(t, ctx)
testRes := ctx.GetResourceByLogicalID("ElasticacheCluster")
assert.NotNil(t, testRes)
sgProp := testRes.GetProperty("VpcSecurityGroupIds")
require.True(t, sgProp.IsNotNil())
require.True(t, sgProp.IsList())
for _, property := range sgProp.AsList() {
resolved, success := ResolveIntrinsicFunc(property)
require.True(t, success)
assert.True(t, resolved.IsNotNil())
}
} | 726,076 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: dataset2files.m
path of file: ./repos/fieldtrip/private
the code of the file until where you have to start completion: function cfg = dataset2files(cfg)
% Helper function that converts a dataset into headerfile and datafile
% if necessary. This is used in PREPROCESSING and DEFINETRIAL
%
% This function operates only on
% cfg.dataset
% cfg.datafile
% cfg.headerfile
% and returns the updated cfg.
% Copyright (C) 2004, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
| function cfg = dataset2files(cfg)
% Helper function that converts a dataset into headerfile and datafile
% if necessary. This is used in PREPROCESSING and DEFINETRIAL
%
% This function operates only on
% cfg.dataset
% cfg.datafile
% cfg.headerfile
% and returns the updated cfg.
% Copyright (C) 2004, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$
% start with empty fields if thery are not present
if ~isfield(cfg, 'dataset')
cfg.dataset = [];
end | 682,958 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: server.rs
path of file: ./repos/tremor-runtime/tremor-cli/src
the code of the file until where you have to start completion: // Copyright 2020-2021, The Tremor Team
//
// 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 agr
| async fn run(&self) {
version::print();
match self.run_dun().await {
Err(e) => {
match e {
Error(ErrorKind::AnyhowError(anyhow_e), _) => {
log_and_print_error!("{:?}", anyhow_e);
}
e => {
log_and_print_error!("Error: {}", e);
for e in e.iter().skip(1) {
eprintln!("Caused by: {e}");
}
}
}
log_and_print_error!("We are SHUTTING DOWN due to errors during initialization!");
// ALLOW: we are purposefully exiting the process here
::std::process::exit(1);
}
Ok(res) => {
// ALLOW: we are purposefully exiting the process here
::std::process::exit(res)
}
}
} | 751,790 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: main.go
path of file: ./repos/google-cloud-go/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetLocation
the code of the file until where you have to start completion: // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
// [START privateca_v1_generated_CertificateAuthorityService_GetLocation_sync]
package main
import (
"context"
privateca "clo
| func main() {
ctx := context.Background()
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in:
// https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
c, err := privateca.NewCertificateAuthorityClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &locationpb.GetLocationRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/location#GetLocationRequest.
}
resp, err := c.GetLocation(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
} | 278,849 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: wrap.go
path of file: ./repos/sealer/vendor/golang.org/x/xerrors
the code of the file until where you have to start completion: // Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license th
| func (e noWrapper) FormatError(p Printer) (next error) {
if f, ok := e.error.(Formatter); ok {
return f.FormatError(p)
}
p.Print(e.error)
return nil
} | 725,296 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: gift.go
path of file: ./repos/studygolang/internal/http/controller
the code of the file until where you have to start completion: // Copyright 2017 The StudyGolang Authors. All rights res
| func (GiftController) GiftList(ctx echo.Context) error {
gifts := logic.DefaultGift.FindAllOnline(context.EchoContext(ctx))
if len(gifts) > 0 {
user, ok := ctx.Get("user").(*model.Me)
if ok {
logic.DefaultGift.UserCanExchange(context.EchoContext(ctx), user, gifts)
}
}
data := map[string]interface{}{
"gifts": gifts,
}
return render(ctx, "gift/list.html", data)
} | 118,840 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: SimpAllExplicitInterpolator.m
path of file: ./repos/Swan/Topology Optimization/MaterialInterpolation
the code of the file until where you have to start completion: classdef SimpAllExplicitInterpolator < handle
properties (Access = private)
muFunc
dmuFunc
kappaFunc
dkappaFunc
end
properties (Access = private)
ndim
| function init(obj,cParams)
obj.matA = cParams.matA;
obj.matB = cParams.matB;
obj.computeNDim(cParams);
end
function computeNDim(obj,cParams)
switch cParams.dim
case '2D'
obj.ndim = 2;
case '3D'
obj.ndim = 3;
end
end
function computeSymbolicInterpolationFunctions(obj)
[muS,dmuS,kS,dkS] = obj.computeSymbolicMuKappa();
obj.muFunc = matlabFunction(muS);
obj.dmuFunc = matlabFunction(dmuS);
obj.kappaFunc = matlabFunction(kS);
obj.dkappaFunc = matlabFunction(dkS);
end | 307,770 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: va_1995.rb
path of file: ./repos/vets-api/app/models/form_profiles
the code of the file until where you have to start completion: # frozen_string
| def metadata
{
version: 0,
prefill: true,
returnUrl: '/applicant/information'
}
end | 575,393 |
You are an expert in writing code in many different languages. Your goal is 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_linux.go
path of file: ./repos/chaos-mesh/cmd/watchmaker
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 use this file except in compliance with the License.
// You may obtain a copy of the License at
| func main() {
fmt.Println("Watchmaker will not support recovery function in future," +
" please use time attack in chaosd.")
initFlag()
version.PrintVersionInfo("watchmaker")
if printVersion {
os.Exit(0)
}
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("error while creating zap logger: %v", err))
}
log := zapr.NewLogger(zapLog)
clkIds := strings.Split(clockIdsSlice, ",")
mask, err := utils.EncodeClkIds(clkIds)
if err != nil {
log.Error(err, "error while converting clock ids to mask")
os.Exit(1)
}
log.Info("get clock ids mask", "mask", mask)
s, err := time.GetSkew(log, time.NewConfig(secDelta, nsecDelta, mask))
if err != nil {
log.Error(err, "error while GetSkew")
os.Exit(1)
}
err = s.Inject(tasks.SysPID(pid))
if err != nil {
log.Error(err, "error while modifying time", "pid", pid, "secDelta", secDelta, "nsecDelta", nsecDelta, "mask", mask)
}
} | 434,901 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: dtr1r2d_dtr1r2d2m.m
path of file: ./repos/md-dmri/methods/dtr1r2d
the code of the file until where you have to start completion: function m = dtr1r2d_dtr1r2d2m(dtr1r2d,opt)
| function m = dtr1r2d_dtr1r2d2m(dtr1r2d,opt)
m = zeros(1 + 7*opt.dtr1r2d.n_out,1);
if ~isempty(dtr1r2d)
m(1:numel(dtr1r2d)) = dtr1r2d;
m = m(1:(1 + 7*opt.dtr1r2d.n_out),1);
m(1) = min([dtr1r2d(1) opt.dtr1r2d.n_out]);
end | 410,450 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: bob_getPose.m
path of file: ./repos/ethx-autonomous-mobile-robot/exercise/solution1/code/common/vrep
the code of the file until where you have to start completion: function [x y gamma] = bob_getPose(connection)
global isoctave;
if ~isoctave
[result,data]=connection.vrep.simxGetStringSignal(connection.clientID,strcat('Bob_pose',num2str(connection.robotNb)),connection.vrep.simx_opmode_buffer);
if (result~=connection.vrep.simx_error_noerror)
| function [x y gamma] = bob_getPose(connection)
global isoctave;
if ~isoctave
[result,data]=connection.vrep.simxGetStringSignal(connection.clientID,strcat('Bob_pose',num2str(connection.robotNb)),connection.vrep.simx_opmode_buffer);
if (result~=connection.vrep.simx_error_noerror)
err = MException('VREP:RemoteApiError', ...
'simxGetStringSignal failed');
throw(err);
end | 19,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: typeext.rs
path of file: ./repos/HarTex/discord-frontend/hartex-discord-entitycache-macros/src
the code of the file until where you have to start completion: /*
* SPDX-License-Identifier: AGPL-3.0-only
*
* This file is part of HarTex.
*
* HarTex
* Copyright (c) 2021-2024 HarTex Project Developers
*
* HarTex is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* th
| fn is_vec_of(&self, vec_of: &str) -> bool {
let Type::Path(path) = self else {
return false;
};
let last = path.path.segments.last().unwrap();
if last.ident == "Vec"
&& let PathArguments::AngleBracketed(angle_bracketed) = &last.arguments
&& let Some(GenericArgument::Type(Type::Path(path))) = angle_bracketed.args.first()
{
let last = path.path.segments.last().unwrap();
return last.ident == vec_of;
}
false
} | 550,325 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: api_op_ResetJobBookmark.go
path of file: ./repos/aws-sdk-go-v2/service/glue
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package glue
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/service/glue/types"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Resets a bookmark entry. For more information a
| func (c *Client) ResetJobBookmark(ctx context.Context, params *ResetJobBookmarkInput, optFns ...func(*Options)) (*ResetJobBookmarkOutput, error) {
if params == nil {
params = &ResetJobBookmarkInput{}
}
result, metadata, err := c.invokeOperation(ctx, "ResetJobBookmark", params, optFns, c.addOperationResetJobBookmarkMiddlewares)
if err != nil {
return nil, err
}
out := result.(*ResetJobBookmarkOutput)
out.ResultMetadata = metadata
return out, nil
} | 228,547 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: flags_test.go
path of file: ./repos/ristretto/z
the code of the file until where you have to start completion: package z
import (
"fmt"
"os"
"os/user"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestFlag(t *testing.T) {
const opt = `bool_key=true; int-key=5; float-key=0.05; string_key=value; ;`
const def = `bool_key=false; int-key=0; float-key=1.0; string-key=; other-key=5;
duration-minutes=15m; duration-hours=12h; duration-days=30d;`
_, err := NewSuperFlag("boolo-key=true").mergeAndCheckDefaultImpl(def)
require.Error(t, err)
_, err = newSuperFlagImpl("key-without-value")
require.Error(t, err)
// bool-key and int-key should not be overwritten. Only other-key should be set.
sf := NewSuperFlag(opt)
sf.MergeAndCheckDefault(def)
require.Equal(t, true, sf.GetBool("bool-key"))
require.Equal(
| func TestGetPath(t *testing.T) {
usr, err := user.Current()
require.NoError(t, err)
homeDir := usr.HomeDir
cwd, err := os.Getwd()
require.NoError(t, err)
tests := []struct {
path string
expected string
}{
{
"/home/user/file.txt",
"/home/user/file.txt",
},
{
"~/file.txt",
filepath.Join(homeDir, "file.txt"),
},
{
"~/abc/../file.txt",
filepath.Join(homeDir, "file.txt"),
},
{
"~/",
homeDir,
},
{
"~filename",
filepath.Join(cwd, "~filename"),
},
{
"./filename",
filepath.Join(cwd, "filename"),
},
{
"",
"",
},
{
"./",
cwd,
},
}
get := func(p string) string {
opt := fmt.Sprintf("file=%s", p)
sf := NewSuperFlag(opt)
return sf.GetPath("file")
}
for _, tc := range tests {
actual := get(tc.path)
require.Equalf(t, tc.expected, actual, "Failed on testcase: %s", tc.path)
}
} | 13,505 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: main_test.go
path of file: ./repos/tidb/pkg/planner/implementation
the code of the file until where you have to start completion: // Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (th
| func TestMain(m *testing.M) {
testsetup.SetupForCommonTest()
opts := []goleak.Option{
goleak.IgnoreTopFunction("github.com/golang/glog.(*fileSink).flushDaemon"),
goleak.IgnoreTopFunction("github.com/bazelbuild/rules_go/go/tools/bzltestutil.RegisterTimeoutHandler.func1"),
goleak.IgnoreTopFunction("github.com/lestrrat-go/httprc.runFetchWorker"),
goleak.IgnoreTopFunction("go.etcd.io/etcd/client/pkg/v3/logutil.(*MergeLogger).outputLoop"),
}
goleak.VerifyTestMain(m, opts...)
} | 580,142 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: readerc.go
path of file: ./repos/trickster/vendor/gopkg.in/yaml.v2
the code of the file until where you have to start completion: package yaml
import (
"io"
)
// Set the reader error and return 0.
func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool {
parser.error = yaml_READER_ERROR
parser.problem = problem
parser.problem_offset = offs
| func yaml_parser_determine_encoding(parser *yaml_parser_t) bool {
// Ensure that we had enough bytes in the raw buffer.
for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 {
if !yaml_parser_update_raw_buffer(parser) {
return false
}
}
// Determine the encoding.
buf := parser.raw_buffer
pos := parser.raw_buffer_pos
avail := len(buf) - pos
if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] {
parser.encoding = yaml_UTF16LE_ENCODING
parser.raw_buffer_pos += 2
parser.offset += 2
} else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] {
parser.encoding = yaml_UTF16BE_ENCODING
parser.raw_buffer_pos += 2
parser.offset += 2
} else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] {
parser.encoding = yaml_UTF8_ENCODING
parser.raw_buffer_pos += 3
parser.offset += 3
} else {
parser.encoding = yaml_UTF8_ENCODING
}
return true
} | 430,646 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: analyzer.go
path of file: ./repos/cockroach/build/bazelutil/staticcheckanalyzers/s1005
the code of the file until where you have to start completion: // Code generated by generate-staticcheck; DO NOT EDIT.
//go:build bazel
// +build bazel
package s1005
import (
util "github.com/cockroac
| func init() {
for _, analyzer := range simple.Analyzers {
if analyzer.Analyzer.Name == "S1005" {
Analyzer = analyzer.Analyzer
break
}
}
util.MungeAnalyzer(Analyzer)
} | 700,241 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: activityruns_server.go
path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/datafactory/armdatafactory/fake
the code of the file until where you have to start completion: //go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license informati
| func (a *ActivityRunsServerTransport) Do(req *http.Request) (*http.Response, error) {
rawMethod := req.Context().Value(runtime.CtxAPINameKey{})
method, ok := rawMethod.(string)
if !ok {
return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")}
}
var resp *http.Response
var err error
switch method {
case "ActivityRunsClient.QueryByPipelineRun":
resp, err = a.dispatchQueryByPipelineRun(req)
default:
err = fmt.Errorf("unhandled API %s", method)
}
if err != nil {
return nil, err
}
return resp, nil
} | 266,377 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: table.rs
path of file: ./repos/edma/tui/src/ui
the code of the file until where you have to start completion: use tui::widgets::TableState;
#[derive(Default, Clone)]
pub struct StatefulTable {
pub state: TableS
| pub fn previous(&mut self) {
let i = match self.state.selected() {
Some(i) => {
if i == 0 {
self.items.len().saturating_sub(1)
} else {
i.saturating_sub(1)
}
}
None => 0,
};
self.state.select(Some(i));
} | 480,159 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: fuzz.go
path of file: ./repos/caire/vendor/golang.org/x/image/tiff
the code of the file until where you have to start completion: // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build gofuzz
// +build gofuzz
package tiff
import "bytes"
func Fuzz(data []byte) int {
cfg, err := DecodeConf
| func Fuzz(data []byte) int {
cfg, err := DecodeConfig(bytes.NewReader(data))
if err != nil {
return 0
}
if cfg.Width*cfg.Height > 1e6 {
return 0
}
img, err := Decode(bytes.NewReader(data))
if err != nil {
return 0
}
var w bytes.Buffer
err = Encode(&w, img, nil)
if err != nil {
panic(err)
}
return 1
} | 389,944 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: users.rs
path of file: ./repos/labrinth/src/models/v3
the code of the file until where you have to start completion: use super::ids::Base62Id;
use crate::{auth:
| pub fn as_str(&self) -> &'static str {
match self {
Role::Developer => "developer",
Role::Moderator => "moderator",
Role::Admin => "admin",
}
} | 214,663 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: main.go
path of file: ./repos/google-cloud-go/internal/generated/snippets/compute/apiv1/RegionInstanceGroupsClient/ListInstances
the code of the file until where you have to start completion: // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
// [START compute_v1_generated_RegionInstanceGroups_ListInstances_sync]
package main
import (
"context"
co
| func main() {
ctx := context.Background()
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in:
// https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
c, err := compute.NewRegionInstanceGroupsRESTClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &computepb.ListInstancesRegionInstanceGroupsRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/cloud.google.com/go/compute/apiv1/computepb#ListInstancesRegionInstanceGroupsRequest.
}
it := c.ListInstances(ctx, req)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
} | 282,840 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: createscratchlayer.go
path of file: ./repos/moby/vendor/github.com/Microsoft/hcsshim/internal/wclayer
the code of the file until where you have to start completion: //go:build windows
package wclayer
import (
"context"
"strings"
"github.com/Microsoft/hcsshim/internal/hcserror"
"github.com/Microsoft/hcsshim/internal/oc"
"go.opencensus
| func CreateScratchLayer(ctx context.Context, path string, parentLayerPaths []string) (err error) {
title := "hcsshim::CreateScratchLayer"
ctx, span := oc.StartSpan(ctx, title)
defer span.End()
defer func() { oc.SetSpanStatus(span, err) }()
span.AddAttributes(
trace.StringAttribute("path", path),
trace.StringAttribute("parentLayerPaths", strings.Join(parentLayerPaths, ", ")))
// Generate layer descriptors
layers, err := layerPathsToDescriptors(ctx, parentLayerPaths)
if err != nil {
return err
}
err = createSandboxLayer(&stdDriverInfo, path, 0, layers)
if err != nil {
return hcserror.New(err, title, "")
}
return nil
} | 660,051 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: auxiliary.go
path of file: ./repos/google-cloud-go/ai/generativelanguage/apiv1beta
the code of the file until where you have to start completion: // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Ver
| func (it *CorpusIterator) Next() (*generativelanguagepb.Corpus, error) {
var item *generativelanguagepb.Corpus
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
} | 285,212 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: nopbreaker_test.go
path of file: ./repos/go-zero/core/breaker
the code of the file until where you have to start completion: package breaker
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNopBreaker(t *testing.T) {
b := NopBreaker()
assert.Equal(t, nopBreakerName, b.Name())
p, err := b.Allow()
assert.Nil(t, err)
p.Accept()
for i := 0; i < 1000; i++ {
p, err := b.Allow()
assert.Nil(t, err)
p.Reject("any")
}
assert.Nil(t, b.Do(func() error {
return nil
}))
assert.Nil(t, b.DoWithAcceptable(func() error {
return nil
}, defaultAcceptable))
| func TestNopBreaker(t *testing.T) {
b := NopBreaker()
assert.Equal(t, nopBreakerName, b.Name())
p, err := b.Allow()
assert.Nil(t, err)
p.Accept()
for i := 0; i < 1000; i++ {
p, err := b.Allow()
assert.Nil(t, err)
p.Reject("any")
}
assert.Nil(t, b.Do(func() error {
return nil
}))
assert.Nil(t, b.DoWithAcceptable(func() error {
return nil
}, defaultAcceptable))
errDummy := errors.New("any")
assert.Equal(t, errDummy, b.DoWithFallback(func() error {
return errDummy
}, func(err error) error {
return nil
}))
assert.Equal(t, errDummy, b.DoWithFallbackAcceptable(func() error {
return errDummy
}, func(err error) error {
return nil
}, defaultAcceptable))
} | 258,166 |
You are an expert in writing code in many different languages. Your goal is 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_UntagResource.go
path of file: ./repos/aws-sdk-go-v2/service/rolesanywhere
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package rolesanywhere
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/smithy-go/midd
| func (c *Client) UntagResource(ctx context.Context, params *UntagResourceInput, optFns ...func(*Options)) (*UntagResourceOutput, error) {
if params == nil {
params = &UntagResourceInput{}
}
result, metadata, err := c.invokeOperation(ctx, "UntagResource", params, optFns, c.addOperationUntagResourceMiddlewares)
if err != nil {
return nil, err
}
out := result.(*UntagResourceOutput)
out.ResultMetadata = metadata
return out, nil
} | 216,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: stk.rb
path of file: ./repos/mpesa/lib/mpesa/resources
the code of the file until where you have to start completion: # frozen_stri
| def body
{
'BusinessShortCode': shortcode,
'Password': password,
'Timestamp': timestamp,
'TransactionType': 'CustomerPayBillOnline',
'Amount': args[:amount],
'PartyA': format_phone(args[:phone]),
'PartyB': shortcode,
'PhoneNumber': format_phone(args[:phone]),
'CallBackURL': args[:callback_url],
'AccountReference': args[:reference],
'TransactionDesc': args[:trans_desc]
}
end | 248,794 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: _access_denied_exception.rs
path of file: ./repos/aws-sdk-rust/sdk/elasticsearch/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>An error occurred because user does not have permissions to access the resource. Returns HTTP status code 403.</p>
#[non
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
::std::write!(f, "AccessDeniedException")?;
if let ::std::option::Option::Some(inner_1) = &self.message {
{
::std::write!(f, ": {}", inner_1)?;
}
}
Ok(())
} | 768,017 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: apply_derivative_boost.m
path of file: ./repos/CanlabCore/CanlabCore/Image_computation_tools
the code of the file until where you have to start completion: function apply_derivative_boost(imgtype, varargin)
% Allows for recalculation of amplitude images from the fitted responses
% for each trial type. Necessary for calculating group statistics when
% using multiple basis functions
%
% :Usage:
% ::
%
% function apply_derivative_boost(varargin)
%
% :NOTES:
% DB estimation only works for 2 specific basis sets:
% timeonly, with 2 parameters (canonical + time derivative)
% timedispersion,' with 3 parameters (canonical hrf + temporal and spatial dispersion)
%
% This function loads the SPM.mat file in the current directory and uses
% the basis set specified in the loaded SPM structure.
%
% : Required Inputs:
% indicate whether images are'.img' or '.nii'
%
% :Optional Inputs:
%
% **'amplitudes'**
% will only create amping images (combination of betas
% across basis functions)
%
% **'contrasts'**
% assumes that amping images are already created; will only
% create contrast images
%
% **'all'**
% will run both the amplitudes and contrasts sections
%
% In addition, 'amplitudes' now has two separate parts:
% - The first uses Vince Calhoun's derivative boost (Calhoun, 2004) to
% estimate
| function
% boost = @(b) sign(b(1)) .* sqrt(sum(b .^ 2));
docontrasts = 0;
doamps = 0;
nodb = 0;
nohtw = 0;
condition_numbers = [];
do_downsample = []; % downsample; default = 1 sec if units are seconds (1/dt)
for i = 1:length(varargin)
if ischar(varargin{i})
switch varargin{i}
% reserved keywords
case 'all', docontrasts = 1; doamps = 1;
case 'amplitudes', doamps = 1;
case 'contrasts', docontrasts = 1;
case 'nodb', nodb = 1; % skip DB estimation
case 'nohtw', nohtw = 1; % skip HTW estimation
case 'startend', startend = varargin{i + 1}; % starting and ending values in seconds for amplitude estimation window (for HTW estimation only).
case 'condition_numbers', condition_numbers = varargin{i + 1};
case 'nodownsample', do_downsample = 0;
case 'downsample', do_downsample = varargin{i + 1};
otherwise, warning(['Unknown input string option:' varargin{i}]);
end
end
end
if isempty(do_downsample)
% default downsampling
do_downsample = round(1 ./ SPM.xBF.dt);
end | 561,476 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: component.rb
path of file: ./repos/dd-trace-rb/lib/datadog/core/remote
the code of the file until where you have to start completion: # frozen_string_literal: true
require_
| def wait_once(timeout = nil)
# TTAS (Test and Test-And-Set) optimisation
# Since @once only ever goes from false to true, this is semantically valid
return :pass if @once
begin
@mutex.lock
return :pass if @once
timeout ||= @timeout
# - starting with Ruby 3.2, ConditionVariable#wait returns nil on
# timeout and an integer otherwise
# - before Ruby 3.2, ConditionVariable returns itself
# so we have to rely on @once having been set
if RUBY_VERSION >= '3.2'
lifted = @condition.wait(@mutex, timeout)
else
@condition.wait(@mutex, timeout)
lifted = @once
end | 209,273 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: mod.rs
path of file: ./repos/async-graphql/src/dataloader
the code of the file until where you have to start completion: //! Batch loading support, used to solve N+1 problem.
//!
//! # Examples
//!
//! ```rust
//! use async_graphql::*;
//! use async_graphql::dataloader::*;
//! use std::collections::{HashSet, HashMap};
//! use std::convert::Infallible;
//! use async_graphql::dataloader::Loader;
//!
//! /// This loader simply
| async fn test_dataloader_with_cache_hashmap_fnv() {
let loader = DataLoader::with_cache(
MyLoader,
tokio::spawn,
HashMapCache::<FnvBuildHasher>::new(),
);
loader.feed_many(vec![(1, 10), (2, 20), (3, 30)]).await;
// All from the cache
assert_eq!(
loader.load_many(vec![1, 2, 3]).await.unwrap(),
vec![(1, 10), (2, 20), (3, 30)].into_iter().collect()
);
// Part from the cache
assert_eq!(
loader.load_many(vec![1, 5, 6]).await.unwrap(),
vec![(1, 10), (5, 5), (6, 6)].into_iter().collect()
);
// All from the loader
assert_eq!(
loader.load_many(vec![8, 9, 10]).await.unwrap(),
vec![(8, 8), (9, 9), (10, 10)].into_iter().collect()
);
// Clear cache
loader.clear::<i32>();
assert_eq!(
loader.load_many(vec![1, 2, 3]).await.unwrap(),
vec![(1, 1), (2, 2), (3, 3)].into_iter().collect()
);
} | 619,330 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: processor_split.go
path of file: ./repos/benthos/internal/impl/pure
the code of the file until where you have to start completion: package pure
import (
"context"
"github.com/benthosdev/benthos/v4/internal/component/interop"
"github.com/benthosdev/benthos/v4/internal/component/processor"
"github.com/benthosdev/benthos/v4/internal/log"
"github.com/benthosdev/benthos/v4/internal/message"
"github.com/benthosdev/benthos/v4/public/service"
)
const (
splitPFieldSize = "size"
splitPFieldByteSize = "byte_size"
)
func init() {
err := service.RegisterBatchProcessor(
"split", service.NewConfigSpec().
Categories("Utility").
Stable().
Summary(`Breaks message batches (synonymous with multiple part messages) into smaller batches. The size of the resulting batches are determined either by a discrete size or, if the field `+"`byte_size`"+` is non-zero, then by total size in bytes (which ever limit is reached first).`).
Description(`
This processor is for breaking batches down into smaller ones. In order to break a single message out into multiple messages use the `+"[`unarchive` processor](/docs/components/processors/unarchive)"+
| func init() {
err := service.RegisterBatchProcessor(
"split", service.NewConfigSpec().
Categories("Utility").
Stable().
Summary(`Breaks message batches (synonymous with multiple part messages) into smaller batches. The size of the resulting batches are determined either by a discrete size or, if the field `+"`byte_size`"+` is non-zero, then by total size in bytes (which ever limit is reached first).`).
Description(`
This processor is for breaking batches down into smaller ones. In order to break a single message out into multiple messages use the `+"[`unarchive` processor](/docs/components/processors/unarchive)"+`.
If there is a remainder of messages after splitting a batch the remainder is also sent as a single batch. For example, if your target size was 10, and the processor received a batch of 95 message parts, the result would be 9 batches of 10 messages followed by a batch of 5 messages.`).
Fields(
service.NewIntField(splitPFieldSize).
Description("The target number of messages.").
Default(1),
service.NewIntField(splitPFieldByteSize).
Description("An optional target of total message bytes.").
Default(0),
),
func(conf *service.ParsedConfig, res *service.Resources) (service.BatchProcessor, error) {
mgr := interop.UnwrapManagement(res)
s := &splitProc{log: mgr.Logger()}
var err error
if s.size, err = conf.FieldInt(splitPFieldSize); err != nil {
return nil, err
}
if s.byteSize, err = conf.FieldInt(splitPFieldByteSize); err != nil {
return nil, err
}
return interop.NewUnwrapInternalBatchProcessor(processor.NewAutoObservedBatchedProcessor("split", s, mgr)), nil
})
if err != nil {
panic(err)
}
} | 251,645 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: icatb_make_composite.m
path of file: ./repos/bspm/thirdparty/MIALAB/GroupICATv4.0a/icatb/toolbox/eegiftv1.0c/icatb_eeg_files
the code of the file until where you have to start completion: function [funcImg, minICAIm, maxICAIm, minInterval, maxInterval] = icatb_make_composite(anat, funcData, ...
imageValues, anatomicalView, structDIM, VOX)
% creates a composite image from structural and functional image
%
% Input:
% 1. anat - anatomical image
% 2. funcData
% 3. imageValues - 1 means positive and negative, 2 means positive, 3 means
% Absoulte, 4 means Negative
% 4. anatomicalView - Anatomical view
%
| function [funcImg, minICAIm, maxICAIm, minInterval, maxInterval] = icatb_make_composite(anat, funcData, ...
imageValues, anatomicalView, structDIM, VOX)
% creates a composite image from structural and functional image
%
% Input:
% 1. anat - anatomical image
% 2. funcData
% 3. imageValues - 1 means positive and negative, 2 means positive, 3 means
% Absoulte, 4 means Negative
% 4. anatomicalView - Anatomical view
%
% Output:
% 1. funcImg - functional image converted to montage
% 2. minICAIm - Minimum value of functional image
% 3. maxICAIm - Max value of functional image
% 4. minInterval - Minimum interval
% 5. maxInterval - Max interval
% Initialise all vars
maxICAIm = zeros(1, size(funcData, 1));
minICAIm = zeros(1, size(funcData, 1));
%--get image in correct plane
if icatb_findstr(lower(anatomicalView), 'sagittal')
% sagittal plane
permuteOrder = [2 3 1];
elseif icatb_findstr(lower(anatomicalView), 'coronal')
% coronal plane
permuteOrder = [1 3 2];
else
permuteOrder = [1 2 3];
end | 515,796 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: api_op_ModifyRedshiftIdcApplication.go
path of file: ./repos/aws-sdk-go-v2/service/redshift
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package redshift
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/service/redshift/types"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Changes an existing Amazon Redshift IAM Identity Center application.
func (c *Client) ModifyRe
| func (c *Client) ModifyRedshiftIdcApplication(ctx context.Context, params *ModifyRedshiftIdcApplicationInput, optFns ...func(*Options)) (*ModifyRedshiftIdcApplicationOutput, error) {
if params == nil {
params = &ModifyRedshiftIdcApplicationInput{}
}
result, metadata, err := c.invokeOperation(ctx, "ModifyRedshiftIdcApplication", params, optFns, c.addOperationModifyRedshiftIdcApplicationMiddlewares)
if err != nil {
return nil, err
}
out := result.(*ModifyRedshiftIdcApplicationOutput)
out.ResultMetadata = metadata
return out, nil
} | 229,831 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: profiles.go
path of file: ./repos/sliver/server/generate
the code of the file until where you have to start completion: package generate
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as publis
| func SaveImplantProfile(pbProfile *clientpb.ImplantProfile) (*clientpb.ImplantProfile, error) {
dbProfile, err := db.ImplantProfileByName(pbProfile.Name)
if err != nil && !errors.Is(err, db.ErrRecordNotFound) {
return nil, err
}
profile := models.ImplantProfileFromProtobuf(pbProfile)
dbSession := db.Session()
if errors.Is(err, db.ErrRecordNotFound) {
err = dbSession.Create(&models.ImplantProfile{
Name: profile.Name,
ImplantConfig: profile.ImplantConfig,
}).Error
dbProfile, err = db.ImplantProfileByName(profile.Name)
if err != nil {
return nil, err
}
} else {
configID, _ := uuid.FromString(dbProfile.Config.ID)
profile.ImplantConfig.ID = configID
profileID, _ := uuid.FromString(dbProfile.ID)
profile.ImplantConfig.ImplantProfileID = profileID
for _, c2 := range dbProfile.Config.C2 {
id, _ := uuid.FromString(c2.ID)
err := db.DeleteC2(id)
if err != nil {
return nil, err
}
}
err := dbSession.Save(profile.ImplantConfig).Error
if err != nil {
return nil, err
}
dbProfile = profile.ToProtobuf()
}
return dbProfile, err
} | 451,796 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: fake_certificatesigningrequest_expansion.go
path of file: ./repos/hubble-ui/backend/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/fake
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.apach
| func (c *FakeCertificateSigningRequests) UpdateApproval(ctx context.Context, certificateSigningRequest *certificates.CertificateSigningRequest, opts metav1.UpdateOptions) (result *certificates.CertificateSigningRequest, err error) {
obj, err := c.Fake.
Invokes(core.NewRootUpdateSubresourceAction(certificatesigningrequestsResource, "approval", certificateSigningRequest), &certificates.CertificateSigningRequest{})
if obj == nil {
return nil, err
}
return obj.(*certificates.CertificateSigningRequest), err
} | 380,402 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: utf16.go
path of file: ./repos/goscript/std/unicode/utf16
the code of the file until where you have to start completion: // Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENS
| func Decode(s []uint16) []rune {
a := make([]rune, len(s))
n := 0
for i := 0; i < len(s); i++ {
switch r := s[i]; {
case r < surr1, surr3 <= r:
// normal rune
a[n] = rune(r)
case surr1 <= r && r < surr2 && i+1 < len(s) &&
surr2 <= s[i+1] && s[i+1] < surr3:
// valid surrogate sequence
a[n] = DecodeRune(rune(r), rune(s[i+1]))
i++
default:
// invalid surrogate sequence
a[n] = replacementChar
}
n++
}
return a[:n]
} | 442,055 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: unsigned.rs
path of file: ./repos/polars/crates/polars-compute/src/arithmetic
the code of the file until where you have to start completion: use arrow::array::{PrimitiveArray as PArr, StaticArray};
use arrow::compute::utils::{combine_validities_and, combine_validities_and3};
use strength_reduce::*;
use super::PrimitiveAr
| fn prim_wrapping_mul_scalar(lhs: PArr<$T>, rhs: $T) -> PArr<$T> {
if rhs == 0 {
lhs.fill_with(0)
} else if rhs == 1 {
lhs
} else if rhs & (rhs - 1) == 0 {
// Power of two.
let shift = rhs.trailing_zeros();
prim_unary_values(lhs, |x| x << shift)
} else {
prim_unary_values(lhs, |x| x.wrapping_mul(rhs))
}
} | 382,670 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: vncinject.rb
path of file: ./repos/metasploit-framework/modules/payloads/stages/windows
the code of the file until where you have to start completion: ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
# Copyright (c) 2008 Stephen Fewer of Harmony Security (w
| def initialize(info = {})
super(update_info(info,
'Name' => 'VNC Server (Reflective Injection)',
'Description' => 'Inject a VNC Dll via a reflective loader (staged)',
'Author' => [ 'sf' ],
'Session' => Msf::Sessions::VncInject,
'Convention' => 'sockedi -http -https'))
end | 739,946 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: task_executor_test.go
path of file: ./repos/tidb/pkg/disttask/framework/taskexecutor
the code of the file until where you have to start completion: // Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// 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 taskexecutor
import (
"context"
"testing"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/pkg/disttask/framework/mock"
mockexecute "github.com/pingcap/tidb/pkg/disttask/framework/mock/execute"
"github.com/pingcap/tidb/pkg/disttask/framework/proto"
"github.com/pingcap/tidb/pkg/disttask/framework/storage"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var (
unfinishedNormalSubtaskStates = []any{
proto.SubtaskStatePending, proto.SubtaskStateRunning,
}
)
func TestTaskExecutorRun(t *testing.T) {
var tp proto.TaskType = "test_task_executor_run"
var concurrency = 10
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSubtaskTable := mock.NewMockTaskTable(ctrl)
mockStepExecutor := mockexecute.NewMockStepExecutor(ctrl)
mockExtension := mock.NewMockExtension(ctrl)
mockExtension.EXPECT().IsRetryableError(gomock.Any()).Return(false).AnyTimes()
task1 := &proto.Task{TaskBase: proto.TaskBase{State: proto.TaskStateRunning, Step: proto.StepOne, Type: tp, ID: 1, Concurrency: concurrency}}
// mock for checkBalanceSubtask
mockSubtaskTable.EXPECT().GetSubtasksByExecIDAndStepAndStates(gomock.Any(), "id",
task1.ID, proto.StepOne, proto.SubtaskStateRunning).Return([]*proto.Subtask{{SubtaskBase: proto.SubtaskBase{ID: 1}}}, nil).AnyTimes()
// mock GetTaskByID at beginning of runStep
mockSubtaskTable.EXPECT().GetTaskByID(gomock.Any(), task1.ID).Return(task1, nil).AnyTimes()
// 1. no taskExecutor constructor
taskExecutorRegisterErr := errors.Errorf("constructor of taskExecutor for key not found")
mockExtension.EXPECT().GetStepExecutor(gomock.Any(), gomock.Any()).Return(nil, taskExecutorRegisterErr).Times(2)
taskExecutor := NewBaseTaskExecutor(ctx, "id", task1, mockSubtaskTable)
taskExecutor.Extension = mockExtension
err := taskExecutor.runStep(nil)
require.EqualError(t, err, taskExecutorRegisterErr.Error())
mockSubtaskTable.EXPECT().FailSubtask(taskExecutor.ctx, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
err = taskExecutor.RunStep(nil)
require.NoError(t, err)
require.True(t, ctrl.Satisfied())
// 2. init subtask exec env failed
mockExtension.EXPECT().GetStepExecutor(gomock.Any(), gomock.Any()).Return(mockStepExecutor, nil).AnyTimes
| func TestTaskExecutor(t *testing.T) {
var tp proto.TaskType = "test_task_executor"
var taskID int64 = 1
var concurrency = 10
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSubtaskTable := mock.NewMockTaskTable(ctrl)
mockStepExecutor := mockexecute.NewMockStepExecutor(ctrl)
mockExtension := mock.NewMockExtension(ctrl)
mockSubtaskTable.EXPECT().UpdateSubtaskStateAndError(gomock.Any(), "id", taskID, proto.SubtaskStateFailed, gomock.Any()).Return(nil)
mockExtension.EXPECT().GetStepExecutor(gomock.Any(), gomock.Any()).Return(mockStepExecutor, nil).AnyTimes()
mockExtension.EXPECT().IsRetryableError(gomock.Any()).Return(false).AnyTimes()
// mock for checkBalanceSubtask
mockSubtaskTable.EXPECT().GetSubtasksByExecIDAndStepAndStates(gomock.Any(), "id",
taskID, proto.StepOne, proto.SubtaskStateRunning).Return([]*proto.Subtask{{SubtaskBase: proto.SubtaskBase{ID: 1}}}, nil).AnyTimes()
task := &proto.Task{TaskBase: proto.TaskBase{Step: proto.StepOne, Type: tp, ID: taskID, Concurrency: concurrency}}
taskExecutor := NewBaseTaskExecutor(ctx, "id", task, mockSubtaskTable)
taskExecutor.Extension = mockExtension
// 1. run failed.
runSubtaskErr := errors.New("run subtask error")
mockStepExecutor.EXPECT().Init(gomock.Any()).Return(nil)
subtasks := []*proto.Subtask{
{SubtaskBase: proto.SubtaskBase{ID: 1, Type: tp, Step: proto.StepOne, State: proto.SubtaskStatePending, ExecID: "id"}},
}
mockSubtaskTable.EXPECT().GetTaskByID(gomock.Any(), task.ID).Return(task, nil)
mockSubtaskTable.EXPECT().GetFirstSubtaskInStates(gomock.Any(), "id", taskID, proto.StepOne,
unfinishedNormalSubtaskStates...).Return(subtasks[0], nil)
mockSubtaskTable.EXPECT().StartSubtask(gomock.Any(), taskID, "id").Return(nil)
mockStepExecutor.EXPECT().RunSubtask(gomock.Any(), gomock.Any()).Return(runSubtaskErr)
mockStepExecutor.EXPECT().Cleanup(gomock.Any()).Return(nil)
err := taskExecutor.runStep(nil)
require.EqualError(t, err, runSubtaskErr.Error())
require.True(t, ctrl.Satisfied())
// 2. run one subtask, then task moved to history(ErrTaskNotFound).
mockStepExecutor.EXPECT().Init(gomock.Any()).Return(nil)
mockSubtaskTable.EXPECT().GetTaskByID(gomock.Any(), task.ID).Return(task, nil)
mockSubtaskTable.EXPECT().GetFirstSubtaskInStates(gomock.Any(), "id", taskID, proto.StepOne,
unfinishedNormalSubtaskStates...).Return(subtasks[0], nil)
mockSubtaskTable.EXPECT().StartSubtask(gomock.Any(), taskID, "id").Return(nil)
mockStepExecutor.EXPECT().RunSubtask(gomock.Any(), gomock.Any()).Return(nil)
mockStepExecutor.EXPECT().OnFinished(gomock.Any(), gomock.Any()).Return(nil)
mockSubtaskTable.EXPECT().FinishSubtask(gomock.Any(), "id", int64(1), gomock.Any()).Return(nil)
mockSubtaskTable.EXPECT().GetFirstSubtaskInStates(gomock.Any(), "id", taskID, proto.StepOne,
unfinishedNormalSubtaskStates...).Return(nil, nil)
mockStepExecutor.EXPECT().Cleanup(gomock.Any()).Return(nil)
err = taskExecutor.runStep(nil)
require.NoError(t, err)
require.True(t, ctrl.Satisfied())
} | 580,438 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: 20231124084532_remove_security_orchestration_policy_configurations_bot_user_id_column.rb
path of file: ./repos/gitlabhq/db/post_migrate
the code of the file until where you have to start completion: # frozen_string_literal: true
class RemoveSecurityOrchestrationPolicyConfigurationsBotUs
| def down
add_column(TABLE, COLUMN, :integer) unless column_exists?(TABLE, COLUMN)
add_concurrent_foreign_key(TABLE, :users, column: COLUMN, on_delete: :nullify)
add_concurrent_index(TABLE, COLUMN,
where: "security_orchestration_policy_configurations.bot_user_id IS NOT NULL",
name: INDEX)
end | 295,640 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: netdevice.rs
path of file: ./repos/rustix/src/net
the code of the file until where you have to start completion: //! Low-level Linux network device access
//!
//! The methods in this module take a socket's file descriptor to communicate with
//! the kernel in their ioctl call:
//! - glibc uses an `AF_UNIX`, `AF_INET`, or `AF_INET6` socket.
//! The address family itself does not matter and glibc tries the next
| fn test_name_to_index() {
let fd = crate::net::socket_with(
AddressFamily::INET,
SocketType::DGRAM,
SocketFlags::CLOEXEC,
None,
)
.unwrap();
let loopback_index = std::fs::read_to_string("/sys/class/net/lo/ifindex")
.unwrap()
.as_str()
.split_at(1)
.0
.parse::<u32>()
.unwrap();
assert_eq!(Ok(loopback_index), name_to_index(fd, "lo"));
} | 462,657 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: object.rb
path of file: ./repos/hyperstack/ruby/hyper-component/lib/hyperstack/ext/component
the code of the file until where you have to start completion: class Object
# Lazy load HTML tag constants in the form DIV or A
# This is needed to allow for a tags to be used in expressions like
# render(DIV) do ...
# By la
| def const_missing(const_name)
# Opal uses const_missing to initially define things,
# so we always call the original, and respond to the exception
_reactrb_tag_original_const_missing(const_name)
rescue StandardError => e
Hyperstack::Internal::Component::Tags.html_tag_class_for(const_name) || raise(e)
end | 315,802 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: environment.rb
path of file: ./repos/gitlabhq/lib/gitlab
the code of the file until where you have to start completion: # frozen_string_literal: true
module Gitlab
module Environment
def self.hostname
@hostname ||= ENV['HOSTNAME'] || Socket.gethostname
end
# Check whether codebase is
| def self.static_verification?
static_verification = Gitlab::Utils.to_boolean(ENV['STATIC_VERIFICATION'], default: false)
env_production = ENV['RAILS_ENV'] == 'production'
warn '[WARNING] Static Verification bypass is enabled in Production.' if static_verification && env_production
static_verification
end | 296,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: suite.go
path of file: ./repos/harbor/src/testing
the code of the file until where you have to start completion: // Copyright Project Harbor 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 obtai
| func (suite *Suite) NextHandler(statusCode int, headers map[string]string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(statusCode)
for key, value := range headers {
w.Header().Set(key, value)
}
})
} | 551,321 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: dialog_import_validator.rb
path of file: ./repos/manageiq/app/models
the code of the file until where you have to start completion: class DialogImportValidator
class BlankFileError < StandardError; end
class ImportNonYamlError < StandardError; end
class InvalidDialogFieldTypeError < StandardErr
| def check_dialog_groups_for_validity(dialog_groups)
dialog_groups.each do |dialog_group|
raise ParsedNonDialogYamlError unless dialog_group["dialog_fields"]
check_dialog_fields_for_validity(dialog_group["dialog_fields"])
end
end | 22,359 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: wavMask.m
path of file: ./repos/CS_MoCo_LAB/reconstruction/matlab/CS_LAB_matlab/@Wavelet/private
the code of the file until where you have to start completion: function res = wavMask(imSize,scale)
| function res = wavMask(imSize,scale)
% function scales the value of each wavelet scale such they display nicely.
sx = imSize(1);
sy = imSize(2);
res = zeros(imSize)+1;
NM = round((log2(imSize)));
for n = 1:min(NM)-scale+1
res(1:round(2^(NM(1)-n)),1:round(2^(NM(2)-n))) = res(1:round(2^(NM(1)-n)),1:round(2^(NM(2)-n)))/2;
end | 61,167 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: cat_vol_pbt.m
path of file: ./repos/cat12
the code of the file until where you have to start completion: function [Ygmt,Ypp,Ymf,Ywmd,Ycsfdc] = cat_vol_pbt(Ymf,opt)
% ______________________________________________________________________
%
% Cortical thickness and surface position estimation.
%
% [Ygmt,Ypp,Ywmd,Ycsfd] = cat_vol_pbt(Ymf,opt)
| function [Ygmt,Ypp,Ymf,Ywmd,Ycsfdc] = cat_vol_pbt(Ymf,opt)
% ______________________________________________________________________
%
% Cortical thickness and surface position estimation.
%
% [Ygmt,Ypp,Ywmd,Ycsfd] = cat_vol_pbt(Ymf,opt)
%
% Ygmt: GM thickness map
% Ypp: percentage position map
% Ywmd: WM distance map
% Ycsfd: CSF distance map
%
% Ymf: tissue segment image or better the noise, bias, and
% intensity corrected
%
% opt.resV voxel resolution (only isotropic)
% opt.method choose of method {'pbt2x','pbt2'} with default=pbt2x as
% the method that is described in the paper.
% opt.pbtlas GM intensity correction to reduce myelination effects
% (added 201908)
% ______________________________________________________________________
%
% Dahnke, R; Yotter R; Gaser C.
% Cortical thickness and central surface estimation.
% NeuroImage 65 (2013) 226-248.
% ______________________________________________________________________
%
% Christian Gaser, Robert Dahnke
% Structural Brain Mapping Group (https://neuro-jena.github.io)
% Departments of Neurology and Psychiatry
% Jena University Hospital
% ______________________________________________________________________
% $Id$
% default variables and check/set function
if ~exist('opt','var'), opt=struct(); end | 527,771 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: zz_generated_service_account_controller.go
path of file: ./repos/rancher/pkg/generated/norman/core/v1
the code of the file until where you have to start completion: package v1
import (
"context"
"time"
"github.com/rancher/norman/controller"
"github.com/rancher/norman/objectclient"
"github.com/rancher/norman/resource"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8
| func (s *serviceAccountClient) Controller() ServiceAccountController {
genericController := controller.NewGenericController(s.ns, ServiceAccountGroupVersionKind.Kind+"Controller",
s.client.controllerFactory.ForResourceKind(ServiceAccountGroupVersionResource, ServiceAccountGroupVersionKind.Kind, true))
return &serviceAccountController{
ns: s.ns,
GenericController: genericController,
}
} | 680,175 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: img_uri.rb
path of file: ./repos/jekyll_picture_tag/lib/jekyll_picture_tag/images
the code of the file until where you have to start completion: require 'addressable'
module PictureTag
# Represents a link to an image. We use the File library rat
| def domain
if PictureTag.cdn?
PictureTag.cdn_url
elsif PictureTag.relative_url
''
else
PictureTag.config['url'] || ''
end | 74,301 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: zsyscall_darwin_amd64.go
path of file: ./repos/sliver/vendor/golang.org/x/sys/unix
the code of the file until where you have to start completion: // go run mksyscall.go -tags darwin,amd64 syscall_bsd.
| func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
} | 455,158 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: visitor_params.go
path of file: ./repos/erda/pkg/parser/pipelineyml
the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/l
| func (v *ParamsVisitor) Visit(s *Spec) {
// 运行时输入参数转化为map
var runParamsMap = make(map[string]interface{})
for _, v := range v.RunPipelineParams {
runParamsMap[v.Name] = v.Value
}
replaced := ReplacePipelineParams(string(v.Data), runParamsMap)
if err := yaml.Unmarshal([]byte(replaced), s); err != nil {
s.appendError(fmt.Errorf("failed to unmarshal to spec after replaced params, err: %v", err))
}
} | 713,523 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: interpolation_spec.rb
path of file: ./repos/puppet/spec/unit/pops/lookup
the code of the file until where you have to start completion: require 'spec_helper'
require 'puppet'
module Puppet::Pops
describe 'Puppet::Pops::Lookup::Interpolation' do
include Lookup::Su
| def lookup(name, lookup_invocation, merge)
track(name)
segments = split_key(name)
root_key = segments.shift
found = @data[root_key]
found = sub_lookup(name, lookup_invocation, segments, found) unless segments.empty?
@interpolator.interpolate(found, lookup_invocation, true)
end | 600,508 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: mod.rs
path of file: ./repos/parity-ethereum/json/src/test_helpers/blockchain
the code of the file until where you have to start completion: // Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of Parity
| pub fn genesis(&self) -> Genesis {
Genesis {
seal: Seal::Ethereum(Ethereum {
nonce: self.genesis_block.nonce.clone(),
mix_hash: self.genesis_block.mix_hash.clone(),
}),
difficulty: self.genesis_block.difficulty,
author: Some(self.genesis_block.author.clone()),
timestamp: Some(self.genesis_block.timestamp),
parent_hash: Some(self.genesis_block.parent_hash.clone()),
gas_limit: self.genesis_block.gas_limit,
transactions_root: Some(self.genesis_block.transactions_root.clone()),
receipts_root: Some(self.genesis_block.receipts_root.clone()),
state_root: Some(self.genesis_block.state_root.clone()),
gas_used: Some(self.genesis_block.gas_used),
extra_data: Some(self.genesis_block.extra_data.clone()),
}
} | 73,693 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: test_rdoc_markup_attributes.rb
path of file: ./repos/jruby/test/mri/rdoc
the code of the file until where you have to start completion: # frozen_string_literal: true
require_relative 'helper'
class TestRDocMarku
| def test_each_name_of
@as.bitmap_for 'two'
@as.bitmap_for 'three'
assert_equal %w[], @as.each_name_of(0).to_a
assert_equal %w[], @as.each_name_of(1).to_a
assert_equal %w[two], @as.each_name_of(2).to_a
assert_equal %w[three], @as.each_name_of(4).to_a
assert_equal %w[two three], @as.each_name_of(6).to_a
end | 624,920 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: core.go
path of file: ./repos/gitness/git/hook
the code of the file until where you have to start completion: // Copyright 2023 Harness, 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 applica
| func handleServerHookOutput(out Output, err error) error {
if err != nil {
return fmt.Errorf("an error occurred when calling the server: %w", err)
}
// print messages before any error
if len(out.Messages) > 0 {
// add empty line before and after to make it easier readable
fmt.Println()
for _, msg := range out.Messages {
fmt.Println(msg)
}
fmt.Println()
}
if out.Error != nil {
return errors.New(*out.Error)
}
return nil
} | 321,913 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: listens.rb
path of file: ./repos/alonetone/app/controllers/concerns
the code of the file until where you have to start completion: module Listens
extend Activ
| def register_listen(asset)
unless is_a_bot? || ip_just_registered_this_listen?(asset)
asset.listens.create(
listener: current_user || nil,
track_owner: asset.user,
source: listen_referer,
user_agent: user_agent,
ip: request.remote_ip,
city: request.headers["HTTP_GEOIP_CITY"], # set by nginx geoip
country: request.headers["HTTP_GEOIP_COUNTRY_CODE"]
)
end | 591,933 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: delete_provisioned_concurrency_config.rs
path of file: ./repos/aws-sdk-rust/sdk/lambda/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 `DeleteProvisionedConcurrencyConfig`.
#[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)]
#[non_exhaustive]
pub struct DeleteProvisionedConcurrencyConfig;
impl DeleteProvisionedConcurrencyConfig {
/// Creates a new `DeleteProvisionedConcurrencyConfig`
pub fn new() -> Self {
Self
}
pub(crate) async fn orchestrate(
runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins,
| fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata {
match self {
Self::ResourceNotFoundException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner),
Self::TooManyRequestsException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner),
Self::ServiceException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner),
Self::InvalidParameterValueException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner),
Self::ResourceConflictException(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner),
Self::Unhandled(_inner) => &_inner.meta,
}
} | 764,887 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: ing.go
path of file: ./repos/popeye/internal/cache
the code of the file until where you have to start completion: // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Popeye
package cache
import (
"errors"
"sync"
"github.com/derailed/popeye/internal"
"github.com/derailed/popeye/internal/db"
netv1 "k8s.io/api/networking/v1"
)
// IngressKey tracks Ingress resource references
const IngressKey = "ing"
// Ingress represents Ingress cache.
type Ingress struct {
db *db.DB
}
//
| func (d *Ingress) IngressRefs(refs *sync.Map) error {
txn, it := d.db.MustITFor(internal.Glossary[internal.ING])
defer txn.Abort()
for o := it.Next(); o != nil; o = it.Next() {
ing, ok := o.(*netv1.Ingress)
if !ok {
return errors.New("expected ing")
}
for _, tls := range ing.Spec.TLS {
d.trackReference(refs, ResFqn(SecretKey, FQN(ing.Namespace, tls.SecretName)))
}
}
return nil
} | 668,559 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: perplexityai.rb
path of file: ./repos/boxcars/lib/boxcars/engine
the code of the file until where you have to start completion: # frozen_string_literal: true
# Boxcars is a framework for running a series of tools to get an a
| def client(prompt:, inputs: {}, **kwargs)
prompt = prompt.first if prompt.is_a?(Array)
params = prompt.as_messages(inputs).merge(default_params).merge(kwargs)
params[:model] ||= "llama-2-70b-chat"
if Boxcars.configuration.log_prompts
Boxcars.debug(params[:messages].last(2).map { |p| ">>>>>> Role: #{p[:role]} <<<<<<\n#{p[:content]}" }.join("\n"), :cyan)
end | 47,903 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: create_landing_zone.rs
path of file: ./repos/aws-sdk-rust/sdk/controltower/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 `CreateLandingZone`.
#[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)]
#[non_exhaustive]
pub struct CreateLandingZone;
impl CreateLandingZone {
/// Creates a new `CreateLandingZone`
pub fn new() -> Self {
Self
}
pub(crate) async fn orchestrate(
runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins,
input: crate::operation::create_landing_zone::CreateLandingZoneInput,
) -> ::std::result::Result<
crate::operation::create_landing_zone::CreateLandingZoneOutput,
::aws_smithy_runtime_api::client::result::SdkError<
crate::operation::create_landing_zone::CreateLandingZoneError,
::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
>,
> {
let map_err = |err: ::aws_smithy_runtime_api::client::result::SdkError<
::aws_smithy_runtime_api::client::interceptors::context::Error,
::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
>| {
err.map_service_error(|err| {
err.downcast
| fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> {
let mut cfg = ::aws_smithy_types::config_bag::Layer::new("CreateLandingZone");
cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new(
CreateLandingZoneRequestSerializer,
));
cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new(
CreateLandingZoneResponseDeserializer,
));
cfg.store_put(::aws_smithy_runtime_api::client::auth::AuthSchemeOptionResolverParams::new(
::aws_smithy_runtime_api::client::auth::static_resolver::StaticAuthSchemeOptionResolverParams::new(),
));
cfg.store_put(::aws_smithy_runtime_api::client::orchestrator::Metadata::new(
"CreateLandingZone",
"controltower",
));
let mut signing_options = ::aws_runtime::auth::SigningOptions::default();
signing_options.double_uri_encode = true;
signing_options.content_sha256_header = false;
signing_options.normalize_uri_path = true;
signing_options.payload_override = None;
cfg.store_put(::aws_runtime::auth::SigV4OperationSigningConfig {
signing_options,
..::std::default::Default::default()
});
::std::option::Option::Some(cfg.freeze())
} | 808,834 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: tests.rs
path of file: ./repos/phaser/phaser/vendor/aho-corasick/src/packed
the code of the file until where you have to start completion: use std::collections::HashMap;
use std::usize;
| // fn to_owned(&self) -> SearchTestOwned {
// SearchTestOwned {
// name: self.name.to_string(),
// patterns: self.patterns.iter().map(|s| s.to_string()).collect(),
// haystack: self.haystack.to_string(),
// matches: self.matches.iter().cloned().collect(),
// }
// } | 620,707 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: memconn_listener.go
path of file: ./repos/sliver/vendor/github.com/akutz/memconn
the code of the file until where you have to start completion: package memconn
import (
"context"
"errors"
"net"
"sync"
)
// Listener implements the net.Listener interface.
type Listener struct {
addr Addr
once sync.Once
rcvr chan *Conn
done chan struct{}
rmvd chan struct{}
}
func (l *Listener) dial(
ctx context.Context,
net
| func (l *Listener) AcceptMemConn() (*Conn, error) {
select {
case remoteConn, ok := <-l.rcvr:
if ok {
return remoteConn, nil
}
return nil, &net.OpError{
Addr: l.addr,
Source: l.addr,
Net: l.addr.Network(),
Err: errors.New("listener closed"),
}
case <-l.done:
return nil, &net.OpError{
Addr: l.addr,
Source: l.addr,
Net: l.addr.Network(),
Err: errors.New("listener closed"),
}
}
} | 452,715 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: reader.go
path of file: ./repos/kubernetes/vendor/go.etcd.io/etcd/pkg/v3/ioutil
the code of the file until where you have to start completion: // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License,
| func (r *limitedBufferReader) Read(p []byte) (n int, err error) {
np := p
if len(np) > r.n {
np = np[:r.n]
}
return r.r.Read(np)
} | 354,480 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: mock_test.go
path of file: ./repos/juju/apiserver/facades/controller/undertaker
the code of the file until where you have to start completion: // Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE fi
| func (m *mockSecrets) CleanupModel(cfg *provider.ModelBackendConfig) error {
if cfg.BackendType != "some-backend" {
return errors.New("unknown backend " + cfg.BackendType)
}
m.cleanedUUID = cfg.ModelUUID
return nil
} | 611,103 |
You are an expert in writing code in many different languages. Your goal is 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_helpers.go
path of file: ./repos/gocryptfs/internal/fusefrontend_reverse
the code of the file until where you have to start completion: package fusefrontend_reverse
import (
"context"
"log"
"path/filepath"
"syscall"
"golang.org/x/sys/unix"
"github.com/hanwen/go-fuse/v2/fs"
"github.com/hanwen/go-fuse/v2/fuse"
"github.com/rfjakob/gocryptfs/v2/internal/configfile"
"github.com/rfjakob/gocryptfs/v2/internal/pathiv"
"github.com/rfjakob/gocryptfs/v2/internal/syscallcompat"
)
con
| func (n *Node) prepareAtSyscall(child string) (d *dirfdPlus, errno syscall.Errno) {
cPath := n.Path()
if child != "" {
cPath = filepath.Join(cPath, child)
}
rn := n.rootNode()
dirfd, pPath, err := rn.openBackingDir(cPath)
if err != nil {
errno = fs.ToErrno(err)
}
d = &dirfdPlus{
dirfd: dirfd,
pPath: pPath,
pName: filepath.Base(pPath),
cPath: cPath,
cName: filepath.Base(cPath),
}
return
} | 167,363 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: market.rb
path of file: ./repos/cryptoexchange/lib/cryptoexchange/exchanges/bhex_futures/services
the code of the file until where you have to start completion: module Cryptoexchange::Exchanges
module BhexFutures
module Services
class Market < Cryptoexchange::Services::Market
class << self
def supports_individual_ticker_query?
false
end
end
def fetch
output = super(ticker_url)
adapt_all(output)
end
def ticker
| def adapt_all(output)
output.map do |ticker|
base, target = ticker["symbol"].split("-")
next if ticker["symbol"].include?("USDT") || ticker["symbol"].include?("PERP")
target = "USDT"
market_pair = Cryptoexchange::Models::MarketPair.new(
base: base,
target: target,
inst_id: ticker["symbol"],
contract_interval: "perpetual",
market: BhexFutures::Market::NAME
)
adapt(ticker, market_pair)
end.compact
end
def adapt(output, market_pair)
ticker = Cryptoexchange::Models::Ticker.new
ticker.base = market_pair.base
ticker.target = market_pair.target
ticker.market = BhexFutures::Market::NAME
ticker.contract_interval = market_pair.contract_interval
ticker.inst_id = market_pair.inst_id
ticker.last = NumericHelper.to_d(output['lastPrice'])
ticker.high = NumericHelper.to_d(output['highPrice'])
ticker.low = NumericHelper.to_d(output['lowPrice'])
ticker.volume = NumericHelper.flip_volume(NumericHelper.to_d(output['volume']), ticker.last)
ticker.timestamp = nil
ticker.payload = output
ticker
end
end | 643,661 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: validations_controller.rb
path of file: ./repos/script_core/spec/dummy/app/controllers/fields
the code of the file until where you have to start completion: # frozen_string_literal: true
class Fields::ValidationsController < Fields::ApplicationController
before_action :set_validations
def edit;
| def edit; end
def update
@validations.assign_attributes(validations_params)
if @validations.valid? && @field.save(validate: false)
redirect_to fields_url, notice: "Field was successfully updated."
else
render :edit
end
end | 578,306 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: divide.m
path of file: ./repos/imtsl/libs/tensor_toolbox_2.5/@sptensor
the code of the file until where you have to start completion: function Y = divide(X,K,epsilon)
%DIVIDE Divide an SPTENSOR by a nonnegative KTENSOR.
%
% Y = DIVIDE(X,K,EPSILON) divides the sparse tensor X by the
% nonnegative ktensor K. Avoids divide-by-zero errors by dividing
% by MIN(EPSILON,K-VALUE) at each nonzero of X.
%
| function Y = divide(X,K,epsilon)
%DIVIDE Divide an SPTENSOR by a nonnegative KTENSOR.
%
% Y = DIVIDE(X,K,EPSILON) divides the sparse tensor X by the
% nonnegative ktensor K. Avoids divide-by-zero errors by dividing
% by MIN(EPSILON,K-VALUE) at each nonzero of X.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.
% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2012) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt
% Assumes K is a nonnegative ktensor
Y = X;
subs = Y.subs;
vals = zeros(size(Y.vals));
R = numel(K.lambda);
N = ndims(Y);
for r = 1:R
tvals = ones(size(vals)) * K.lambda(r);
for n = 1:N
v = K{n}(:,r);
tvals = tvals .* v(subs(:,n));
end | 440,000 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: outputPower.m
path of file: ./repos/underwater-wireless-optical-communication/MATLAB
the code of the file until where you have to start completion: function outputPower = outputPower(type, params, angle)
if strcmp(type,'Lambertian')
params = params(1);
outputPower = (params+1)/2/pi*cos(angle).^(params+1);
elseif strcmp(type,'HG')
outputPower = 1/4/pi*(1 - params^2)/...
| function outputPower = outputPower(type, params, angle)
if strcmp(type,'Lambertian')
params = params(1);
outputPower = (params+1)/2/pi*cos(angle).^(params+1);
elseif strcmp(type,'HG')
outputPower = 1/4/pi*(1 - params^2)/...
(1 + params^2 - 2*params*cos(angle))^(3/2);
else
outputPower = 1/4/pi;
end | 68,462 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: spiffe.go
path of file: ./repos/plumber/vendor/google.golang.org/grpc/internal/credentials
the code of the file until where you have to start completion: /*
*
* Copyright 2020 gRPC 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 credentials defines APIs for parsing SPIFFE ID.
//
// All APIs in this package are experimental.
package credentials
import (
"crypto/tls"
"
| func SPIFFEIDFromCert(cert *x509.Certificate) *url.URL {
if cert == nil || cert.URIs == nil {
return nil
}
var spiffeID *url.URL
for _, uri := range cert.URIs {
if uri == nil || uri.Scheme != "spiffe" || uri.Opaque != "" || (uri.User != nil && uri.User.Username() != "") {
continue
}
// From this point, we assume the uri is intended for a SPIFFE ID.
if len(uri.String()) > 2048 {
logger.Warning("invalid SPIFFE ID: total ID length larger than 2048 bytes")
return nil
}
if len(uri.Host) == 0 || len(uri.Path) == 0 {
logger.Warning("invalid SPIFFE ID: domain or workload ID is empty")
return nil
}
if len(uri.Host) > 255 {
logger.Warning("invalid SPIFFE ID: domain length larger than 255 characters")
return nil
}
// A valid SPIFFE certificate can only have exactly one URI SAN field.
if len(cert.URIs) > 1 {
logger.Warning("invalid SPIFFE ID: multiple URI SANs")
return nil
}
spiffeID = uri
}
return spiffeID
} | 458,656 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: epall.go
path of file: ./repos/rclone/backend/union/policy
the code of the file until where you have to start completion: package policy
import (
"context"
"path"
"sync"
"github.com/rclone/rclone/backend/union/upstream"
"git
| func (p *EpAll) Create(ctx context.Context, upstreams []*upstream.Fs, path string) ([]*upstream.Fs, error) {
if len(upstreams) == 0 {
return nil, fs.ErrorObjectNotFound
}
upstreams = filterNC(upstreams)
if len(upstreams) == 0 {
return nil, fs.ErrorPermissionDenied
}
upstreams, err := p.epall(ctx, upstreams, path+"/..")
return upstreams, err
} | 47,227 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: run_start_message.rb
path of file: ./repos/chef/lib/chef/data_collector
the code of the file until where you have to start completion: #
# Copyright:: Copyright (c) Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the
| def construct_message(data_collector)
run_status = data_collector.run_status
node = data_collector.node
{
"chef_server_fqdn" => URI(Chef::Config[:chef_server_url]).host,
"entity_uuid" => Chef::Config[:chef_guid],
"id" => run_status&.run_id,
"message_version" => "1.0.0",
"message_type" => "run_start",
"node_name" => node&.name || data_collector.node_name,
"organization_name" => organization,
"run_id" => run_status&.run_id,
"source" => solo_run? ? "chef_solo" : "chef_client",
"start_time" => run_status&.start_time&.utc&.iso8601,
}
end | 582,610 |
Subsets and Splits