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: tx.rs path of file: ./repos/zenoh/io/zenoh-transport/src/multicast the code of the file until where you have to start completion: // // Copyright (c) 2023 ZettaScale Technology // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 // which is available at https://www.apache.org/licenses/LICENSE-2.0. // // SPDX-License-Identifier: EPL-2.0 OR
pub(super) fn schedule(&self, mut msg: NetworkMessage) -> bool { #[cfg(feature = "shared-memory")] { let res = if self.manager.config.multicast.is_shm { crate::shm::map_zmsg_to_shminfo(&mut msg) } else { crate::shm::map_zmsg_to_shmbuf(&mut msg, &self.manager.state.multicast.shm.reader) }; if let Err(e) = res { log::trace!("Failed SHM conversion: {}", e); return false; } } let res = self.schedule_on_link(msg); #[cfg(feature = "stats")] if res { self.stats.inc_tx_n_msgs(1); } else { self.stats.inc_tx_n_dropped(1); } res }
170,997
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _list_studio_session_mappings_output.rs path of file: ./repos/aws-sdk-rust/sdk/emr/src/operation/list_studio_session_mappings the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // d
pub fn build(self) -> crate::operation::list_studio_session_mappings::ListStudioSessionMappingsOutput { crate::operation::list_studio_session_mappings::ListStudioSessionMappingsOutput { session_mappings: self.session_mappings, marker: self.marker, _request_id: self._request_id, } }
756,049
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: weird_type.rs path of file: ./repos/simd-json/tests the code of the file until where you have to start completion: #![cfg(feature = "serde")] use serde::{Deserialize, Serialize}; mod field_serde { use serde::{ de::{Deserializer, Error as DeError, Visitor}, ser::Serializer, };
fn test_simd_json() { unsafe { assert_eq!( MISSING_EXPECTED, simd_json::from_str(&mut MISSING_INPUT.to_owned()).unwrap() ); assert_eq!( PRESENT_EXPECTED, simd_json::from_str(&mut PRESENT_INPUT.to_owned()).unwrap() ); } }
155,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: spm_DEM_F.m path of file: ./repos/malini/Codes/deconvolution - model/spm8 the code of the file until where you have to start completion: function [F,p] = spm_DEM_F(DEM,ip) % Free-energy as a function of conditional parameters % [F,P1,P2] = spm_DEM_F(DEM)) % % DEM - hierarchical model % % F(i) - free-energy at <q(P(ip))> = p(i) % % where p(i) is the ip-th free-parameter. This is a bound on % the log-likehood (log-evidence) conditioned on the expeceted parameters %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Karl Friston % $Id: spm_DEM_F.m 4146 2010-12-23 21:01:39Z karl $ % Find paramter ranges (using prior covariance) %-------------------------------------------------------------------------- pE = spm_vec(DEM.M(1).pE); p = linspace(-6,6,16); dp = sqrt(DEM.M(1).pC(ip,ip))*p; p = dp + pE(ip); % get F %========================================================================== DEM.M(1).E.nE = 1; DEM.M(1).E.nN = 1; for i = 1:length(p)
function [F,p] = spm_DEM_F(DEM,ip) % Free-energy as a function of conditional parameters % [F,P1,P2] = spm_DEM_F(DEM)) % % DEM - hierarchical model % % F(i) - free-energy at <q(P(ip))> = p(i) % % where p(i) is the ip-th free-parameter. This is a bound on % the log-likehood (log-evidence) conditioned on the expeceted parameters %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Karl Friston % $Id: spm_DEM_F.m 4146 2010-12-23 21:01:39Z karl $ % Find paramter ranges (using prior covariance) %-------------------------------------------------------------------------- pE = spm_vec(DEM.M(1).pE); p = linspace(-6,6,16); dp = sqrt(DEM.M(1).pC(ip,ip))*p; p = dp + pE(ip); % get F %========================================================================== DEM.M(1).E.nE = 1; DEM.M(1).E.nN = 1; for i = 1:length(p) % adjust paramter (through prio expecatation) %---------------------------------------------------------------------- P = pE; P(ip) = p(i); DEM.M(1).P = spm_unvec(P,DEM.M(1).pE); % comute free-energy %---------------------------------------------------------------------- DEM = spm_DEM(DEM); F(i) = DEM.F(end
386,295
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: lib.rs path of file: ./repos/tarpaulin/tests/data/simple_project/src the code of the file until where you have to start completion: pub mod unused; pub fn branch_test_one(x: i32) -> i32
pub fn branch_test_one(x: i32) -> i32 { if x > 5 { 10 } else { 5 } }
369,660
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: epoch.rs path of file: ./repos/axos/crates/primitives/src the code of the file until where you have to start completion: //! L1 Epoch Block Info use crate::attributes::AttributesDepositedCall; use allo
pub fn new(number: u64, hash: B256, timestamp: u64) -> Self { Self { number, hash, timestamp, } }
524,805
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _voice_connector.rs path of file: ./repos/aws-sdk-rust/sdk/chimesdkvoice/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>The Amazon Chime SDK Voice Connector configuration, including outbound host name and encryption settings.
pub fn build(self) -> crate::types::VoiceConnector { crate::types::VoiceConnector { voice_connector_id: self.voice_connector_id, aws_region: self.aws_region, name: self.name, outbound_host_name: self.outbound_host_name, require_encryption: self.require_encryption, created_timestamp: self.created_timestamp, updated_timestamp: self.updated_timestamp, voice_connector_arn: self.voice_connector_arn, } }
815,841
You are an expert in writing code in many different languages. Your goal is 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_assessment_report_input.rs path of file: ./repos/aws-sdk-rust/sdk/auditmanager/src/operation/create_assessment_report the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp:
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { let mut formatter = f.debug_struct("CreateAssessmentReportInput"); formatter.field("name", &self.name); formatter.field("description", &"*** Sensitive Data Redacted ***"); formatter.field("assessment_id", &self.assessment_id); formatter.field("query_statement", &self.query_statement); formatter.finish() }
778,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: helpers_test.go path of file: ./repos/kubernetes/staging/src/k8s.io/kubectl/pkg/cmd/util the code of the file until where you have to start completion: /* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package util import ( goerrors "errors" "fmt" "net/http" "os" "strings" "syscall" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/
func TestMerge(t *testing.T) { tests := []struct { obj runtime.Object fragment string expected runtime.Object expectErr bool }{ { obj: &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", }, }, fragment: fmt.Sprintf(`{ "apiVersion": "%s" }`, "v1"), expected: &corev1.Pod{ TypeMeta: metav1.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: "foo", }, Spec: corev1.PodSpec{}, }, }, { obj: &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", }, }, fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "volumes": [ {"name": "v1"}, {"name": "v2"} ] } }`, "v1"), expected: &corev1.Pod{ TypeMeta: metav1.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: "foo", }, Spec: corev1.PodSpec{ Volumes: []corev1.Volume{ { Name: "v1", }, { Name: "v2", }, }, }, }, }, { obj: &corev1.Pod{}, fragment: "invalid json", expected: &corev1.Pod{}, expectErr: true, }, { obj: &corev1.Service{}, fragment: `{ "apiVersion": "badVersion" }`, expectErr: true, }, { obj: &corev1.Service{ Spec: corev1.ServiceSpec{}, }, fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "ports": [ { "port": 0 } ] } }`, "v1"), expected: &corev1.Service{ TypeMeta: metav1.TypeMeta{ Kind: "Service", APIVersion: "v1", }, Spec: corev1.ServiceSpec{ Ports: []corev1.ServicePort{ { Port: 0, }, }, }, }, }, { obj: &corev1.Service{ Spec: corev1.ServiceSpec{ Selector: map[string]string{ "version": "v1", }, }, }, fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "selector": { "version": "v2" } } }`, "v1"), expected: &corev1.Service{ TypeMeta: metav1.TypeMeta{ Kind: "Service", APIVersion: "v1", }, Spec: corev1.ServiceSpec{ Selector: map[string]string{ "version": "v2", }, }, }, }, } codec := runtime.NewCodec(scheme.DefaultJSONEncoder(), scheme.Codecs.UniversalDecoder(scheme.Scheme.PrioritizedVersionsAllGroups()...)) for i, test := range tests { out, err := Merge(codec, test.obj, test.fragment) if !test.expectErr { if err != nil { t.Errorf("testcase[%d], unexpected error: %v", i, err) } else if !apiequality.Semantic.DeepEqual(test.expected, out) { t.Errorf("\n\ntestcase[%d]\nexpected:\n%s", i, cmp.Diff(test.expected, out)) } } if test.expectErr && err == nil { t.Errorf("testcase[%d], unexpected non-error", i) } } }
358,278
You are an expert in writing code in many different languages. Your goal is 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_kafka_ready_check.rs path of file: ./repos/risingwave/src/risedevtool/src/task the code of the file until where you have to start completion: // Copyright 2024 RisingWave Labs // // 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 exp
fn execute(&mut self, ctx: &mut ExecuteContext<impl std::io::Write>) -> anyhow::Result<()> { ctx.pb.set_message("waiting for online..."); let mut config = ClientConfig::new(); config.set( "bootstrap.servers", &format!("{}:{}", self.config.address, self.config.port), ); let rt = tokio::runtime::Builder::new_current_thread() .enable_time() .enable_io() .build()?; let consumer = rt.block_on(async { BaseConsumer::from_config(&config) .await .context("failed to create consumer") })?; ctx.wait(|| { rt.block_on(async { let _metadata = consumer .fetch_metadata(None, Duration::from_secs(1)) .await .context("failed to fetch metadata")?; Ok(()) }) })?; ctx.complete_spin(); Ok(()) }
404,374
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _list_detectors_output.rs path of file: ./repos/aws-sdk-rust/sdk/ioteventsdata/src/operation/list_detectors 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 fn build(self) -> crate::operation::list_detectors::ListDetectorsOutput { crate::operation::list_detectors::ListDetectorsOutput { detector_summaries: self.detector_summaries, next_token: self.next_token, _request_id: self._request_id, } }
755,819
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: oai_mods.rb path of file: ./repos/archivesspace/backend/app/lib/oai/mappers the code of the file until where you have to start completion: require_relative 'oai_utils' class OAIMODSMapper def map_oai_record(record) jsonmodel = record.jsonmodel_record result = Nokogiri::XML::Builder.new do |xml| xml.mods('xmlns' => 'http://www.loc.gov/mods/v3', 'xmlns:xlink' => 'http://www.w3.org/1999/xlink', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation' => 'http://www.loc.gov/mods/v3 https://www.loc.gov/standards/mods/v3/mods-3-6.xsd') do # Repo name -> location/physicalLocation xml.location { xml.physicalLocation(jsonmodel['repository']['_resolved']['name']) } # Identifier -> identifier # TODO: Reuse after implementing 'off' switch for ARK merged_identifier = if jsonmodel['jsonmodel_type'] == 'archival_object' ([jsonmodel['component_id']] + jsonmodel['ancestors'].map {|a| a['_resolved']['component_id']}).compact.reverse.join(".") else (0..3).
def map_oai_record(record) jsonmodel = record.jsonmodel_record result = Nokogiri::XML::Builder.new do |xml| xml.mods('xmlns' => 'http://www.loc.gov/mods/v3', 'xmlns:xlink' => 'http://www.w3.org/1999/xlink', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation' => 'http://www.loc.gov/mods/v3 https://www.loc.gov/standards/mods/v3/mods-3-6.xsd') do # Repo name -> location/physicalLocation xml.location { xml.physicalLocation(jsonmodel['repository']['_resolved']['name']) } # Identifier -> identifier # TODO: Reuse after implementing 'off' switch for ARK merged_identifier = if jsonmodel['jsonmodel_type'] == 'archival_object' ([jsonmodel['component_id']] + jsonmodel['ancestors'].map {|a| a['_resolved']['component_id']}).compact.reverse.join(".") else (0..3).map {|id| jsonmodel["id_#{id}"]}.compact.join('.') end if AppConfig[:arks_enabled] && jsonmodel['ark_name'] ark_url = jsonmodel['ark_name']['current'] xml.identifier(ark_url) if ark_url end # Creator -> name/namePart Array(jsonmodel['linked_agents']).each do |link| next unless link['_resolved']['publish'] if link['role'] == 'creator' xml.name { xml.namePart(link['_resolved']['title']) } end end
583,753
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: manifest.rs path of file: ./repos/mini-lsm/mini-lsm/src the code of the file until where you have to start completion: use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::path::Path; use std::sync::Arc; use anyhow::{
pub fn create(path: impl AsRef<Path>) -> Result<Self> { Ok(Self { file: Arc::new(Mutex::new( OpenOptions::new() .read(true) .create_new(true) .write(true) .open(path) .context("failed to create manifest")?, )), }) }
598,893
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 07-callback.go path of file: ./repos/gout/_example the code of the file until where you have to start completion: package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/guonaihong/gout" "math/rand" "time" ) type Result struct { Errmsg string `json:"errmsg"` ErrCode int `json:"errcode"` } // Callback接口用于处理服务段会返回多种数据结构,比如404返回出错html, 200返回json // 客户端example func callbackExample() { r, str404 :=
func server() { router := gin.New() router.GET("/", func(c *gin.Context) { rand.Seed(time.Now().UnixNano()) x := rand.Intn(2) //使用随机函数模拟某个服务有一定概率出现404 switch x { case 0: // 模拟 404 找不到资源 c.String(404, "<html> not found </html>") case 1: // 正确业务返回结果 c.JSON(200, Result{Errmsg: "ok"}) } }) router.Run() }
376,716
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: progress.rs path of file: ./repos/fluvio/crates/fluvio-cluster/src the code of the file until where you have to start completion: use std::{borrow::Cow, time::Duration}; use indicatif::{ProgressBar, ProgressStyle}; use
fn create_spinning_indicator() -> Result<ProgressBar> { let pb = ProgressBar::new(1); pb.set_style( ProgressStyle::default_bar() .template("{msg} {spinner}")? .tick_chars("/-\\|"), ); pb.enable_steady_tick(Duration::from_millis(100)); Ok(pb) }
624,272
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: decoder_test.go path of file: ./repos/kubernetes/staging/src/k8s.io/client-go/rest/watch the code of the file until where you have to start completion: /* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri
func TestDecoder_SourceClose(t *testing.T) { out, in := io.Pipe() decoder := restclientwatch.NewDecoder(streaming.NewDecoder(out, getDecoder()), getDecoder()) done := make(chan struct{}) go func() { _, _, err := decoder.Decode() if err == nil { t.Errorf("Unexpected nil error") } close(done) }() in.Close() select { case <-done: break case <-time.After(wait.ForeverTestTimeout): t.Error("Timeout") } }
357,844
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: middleware.go path of file: ./repos/kin-openapi/openapi3filter the code of the file until where you have to start completion: package openapi3filter import ( "bytes" "io" "log" "net/http" "github.com/getkin/kin-openapi/routers" ) // Validator provides HTTP request and response validation middleware. type Validator struct { router routers.Router errFunc
func NewValidator(router routers.Router, options ...ValidatorOption) *Validator { v := &Validator{ router: router, errFunc: func(w http.ResponseWriter, status int, code ErrCode, _ error) { http.Error(w, code.responseText(), status) }, logFunc: func(message string, err error) { log.Printf("%s: %v", message, err) }, } for i := range options { options[i](v) } return v }
464,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: basic.rb path of file: ./repos/truffleruby/lib/mri/bundler/vendor/thor/lib/thor/line_editor the code of the file until where you have to start completion: class Bundler::Thor module LineEdit
def get_input if echo? $stdin.gets else # Lazy-load io/console since it is gem-ified as of 2.3 require "io/console" $stdin.noecho(&:gets) end
176,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: MasterSlaveRelator.m path of file: ./repos/Swan/FEM/Preprocess the code of the file until where you have to start completion: classdef MasterSlaveRelator < handle properties (Access = private) x y z nodesInXmin
function closestNodesUF = obtainClosestNodeInOppositeFace(obj,nodesLF,nodesUF,pos) nNodes = length(nodesLF); closestNodesUF = zeros(nNodes,1); for inode = 1:nNodes nodeLF = nodesLF(inode); closestNodesUF(inode) = obj.obtainClosestNode(nodeLF,nodesUF,pos); end
307,358
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: textedit.go path of file: ./repos/gapid/core/langsvr the code of the file until where you have to start completion: // Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "Licens
func (l TextEditList) toProtocol() []protocol.TextEdit { out := make([]protocol.TextEdit, len(l)) for i, e := range l { out[i] = e.toProtocol() } return out }
602,882
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: msgappv2_codec_test.go path of file: ./repos/learning/golang/practice/go-crontab/gopath/src/github.com/coreos/etcd/etcdserver/api/rafthttp the code of the file until where you have to start completion: // Copyright 2015 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of 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 r
func TestMsgAppV2(t *testing.T) { tests := []raftpb.Message{ linkHeartbeatMessage, { Type: raftpb.MsgApp, From: 1, To: 2, Term: 1, LogTerm: 1, Index: 0, Entries: []raftpb.Entry{ {Term: 1, Index: 1, Data: []byte("some data")}, {Term: 1, Index: 2, Data: []byte("some data")}, {Term: 1, Index: 3, Data: []byte("some data")}, }, }, // consecutive MsgApp { Type: raftpb.MsgApp, From: 1, To: 2, Term: 1, LogTerm: 1, Index: 3, Entries: []raftpb.Entry{ {Term: 1, Index: 4, Data: []byte("some data")}, }, }, linkHeartbeatMessage, // consecutive MsgApp after linkHeartbeatMessage { Type: raftpb.MsgApp, From: 1, To: 2, Term: 1, LogTerm: 1, Index: 4, Entries: []raftpb.Entry{ {Term: 1, Index: 5, Data: []byte("some data")}, }, }, // MsgApp with higher term { Type: raftpb.MsgApp, From: 1, To: 2, Term: 3, LogTerm: 1, Index: 5, Entries: []raftpb.Entry{ {Term: 3, Index: 6, Data: []byte("some data")}, }, }, linkHeartbeatMessage, // consecutive MsgApp { Type: raftpb.MsgApp, From: 1, To: 2, Term: 3, LogTerm: 2, Index: 6, Entries: []raftpb.Entry{ {Term: 3, Index: 7, Data: []byte("some data")}, }, }, // consecutive empty MsgApp { Type: raftpb.MsgApp, From: 1, To: 2, Term: 3, LogTerm: 2, Index: 7, Entries: nil, }, linkHeartbeatMessage, } b := &bytes.Buffer{} enc := newMsgAppV2Encoder(b, &stats.FollowerStats{}) dec := newMsgAppV2Decoder(b, types.ID(2), types.ID(1)) for i, tt := range tests { if err := enc.encode(&tt); err != nil { t.Errorf("#%d: unexpected encode message error: %v", i, err) continue } m, err := dec.decode() if err != nil { t.Errorf("#%d: unexpected decode message error: %v", i, err) continue } if !reflect.DeepEqual(m, tt) { t.Errorf("#%d: message = %+v, want %+v", i, m, tt) } } }
555,588
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: client_ip.rs path of file: ./repos/surrealdb/src/net the code of the file until where you have to start completion: use axum::async_trait; use axum::extract::ConnectInfo; use axum::extract::FromRef; use axum::extract::FromRequestParts; use axum::middleware::Next; use axum::response::Response; use axum::Extension; use axum::R
fn is_header(&self) -> bool { match self { ClientIp::None => false, ClientIp::Socket => false, ClientIp::CfConnectingIp => true, ClientIp::FlyClientIp => true, ClientIp::TrueClientIP => true, ClientIp::XRealIp => true, ClientIp::XForwardedFor => true, } }
147,614
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: analytics.rb path of file: ./repos/hound/app/models the code of the file until where you have to start completion: class Analytics class_attribute :backend self.backend = AnalyticsRuby de
def track_repo_deactivated(repo) track( event: "Repo Deactivated", properties: { name: repo.name, private: repo.private, } ) end
69,473
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_CreateXssMatchSet.go path of file: ./repos/aws-sdk-go-v2/service/waf the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package waf import ( "context" "fmt" awsmiddleware "g
func newServiceMetadataMiddleware_opCreateXssMatchSet(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "CreateXssMatchSet", } }
219,845
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: arith128_test.go path of file: ./repos/mongo-go-driver/internal/rand the code of the file until where you have to start completion: // Copied from https://cs.opensource.google/go/x/exp/+/24438e51023af3bfc1db8aed43c1342817e8cfcd:rand/arith128_test.go // Copyright 2017 The Go Author
func TestPCGMultiplyLong(t *testing.T) { if testing.Short() { return } for i := 0; i < 1e6; i++ { low := rand.Uint64() high := rand.Uint64() p := &PCGSource{ low: low, high: high, } p.multiply() expectHi, expectLo := bigMulMod128bits(high, low, mHi, mLo) if p.low != expectLo || p.high != expectHi { t.Fatalf("%d: (%d,%d): got hi=%d lo=%d; expect hi=%d lo=%d", i, high, low, p.high, p.low, expectHi, expectLo) } } }
471,405
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: router_linux.go path of file: ./repos/scan4all/vendor/github.com/projectdiscovery/naabu/v2/pkg/routing the code of the file until where you have to start completion: //go:build linux // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. // Package routing provides a very basic but mostly functional implementation of // a routing table for IPv4/IPv6 addresses. It uses a routing table pulled from // the kernel via netlink to find the correct interface, gateway, and
func (r *router) route(routes routeSlice, input net.HardwareAddr, src, dst net.IP) (iface int, gateway, preferredSrc net.IP, err error) { var inputIndex uint32 if input != nil { for i, iface := range r.ifaces { if bytes.Equal(input, iface.HardwareAddr) { inputIndex = uint32(i) break } } } var defaultGateway *rtInfo = nil for _, rt := range routes { if rt.InputIface != 0 && rt.InputIface != inputIndex { continue } if rt.Src == nil && rt.Dst == nil { defaultGateway = rt continue } if rt.Src != nil && !rt.Src.Contains(src) { continue } if rt.Dst != nil && !rt.Dst.Contains(dst) { continue } return int(rt.OutputIface), rt.Gateway, rt.PrefSrc, nil } if defaultGateway != nil { return int(defaultGateway.OutputIface), defaultGateway.Gateway, defaultGateway.PrefSrc, nil } err = fmt.Errorf("no route found for %v", dst) return }
140,919
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: samsung_security_manager_put.rb path of file: ./repos/metasploit-framework/modules/exploits/windows/browser the code of the file until where you have to start completion: ## # This module require
def encode_js(string) i = 0 encoded_0 = [] encoded_1 = [] string.each_byte do |c| if i > 65534 encoded_1 << c else encoded_0 << c end i += 1 end
743,192
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: net_http_fcgi.go path of file: ./repos/gomacro/imports the code of the file until where you have to start completion: // this file was generated by gomacro command: import _b "net/http/
func init() { Packages["net/http/fcgi"] = Package{ Name: "fcgi", Binds: map[string]Value{ "ErrConnClosed": ValueOf(&fcgi.ErrConnClosed).Elem(), "ErrRequestAborted": ValueOf(&fcgi.ErrRequestAborted).Elem(), "ProcessEnv": ValueOf(fcgi.ProcessEnv), "Serve": ValueOf(fcgi.Serve), }, } }
714,718
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: base_flow_controller.go path of file: ./repos/scan4all/vendor/github.com/quic-go/quic-go/internal/flowcontrol the code of the file until where you have to start completion: package flowcontrol import ( "sync" "time" "github.com/quic-g
func (c *baseFlowController) addBytesRead(n protocol.ByteCount) { // pretend we sent a WindowUpdate when reading the first byte // this way auto-tuning of the window size already works for the first WindowUpdate if c.bytesRead == 0 { c.startNewAutoTuningEpoch(time.Now()) } c.bytesRead += n }
143,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: complex.go path of file: ./repos/IOC-golang/example/autowire/autowire_rpc/client/test/service the code of the file until where you have to start completion: /* * Copyright (c) 2022, Alibaba Group; * Licensed under th
func (s *ComplexService) RPCWithError() (*dto.User, error) { errMsg := "custom" return &dto.User{ Id: 1, Name: "laurence", Age: 23, }, fmt.Errorf("custom error = %s", errMsg) }
504,716
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: util.go path of file: ./repos/IOC-golang/extension/aop/monitor the code of the file until where you have to start completion: /* * Copyright (c) 2022, Alibaba Group; * Licensed under the Apache License, Version 2.0 (the "Lic
func getAverageInt64(input []int64) float32 { length := len(input) if length == 0 { return 0 } sum := int64(0) for _, v := range input { sum += v } return float32(sum) / float32(length) }
504,484
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: client.rb path of file: ./repos/kitchen-terraform/lib/kitchen/terraform/config_attribute the code of the file until where you have to start completion: # frozen_string_literal: true # Copyright 2016-2021 Copado NCS LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:/
def included(plugin_class) ::Kitchen::Terraform::ConfigAttributeDefiner.new( attribute: self, schema: ::Kitchen::Terraform::ConfigAttributeContract::String.new, ).define plugin_class: plugin_class plugin_class.expand_path_for to_sym do |plugin| !::TTY::Which.exist? plugin[to_sym] end self end
635,146
You are an expert in writing code in many different languages. Your goal is 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/datacatalog/apiv1/PolicyTagManagerClient/UpdatePolicyTag 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 spec
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 := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &datacatalogpb.UpdatePolicyTagRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/cloud.google.com/go/datacatalog/apiv1/datacatalogpb#UpdatePolicyTagRequest. } resp, err := c.UpdatePolicyTag(ctx, req) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp }
283,370
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: host_path.go path of file: ./repos/kubeedge/vendor/k8s.io/kubernetes/test/e2e/common/storage the code of the file until where you have to start completion: /* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compl
func testPodWithHostVol(path string, source *v1.HostPathVolumeSource, privileged bool) *v1.Pod { podName := "pod-host-path-test" return &v1.Pod{ TypeMeta: metav1.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: podName, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: containerName1, Image: imageutils.GetE2EImage(imageutils.Agnhost), Args: []string{"mounttest"}, VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: path, }, }, SecurityContext: &v1.SecurityContext{ Privileged: &privileged, }, }, { Name: containerName2, Image: imageutils.GetE2EImage(imageutils.Agnhost), Args: []string{"mounttest"}, VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: path, }, }, SecurityContext: &v1.SecurityContext{ Privileged: &privileged, }, }, }, RestartPolicy: v1.RestartPolicyNever, Volumes: mount(source), }, } }
417,261
You are an expert in writing code in many different languages. Your goal is 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/minijinja/minijinja/src/vm the code of the file until where you have to start completion: use std::collections::BTreeMap; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use crate::compiler::instructions::{ Instruction, Instructions, LOOP_FLAG_RECURSIVE, LOOP_FLAG_WITH_LOOP_VAR, MAX_LOCALS, }; use crate::environment::Environment; use crate::error::{Error, ErrorKind}; use crate::output::{CaptureMode, Output}; use crate::utils::{untrusted_size_hint, AutoEscape, UndefinedBehavior}; use crate::value
fn prepare_loop_recursion(&self, state: &mut State) -> Result<usize, Error> { if let Some(loop_ctx) = state.ctx.current_loop() { if let Some(recurse_jump_target) = loop_ctx.recurse_jump_target { Ok(recurse_jump_target) } else { Err(Error::new( ErrorKind::InvalidOperation, "cannot recurse outside of recursive loop", )) } } else { Err(Error::new( ErrorKind::InvalidOperation, "cannot recurse outside of loop", )) } }
53,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: upstream.go path of file: ./repos/dnsproxy/upstream the code of the file until where you have to start completion: // Package upstream implements DNS clients for all known DNS encryption // protocols. package upstream import ( "context" "crypto/tls" "crypto/x509" "fmt" "io" "net" "net/netip" "net/url" "os" "strconv" "strings" "time" "github.
func isTimeout(err error) (ok bool) { var netErr net.Error switch { case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded), errors.Is(err, os.ErrDeadlineExceeded): return true case errors.As(err, &netErr): return netErr.Timeout() default: return false } }
31,163
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: PhysicalProblem.m path of file: ./repos/Swan/FEM the code of the file until where you have to start completion: classdef PhysicalProblem < handle properties (Access = protected) inputReader end methods (Access = public)
function obj = create(s) switch s.type case 'ELASTIC' switch s.scale case 'MACRO' obj = ElasticProblem(s); case 'MICRO' obj = ElasticProblemMicro(s); end
307,370
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: serverparameters_server.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/mysql/armmysql/fake the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. package fake import ( "context" "errors" "fmt" azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" "github.com/Azure/a
func (s *ServerParametersServerTransport) 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 "ServerParametersClient.BeginListUpdateConfigurations": resp, err = s.dispatchBeginListUpdateConfigurations(req) default: err = fmt.Errorf("unhandled API %s", method) } if err != nil { return nil, err } return resp, nil }
269,650
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: date.rs path of file: ./repos/materialize/src/repr/src/adt the code of the file until where you have to start completion: // Copyright Materialize, Inc. and contributors. All rights reserved. //
pub fn from_unix_epoch(unix_days: i32) -> Result<Date, DateError> { let pg_days = unix_days.saturating_sub(Self::UNIX_EPOCH_TO_PG_EPOCH); if pg_days == i32::MIN { return Err(DateError::OutOfRange); } Self::from_pg_epoch(pg_days) }
370,865
You are an expert in writing code in many different languages. Your goal is 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_reverse_row_align_content_flex_start.rs path of file: ./repos/stretch/tests/generated the code of the file until where you have to start completion: #[test] fn wrap_reverse_row_align_content_flex_start() { let mut stretch = stretch::Stretch::new(); let node0 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(10f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node1 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(20f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node2 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(30f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node3 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(40f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node4 = stretch .ne
fn wrap_reverse_row_align_content_flex_start() { let mut stretch = stretch::Stretch::new(); let node0 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(10f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node1 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(20f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node2 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(30f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node3 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(40f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node4 = stretch .new_node( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(30f32), height: stretch::style::Dimension::Points(50f32), ..Default::default() }, ..Default::default() }, &[], ) .unwrap(); let node = stretch .new_node( stretch::style::Style { flex_wrap: stretch::style::FlexWrap::WrapReverse, align_content: stretch::style::AlignContent::FlexStart, size: stretch::geometry::Size { width: stretch::style::Dimension::Points(100f32), ..Default::default() }, ..Default::default() }, &[node0, node1, node2, node3, node4], ) .unwrap(); stretch.compute_layout(node, stretch::geometry::Size::undefined()).unwrap(); assert_eq!(stretch.layout(node).unwrap().size.width, 100f32); assert_eq!(stretch.layout(node).unwrap().size.height, 80f32); assert_eq!(stretch.layout(node).unwrap().location.x, 0f32); assert_eq!(stretch.layout(node).unwrap().location.y, 0f32); assert_eq!(stretch.layout(node0).unwrap().size.width, 30f32); assert_eq!(stretch.layout(node0).unwrap().size.height, 10f32); assert_eq!(stretch.layout(node0).unwrap().location.x, 0f32); assert_eq!(stretch.layout(node0).unwrap().location.y, 70f32); assert_eq!(stretch.layout(node1).unwrap().size.width, 30f32); assert_eq!(stretch.layout(node1).unwrap().size.height, 20f32); assert_eq!(stretch.layout(node1).unwrap().location.x, 30f32); assert_eq!(stretch.layout(node1).unwrap().location.y, 60f32); assert_eq!(stretch.layout(node2).unwrap().size.width, 30f32); assert_eq!(stretch.layout(node2).unwrap().size.height, 30f32); assert_eq!(stretch.layout(node2).unwrap().location.x, 60f32); assert_eq!(stretch.layout(node2).unwrap().location.y, 50f32); assert_eq!(stretch.layout(node3).unwrap().size.width, 30f32); assert_eq!(stretch.layout(node3).unwrap().size.height, 40f32); assert_eq!(stretch.layout(node3).unwrap().location.x, 0f32); assert_eq!(stretch.layout(node3).unwrap().location.y, 10f32); assert_eq!(stretch.layout(node4).unwrap().size.width, 30f32); assert_eq!(stretch.layout(node4).unwrap().size.height, 50f32); assert_eq!(stretch.layout(node4).unwrap().location.x, 30f32); assert_eq!(stretch.layout(node4).unwrap().location.y, 0f32); }
130,245
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: pstore.rb path of file: ./repos/artichoke/artichoke-backend/vendor/ruby/lib/cgi/session the code of the file until where you have to start completion: # frozen_string_literal: true # # cgi/session/pstore.rb - persistent storage of marshalled session data # # Documentation: William Webber (william@williamwebber.com) # # ==
def initialize(session, option={}) option = {'suffix'=>''}.update(option) path, @hash = session.new_store_file(option) @p = ::PStore.new(path) @p.transaction do |p| File.chmod(0600, p.path) end end
311,576
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: goroutine_panic.go path of file: ./repos/the-way-to-go_ZH_CN/eBook/exercises/chapter_14 the code of the file until where you have to start completion: package main import ( "fmt" ) func tel(ch chan int) { for i
func main() { var ok = true ch := make(chan int) go tel(ch) for ok { i := <-ch fmt.Printf("ok is %t and the counter is at %d\n", ok, i) } }
260,529
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: backend.go path of file: ./repos/zrok/endpoints/drive the code of the file until where you have to start completion: package drive import ( "fmt" "github.com/openziti/sdk-golang/ziti" "github.com/openziti/sdk-golang/ziti/edge" "github.com/openziti/zrok/drives/davServer" "github.com/openziti/zrok/endpoints" "github.com/pkg/errors" "net/http" "time" ) type BackendConfig struct { IdentityPath string DriveRoot string ShrToken string Requests chan *endpoints.Request } type Backend struct { cfg *BackendConfig listener edge.Listener handler http.Handler } func NewBackend(cfg *BackendConfig) (*Backend, error) { options := ziti.ListenOptions{ ConnectTimeout: 5 * time.Minute, WaitForNEstablishedListeners: 1, } zcfg, err := ziti.NewConfigFromFile(cfg.IdentityPath) if err != nil { return nil, errors.Wrap(err, "error loading ziti identity") } zctx, err := ziti.NewContext(zcfg) if err != nil { return nil, errors.Wrap(err, "error loading ziti context") } listener, err
func NewBackend(cfg *BackendConfig) (*Backend, error) { options := ziti.ListenOptions{ ConnectTimeout: 5 * time.Minute, WaitForNEstablishedListeners: 1, } zcfg, err := ziti.NewConfigFromFile(cfg.IdentityPath) if err != nil { return nil, errors.Wrap(err, "error loading ziti identity") } zctx, err := ziti.NewContext(zcfg) if err != nil { return nil, errors.Wrap(err, "error loading ziti context") } listener, err := zctx.ListenWithOptions(cfg.ShrToken, &options) if err != nil { return nil, err } handler := &davServer.Handler{ FileSystem: davServer.Dir(cfg.DriveRoot), LockSystem: davServer.NewMemLS(), Logger: func(r *http.Request, err error) { if cfg.Requests != nil { cfg.Requests <- &endpoints.Request{ Stamp: time.Now(), RemoteAddr: fmt.Sprintf("%v", r.Header["X-Real-Ip"]), Method: r.Method, Path: r.URL.String(), } } }, } return &Backend{ cfg: cfg, listener: listener, handler: handler, }, nil }
698,973
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: active_job_adapter.rb path of file: ./repos/shoryuken/lib/shoryuken/extensions the code of the file until where you have to start completion: # ActiveJob docs: http://edgeguides.rubyonrails.org/active_job_basics.html #
def enqueue(job, options = {}) #:nodoc: register_worker!(job) job.sqs_send_message_parameters.merge! options queue = Shoryuken::Client.queues(job.queue_name) send_message_params = message queue, job job.sqs_send_message_parameters = send_message_params queue.send_message send_message_params end
403,482
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: extractObjectsMasksDistances.m path of file: ./repos/Image-Harmonization-Dataset-iHarmony4/Lalonde and Efros/colorStatistics/mycode/datasetGeneration the code of the file until where you have to start completion: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function extractObjectsMasksDistances % Generate test images to evaluate if our method actually captures % statistics of natural images. Uses location information to choose the % object to paste (closest mask in SSD distance). Second part: compute % the SSD distance from every image to every other one. % % Input parameters: % % Output parameters: % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function extractObjectsMasks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright 2006-2007 Jean-Francois Lalonde % Carnegie Mellon University % Do not distribute %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% addpath ../database; addpath ../../3rd_party/LabelMeToolbox; % define the input and output paths outputBasePath = '/nfs/hn01/jlalonde/results/colorStatistics/testDataSemantic/'; maskPath = fullfile(outputBasePath, 'maskInfo.mat'); fprintf('Loading the masks...'); load(maskPath); fprintf('done.\n'); % Initialize a matrix of the corresponding size distMatrix = zeros(accObjects, accObjects); tmpDistMatrix = zeros(accObjects, accObjects); % fill in the matrix elements tmpMasks = double(reshape(permute(maskVec(1:accObjects,:,:), [2 3 1]), size(maskVec,2)*size(maskVec,3), accObjects)); for i=1:accObjects curMask = double(repmat(reshape(squeeze(maskVec(i,:,:)), size(maskVec,2)*size(maskVec,3), 1), 1, accObjects)); distMatrix(i,:) = sum((curMask - tmpMasks).^2, 1); fprintf('%d.',i); end
570,486
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: syscallconn.go path of file: ./repos/buildkit/vendor/google.golang.org/grpc/internal/credentials the code of the file until where you have to start completion: /* * * Copyright 2018 gRPC authors. * * Licensed under
func WrapSyscallConn(rawConn, newConn net.Conn) net.Conn { sysConn, ok := rawConn.(syscall.Conn) if !ok { return newConn } return &syscallConn{ Conn: newConn, sysConn: sysConn, } }
654,497
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _statistical_issue_status.rs path of file: ./repos/aws-sdk-rust/sdk/lookoutequipment/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen
pub fn as_str(&self) -> &str { match self { StatisticalIssueStatus::NoIssueDetected => "NO_ISSUE_DETECTED", StatisticalIssueStatus::PotentialIssueDetected => "POTENTIAL_ISSUE_DETECTED", StatisticalIssueStatus::Unknown(value) => value.as_str(), } }
770,798
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: base_test.go path of file: ./repos/vuls/scanner the code of the file until where you have to start completion: package scanner import ( "reflect" "testing" _ "github.com/aquasecurity/trivy/pkg/fanal/analyzer/language/dotnet/deps" _ "github.com/aquasecurity/trivy/pkg/fanal/analyzer/language/dotnet/nuget" _ "github.com/aquasecurity/trivy/pkg/fanal/analyzer/language/golang/binary" _ "github.com/aquasecurity/trivy/pkg/fanal/analyzer/language/golang/mod" _ "github.com/aquasecurity/trivy/pkg/fanal/analyzer
func TestIsAwsInstanceID(t *testing.T) { var tests = []struct { in string expected bool }{ {"i-1234567a", true}, {"i-1234567890abcdef0", true}, {"i-1234567890abcdef0000000", true}, {"e-1234567890abcdef0", false}, {"i-1234567890abcdef0 foo bar", false}, {"no data", false}, } r := newAmazon(config.ServerInfo{}) for _, tt := range tests { actual := r.isAwsInstanceID(tt.in) if tt.expected != actual { t.Errorf("expected %t, actual %t, str: %s", tt.expected, actual, tt.in) } } }
13,936
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: spanner_executor_proxy_client_example_test.go path of file: ./repos/google-cloud-go/spanner/executor/apiv1 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. package executor_test import ( "context" "io" executor "cloud.google.com/go/spanner/executor/apiv1" executorpb "cloud.google.com/go/spanner/executor/apiv1/executorpb" ) func ExampleNewSpan
func ExampleSpannerExecutorProxyClient_ExecuteActionAsync() { 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 := executor.NewSpannerExecutorProxyClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() stream, err := c.ExecuteActionAsync(ctx) if err != nil { // TODO: Handle error. } go func() { reqs := []*executorpb.SpannerAsyncActionRequest{ // TODO: Create requests. } for _, req := range reqs { if err := stream.Send(req); err != nil { // TODO: Handle error. } } stream.CloseSend() }() for { resp, err := stream.Recv() if err == io.EOF { break } if err != nil { // TODO: handle error. } // TODO: Use resp. _ = resp } }
283,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: main.go path of file: ./repos/learning/golang/practice/go-crontab/source/prepare/etcd_usage/demo9 the code of the file until where you have to start completion: package main import ( "github.com/coreos/etcd/clientv3" "time" "fmt" "context" ) func main() { var ( config clientv3.Config client *clientv3.Client err error lease clientv3.Lease leaseGrantResp *clientv3.LeaseGrantResponse leaseId clientv3.LeaseID keepRespChan <-chan *clientv3.LeaseKeepAliveResponse keepResp *clientv3.LeaseKeepAliveResponse ctx context.Context cancelFunc context.CancelFunc kv clientv3.KV txn clientv3.Txn txnResp *clientv3.TxnResponse ) // 客户端配置 config = clientv3.Config{ Endpoints: []string{"36.111.184.221:2379"}, DialTimeout: 5 * time.Second, } // 建立连接 if client, err = clientv3.New(config); err != nil { fmt.Println(err) return } // lease实现锁自动过期: // op操作 // txn事务: if else then // 1, 上锁 (创建租约, 自动续租, 拿着租约去抢占一个key) lease = clientv3.NewLease(client) // 申请一个5秒的租约 if leaseGrantResp, err = lease.Grant(context.TODO(), 5); err != nil { fmt.Println(err) return } // 拿到租约的ID leaseId = leaseGrantResp.ID // 准备一个用于取消自动续租的context ctx, cancelFunc = context.WithCancel(context.TODO()) // 确保函数退出后, 自动续租会停止 defer cancelFunc() defer lease.Revoke(context.TODO(), leaseId) // 5秒后会取消自动续租 if keepRespChan, err = lease.KeepAlive(ctx, leaseId); err != nil { fmt.Println(err) return } // 处理续约应答的协程 go func() { for { select { case keepResp = <- keepRespChan: if keepRespChan == nil { fmt.Println("租约已经失效了") goto END
func main() { var ( config clientv3.Config client *clientv3.Client err error lease clientv3.Lease leaseGrantResp *clientv3.LeaseGrantResponse leaseId clientv3.LeaseID keepRespChan <-chan *clientv3.LeaseKeepAliveResponse keepResp *clientv3.LeaseKeepAliveResponse ctx context.Context cancelFunc context.CancelFunc kv clientv3.KV txn clientv3.Txn txnResp *clientv3.TxnResponse ) // 客户端配置 config = clientv3.Config{ Endpoints: []string{"36.111.184.221:2379"}, DialTimeout: 5 * time.Second, } // 建立连接 if client, err = clientv3.New(config); err != nil { fmt.Println(err) return } // lease实现锁自动过期: // op操作 // txn事务: if else then // 1, 上锁 (创建租约, 自动续租, 拿着租约去抢占一个key) lease = clientv3.NewLease(client) // 申请一个5秒的租约 if leaseGrantResp, err = lease.Grant(context.TODO(), 5); err != nil { fmt.Println(err) return } // 拿到租约的ID leaseId = leaseGrantResp.ID // 准备一个用于取消自动续租的context ctx, cancelFunc = context.WithCancel(context.TODO()) // 确保函数退出后, 自动续租会停止 defer cancelFunc() defer lease.Revoke(context.TODO(), leaseId) // 5秒后会取消自动续租 if keepRespChan, err = lease.KeepAlive(ctx, leaseId); err != nil { fmt.Println(err) return } // 处理续约应答的协程 go func() { for { select { case keepResp = <- keepRespChan: if keepRespChan == nil { fmt.Println("租约已经失效了") goto END } else { // 每秒会续租一次, 所以就会受到一次应答 fmt.Println("收到自动续租应答:", keepResp.ID) } } } END: }() // if 不存在key, then 设置它, else 抢锁失败 kv = clientv3.NewKV(client) // 创建事务 txn = kv.Txn(context.TODO()) // 定义事务 // 如果key不存在 txn.If(clientv3.Compare(clientv3.CreateRevision("/cron/lock/job9"), "=", 0)). Then(clientv3.OpPut("/cron/lock/job9", "xxx", clientv3.WithLease(leaseId))). Else(clientv3.OpGet("/cron/lock/job9")) // 否则抢锁失败 // 提交事务 if txnResp, err = txn.Commit(); err != nil { fmt.Println(err) return // 没有问题 } // 判断是否抢到了锁 if !txnResp.Succeeded { fmt.Println("锁被占用:", string(txnResp.Responses[0].GetResponseRange().Kvs[0].Value)) return } // 2, 处理业务 fmt.Println("处理任务") time.Sleep(5 * time.Second) // 3, 释放锁(取消自动续租, 释放租约) // defer 会把租约释放掉, 关联的KV就被删除了 }
555,196
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: env_info.rs path of file: ./repos/meilisearch/xtask/src/bench the code of the file until where you have to start completion: use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Environment { pub hostname: Option<String>, pub cpu: String, /// Advertised or nominal clock speed in Hertz. pub clock_speed: u64, /// Total number of bytes of memory provided by the system. */ pub memory: u64, pub os_type: String, pub software: Vec<VersionInfo>, pub user_name: String, /// Is set true when the data was gathered by a manual run, /// possibly on a developer machine, instead of the usual benchmark server. pub manual_run: bool, } impl Environment { pub fn generate_from_current_config() -> Self { use sysinfo::System; let unknown_string = String::from("Unknown"); let mut system = System::new(); system.refresh_cpu(); system.refresh_cpu_frequency(); system.refresh_memory(); let (cpu, frequency) = match system.cpus().first() { Some(cpu) => ( format!("{} @ {:.2}GHz", cpu.brand(), cpu.frequency() as f64 / 1000.0),
pub fn generate_from_current_config() -> Self { use sysinfo::System; let unknown_string = String::from("Unknown"); let mut system = System::new(); system.refresh_cpu(); system.refresh_cpu_frequency(); system.refresh_memory(); let (cpu, frequency) = match system.cpus().first() { Some(cpu) => ( format!("{} @ {:.2}GHz", cpu.brand(), cpu.frequency() as f64 / 1000.0), cpu.frequency() * 1_000_000, ), None => (unknown_string.clone(), 0), }; let mut software = Vec::new(); if let Some(distribution) = System::name() { software .push(VersionInfo { name: distribution, version: String::from("distribution") }); } if let Some(kernel) = System::kernel_version() { software.push(VersionInfo { name: kernel, version: String::from("kernel") }); } if let Some(os) = System::os_version() { software.push(VersionInfo { name: os, version: String::from("kernel-release") }); } if let Some(arch) = System::cpu_arch() { software.push(VersionInfo { name: arch, version: String::from("arch") }); } Self { hostname: System::host_name(), cpu, clock_speed: frequency, memory: system.total_memory(), os_type: System::long_os_version().unwrap_or(unknown_string.clone()), user_name: System::name().unwrap_or(unknown_string.clone()), manual_run: false, software, } }
540,174
You are an expert in writing code in many different languages. Your goal is 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.go path of file: ./repos/juju/apiserver/common/secrets the code of the file until where you have to start completion: // Copyright 2023 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package
func AuthTagApp(authTag names.Tag) string { switch authTag.Kind() { case names.ApplicationTagKind: return authTag.Id() case names.UnitTagKind: authAppName, _ := names.UnitApplication(authTag.Id()) return authAppName } return "" }
611,502
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: base_component.rb path of file: ./repos/view_components/app/components/primer the code of the file until where you have to start completion: # frozen_string_literal: true require "primer/classify" m
def initialize(tag:, classes: nil, **system_arguments) @tag = tag @system_arguments = validate_arguments(tag: tag, **system_arguments) @result = Primer::Classify.call(**@system_arguments.merge(classes: classes)) @system_arguments[:"data-view-component"] = true # Filter out Primer keys so they don't get assigned as HTML attributes @content_tag_args = add_test_selector(@system_arguments).except(*Primer::Classify::Utilities::UTILITIES.keys) end def call if SELF_CLOSING_TAGS.include?(@tag) tag(@tag, @content_tag_args.merge(@result)) else content_tag(@tag, content, @content_tag_args.merge(@result)) end end
402,684
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: chunk_queue_test.rs path of file: ./repos/webrtc/util/src/vnet/chunk_queue the code of the file until where you have to start completion: use std::net::SocketAddr; use std::str::FromStr; use super::*; use crate::error::Result; const DEMO_IP: &str = "1.2.3.4"; #[tokio::test] async fn test_chunk_queue() -> Result<()> { let c: Box<dyn Chunk> = Box::new(ChunkUdp::new( SocketAddr::from_str("192.188.0.2:1234")?, SocketAddr::from_str(&(DEMO_IP.to_owned() + ":5678"))?, )); let q = ChunkQueue::new(0); let d = q.peek().await; assert!(d.is_none(), "should return none"); let ok = q.push(c.clone_to()).await; assert!(ok, "should succeed"); let d = q.pop().await; assert!(d.is_some(), "should succeed"); if let Some(d) = d { assert_eq!(c.to_string(), d.to_string(), "should be the same"); } let d = q.pop().await; assert!(d.is_none(), "should fail"); let q = ChunkQueue::new(1); let ok = q.push(c.clone_to()).await;
async fn test_chunk_queue() -> Result<()> { let c: Box<dyn Chunk> = Box::new(ChunkUdp::new( SocketAddr::from_str("192.188.0.2:1234")?, SocketAddr::from_str(&(DEMO_IP.to_owned() + ":5678"))?, )); let q = ChunkQueue::new(0); let d = q.peek().await; assert!(d.is_none(), "should return none"); let ok = q.push(c.clone_to()).await; assert!(ok, "should succeed"); let d = q.pop().await; assert!(d.is_some(), "should succeed"); if let Some(d) = d { assert_eq!(c.to_string(), d.to_string(), "should be the same"); } let d = q.pop().await; assert!(d.is_none(), "should fail"); let q = ChunkQueue::new(1); let ok = q.push(c.clone_to()).await; assert!(ok, "should succeed"); let ok = q.push(c.clone_to()).await; assert!(!ok, "should fail"); let d = q.peek().await; assert!(d.is_some(), "should succeed"); if let Some(d) = d { assert_eq!(c.to_string(), d.to_string(), "should be the same"); } Ok(()) }
306,807
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _input_mode.rs path of file: ./repos/aws-sdk-rust/sdk/sagemaker/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 { InputMode::File => write!(f, "File"), InputMode::Pipe => write!(f, "Pipe"), InputMode::Unknown(value) => write!(f, "{}", value), } }
763,022
You are an expert in writing code in many different languages. Your goal is 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_revision.rs path of file: ./repos/aws-sdk-rust/sdk/dataexchange/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 `DeleteRevision`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct DeleteRevision; impl DeleteRevision { /// Creates a new `DeleteRevision` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_runtime_api::client::
fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> { let mut cfg = ::aws_smithy_types::config_bag::Layer::new("DeleteRevision"); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new( DeleteRevisionRequestSerializer, )); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new( DeleteRevisionResponseDeserializer, )); 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( "DeleteRevision", "dataexchange", )); 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()) }
778,349
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: channels_per_key.rs path of file: ./repos/tarpc/tarpc/src/server/limits the code of the file until where you have to start completion: // Copyright 2018 Google LLC // // Use of this source code is governed by an MIT-style // license that can be found i
fn channel_filter_increment_channels_for_key() { use assert_matches::assert_matches; use pin_utils::pin_mut; struct TestChannel { key: &'static str, } let (_, listener) = futures::channel::mpsc::unbounded(); let filter = MaxChannelsPerKey::new(listener, 2, |chan: &TestChannel| chan.key); pin_mut!(filter); let tracker1 = filter.as_mut().increment_channels_for_key("key").unwrap(); assert_eq!(Arc::strong_count(&tracker1), 1); let tracker2 = filter.as_mut().increment_channels_for_key("key").unwrap(); assert_eq!(Arc::strong_count(&tracker1), 2); assert_matches!(filter.increment_channels_for_key("key"), Err("key")); drop(tracker2); assert_eq!(Arc::strong_count(&tracker1), 1); }
678,039
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: list.go path of file: ./repos/go-oauth2-server/util/response the code of the file until where you have to start completion: package response import ( "github.com/RichardKnop/jsonhal" ) // ListResponse ... type ListResponse struct { jsonhal.Hal Count uint `json:"count"` Page uint `json:"page"` } // NewListResponse cr
func NewListResponse(count, page int, self, first, last, previous, next, embedName string, items interface{}) *ListResponse { response := &ListResponse{ Count: uint(count), Page: uint(page), } response.SetLink("self", self, "") response.SetLink("first", first, "") response.SetLink("last", last, "") response.SetLink("prev", previous, "") response.SetLink("next", next, "") response.SetEmbedded(embedName, jsonhal.Embedded(items)) return response }
397,779
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: binder.rb path of file: ./repos/puma/lib/puma the code of the file until where you have to start completion: # frozen_string_literal: true require 'uri' require 'socket' require_relative 'const' require_relative 'u
def inherit_unix_listener(path, fd) s = fd.kind_of?(::TCPServer) ? fd : ::UNIXServer.for_fd(fd) @ios << s env = @proto_env.dup env[REMOTE_ADDR] = "127.0.0.1" @envs[s] = env s end
108,772
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sockcmsg_dragonfly.go path of file: ./repos/docker-ce/components/engine/vendor/golang.org/x/sys/unix 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
func cmsgAlignOf(salen int) int { salign := SizeofPtr if SizeofPtr == 8 && !supportsABI(_dragonflyABIChangeVersion) { // 64-bit Dragonfly before the September 2019 ABI changes still requires // 32-bit aligned access to network subsystem. salign = 4 } return (salen + salign - 1) & ^(salign - 1) }
567,202
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: retry_test.go path of file: ./repos/resty the code of the file until where you have to start completion: // Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. package resty import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "reflect" "strconv" "strings" "testing" "time" ) func TestBackoffSuccess(t *testing.T) { attempts := 3 externalCounter := 0 retryErr := Backoff(func() (*Response, error) { exte
func TestClientRetryWaitCallbackSwitchToDefault(t *testing.T) { ts := createGetServer(t) defer ts.Close() attempt := 0 retryCount := 5 retryIntervals := make([]uint64, retryCount+1) // Set retry wait times that do not intersect with default ones retryWaitTime := 1 * time.Second retryMaxWaitTime := 3 * time.Second retryAfter := func(client *Client, resp *Response) (time.Duration, error) { return 0, nil // use default algorithm to determine retry-after time } c := dc(). EnableTrace(). SetRetryCount(retryCount). SetRetryWaitTime(retryWaitTime). SetRetryMaxWaitTime(retryMaxWaitTime). SetRetryAfter(retryAfter). AddRetryCondition( func(r *Response, _ error) bool { timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64) retryIntervals[attempt] = timeSlept attempt++ return true }, ) resp, _ := c.R().Get(ts.URL + "/set-retrywaittime-test") // 6 attempts were made assertEqual(t, attempt, 6) assertEqual(t, resp.Request.Attempt, 6) assertEqual(t, resp.Request.TraceInfo().RequestAttempt, 6) // Initial attempt has 0 time slept since last request assertEqual(t, retryIntervals[0], uint64(0)) for i := 1; i < len(retryIntervals); i++ { slept := time.Duration(retryIntervals[i]) expected := (1 << (uint(i - 1))) * time.Second if expected > retryMaxWaitTime { expected = retryMaxWaitTime } // Ensure that client has slept some duration between // waitTime and maxWaitTime for consequent requests if slept < expected/2-5*time.Millisecond || expected+5*time.Millisecond < slept { t.Errorf("Client has slept %f seconds before retry %d", slept.Seconds(), i) } } }
438,265
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: annotated_string.pb.go path of file: ./repos/google-cloud-go/dataqna/apiv1alpha/dataqnapb the code of the file until where you have to start completion: // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. /
func (x *AnnotatedString) Reset() { *x = AnnotatedString{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dataqna_v1alpha_annotated_string_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
284,224
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: syscalls.rs path of file: ./repos/rustix/src/backend/libc/fs the code of the file until where you have to start completion: //! libc syscalls supporting `rustix::fs`. use crate::backend::c; #[cfg(any( not(target_os = "redox"), feature = "alloc", all(linux_kernel, feature =
pub(crate) fn fstat(fd: BorrowedFd<'_>) -> io::Result<Stat> { // 32-bit and mips64 Linux: `struct stat64` is not y2038 compatible; use // `statx`. // // And, some old platforms don't support `statx`, and some fail with a // confusing error code, so we call `crate::fs::statx` to handle that. If // `statx` isn't available, fall back to the buggy system call. #[cfg(all( linux_kernel, any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ) ))] { match crate::fs::statx(fd, cstr!(""), AtFlags::EMPTY_PATH, StatxFlags::BASIC_STATS) { Ok(x) => statx_to_stat(x), Err(io::Errno::NOSYS) => fstat_old(fd), Err(err) => Err(err), } } // Main version: libc is y2038 safe. Or, the platform is not y2038 safe and // there's nothing practical we can do. #[cfg(not(all( linux_kernel, any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ) )))] unsafe { let mut stat = MaybeUninit::<Stat>::uninit(); ret(c::fstat(borrowed_fd(fd), stat.as_mut_ptr()))?; Ok(stat.assume_init()) } }
462,667
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: diagnostic.rs path of file: ./repos/aws-sdk-rust/sdk/keyspaces/src/endpoint_lib the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use std::error::Error; /// D
pub(crate) fn capture<T, E: Into<Box<dyn Error + Send + Sync>>>(&mut self, err: Result<T, E>) -> Option<T> { match err { Ok(res) => Some(res), Err(e) => { self.report_error(e); None } } }
771,030
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: longpath.go path of file: ./repos/octant/vendor/github.com/Microsoft/hcsshim/internal/longpath the code of the file until where you have to start completion: package longpath import ( "path/filepath" "strings" ) // LongAbs makes a path absolute and returns it in NT long
func LongAbs(path string) (string, error) { if strings.HasPrefix(path, `\\?\`) || strings.HasPrefix(path, `\\.\`) { return path, nil } if !filepath.IsAbs(path) { absPath, err := filepath.Abs(path) if err != nil { return "", err } path = absPath } if strings.HasPrefix(path, `\\`) { return `\\?\UNC\` + path[2:], nil } return `\\?\` + path, nil }
197,001
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: envconfig.go path of file: ./repos/buildkit/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig the code of the file until where you have to start completion: // Code created by gotmpl. DO NOT MODIFY. // source: internal/shared/otlp/otlptrace/otlpconfig/envconfig.go.tmpl // Copyright The OpenTelemetry Authors // //
func withEndpointForGRPC(u *url.URL) func(cfg Config) Config { return func(cfg Config) Config { // For OTLP/gRPC endpoints, this is the target to which the // exporter is going to send telemetry. cfg.Traces.Endpoint = path.Join(u.Host, u.Path) return cfg } }
654,364
You are an expert in writing code in many different languages. Your goal is 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_GetSnapshot.go path of file: ./repos/aws-sdk-go-v2/service/redshiftserverless the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package redshiftserverless import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/service/redshiftserverless/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Returns
func (c *Client) GetSnapshot(ctx context.Context, params *GetSnapshotInput, optFns ...func(*Options)) (*GetSnapshotOutput, error) { if params == nil { params = &GetSnapshotInput{} } result, metadata, err := c.invokeOperation(ctx, "GetSnapshot", params, optFns, c.addOperationGetSnapshotMiddlewares) if err != nil { return nil, err } out := result.(*GetSnapshotOutput) out.ResultMetadata = metadata return out, nil }
220,297
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _batch_get_blueprints_output.rs path of file: ./repos/aws-sdk-rust/sdk/glue/src/operation/batch_get_blueprints the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq,
pub fn build(self) -> crate::operation::batch_get_blueprints::BatchGetBlueprintsOutput { crate::operation::batch_get_blueprints::BatchGetBlueprintsOutput { blueprints: self.blueprints, missing_blueprints: self.missing_blueprints, _request_id: self._request_id, } }
795,809
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: firewallrules_client.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/redis/armredis the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information.
func (client *FirewallRulesClient) createOrUpdateHandleResponse(resp *http.Response) (FirewallRulesClientCreateOrUpdateResponse, error) { result := FirewallRulesClientCreateOrUpdateResponse{} if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRule); err != nil { return FirewallRulesClientCreateOrUpdateResponse{}, err } return result, nil }
263,939
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: bramila_erodemask.m path of file: ./repos/bspm/thirdparty/bramila the code of the file until where you have to start completion: function mask = bramila_erodemask(mask,erodemask)
function mask = bramila_erodemask(mask,erodemask) % create voxel-free zone between two masks. Here the layer thickness is 1 % voxel, also counting diagonal neighbors. % INPUT: % mask = mask to be eroded (shrinks) % erodemask = mask used for eroding operation (not modified) % OUTPUT; % mask = eroded mask (unchanged if two masks are already far separated) MAX_NEAREST_NEIGHBORS = 0; siz=size(mask); x_max=siz(1); y_max=siz(2); z_max=siz(3); [xx,yy,zz]=ind2sub(size(mask),find(mask)); N=length(xx); for i=1:N x=(xx(i)-1):(xx(i)+1); y=(yy(i)-1):(yy(i)+1); z=(zz(i)-1):(zz(i)+1); x(x<1 | x>x_max)=[]; y(y<1 | y>y_max)=[]; z(z<1 | z>z_max)=[]; val = sum(sum(sum(erodemask(x,y,z)))); if val > MAX_NEAREST_NEIGHBORS % remove if too many voxels inside cube mask(xx(i),yy(i),zz(i))=0; end
520,340
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: AnalyzeGroup_FUN_GA_WU.m path of file: ./repos/BRAPH-2/braph2/pipelines/functional group_average the code of the file until where you have to start completion: classdef AnalyzeGroup_FUN_GA_WU < AnalyzeGroup %AnalyzeGroup_FUN_GA_WU is a graph analysis using averaged functional data. % It is a subclass of <a href="matlab:help AnalyzeGroup">AnalyzeGroup</a>. % % AnalyzeGroup_FUN_GA_WU uses functional data averaged over a group % and analyzes them using weighted undirected graphs. % % The list of AnalyzeGroup_FUN_GA_WU properties is: % <strong>1</strong> <strong>ELCLASS</strong> ELCLASS (constant, string) is the class of the % % % . % <strong>2</strong> <strong>NAME</strong> NAME (constant, string) is the name of the graph analysis with averaged functional data. % <strong>3</strong> <strong>DESCRIPTION</strong> DESCRIPTION (constant, string) is the description of the graph analysis with averaged functional data. % <strong>4</strong> <strong>TEMPLATE</strong> TEMPLATE (parameter, item) is the template of the graph analysis with averaged functional data. % <stron
function prop_description = getPropDescription(pointer) %GETPROPDESCRIPTION returns the description of a property. % % DESCRIPTION = Element.GETPROPDESCRIPTION(PROP) returns the % description of the property PROP. % % DESCRIPTION = Element.GETPROPDESCRIPTION(TAG) returns the % description of the property with tag TAG. % % Alternative forms to call this method are (POINTER = PROP or TAG): % DESCRIPTION = A.GETPROPDESCRIPTION(POINTER) returns description of POINTER of A. % DESCRIPTION = Element.GETPROPDESCRIPTION(AnalyzeGroup_FUN_GA_WU, POINTER) returns description of POINTER of AnalyzeGroup_FUN_GA_WU. % DESCRIPTION = A.GETPROPDESCRIPTION(AnalyzeGroup_FUN_GA_WU, POINTER) returns description of POINTER of AnalyzeGroup_FUN_GA_WU. % % Note that the Element.GETPROPDESCRIPTION(A) and Element.GETPROPDESCRIPTION('AnalyzeGroup_FUN_GA_WU') % are less computationally efficient. % % See also getPropProp, getPropTag, getPropCategory, % getPropFormat, getPropSettings, getPropDefault, checkProp. prop = AnalyzeGroup_FUN_GA_WU.getPropProp(pointer); %CET: Computational Efficiency Trick analyzegroup_fun_ga_wu_description_list = { 'ELCLASS (constant, string) is the class of the % % % .' 'NAME (constant, string) is the name of the graph analysis with averaged functional data.' 'DESCRIPTION (constant, string) is the description of the graph analysis with averaged functional data.' 'TEMPLATE (parameter, item) is the template of the graph analysis with averaged functional data.' 'ID (data, string) is a few-letter code for the graph analysis with averaged functional data.' 'LABEL (metadata, string) is an extend
661,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: validate.go path of file: ./repos/parca/gen/proto/go/parca/query/v1alpha1 the code of the file until where you have to start completion: // Copyright 2022-2024 The Parca Authors // Licensed under the Apache License, Version 2.0 (th
func (r ReportTypeRule) Validate(v interface{}) error { i, ok := v.(QueryRequest_ReportType) if !ok { return fmt.Errorf("report type is not a report type") } _, ok = QueryRequest_ReportType_name[int32(i)] if !ok { return fmt.Errorf("invalid report type") } return nil }
640,731
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: grid_justify_items_sized_center.rs path of file: ./repos/taffy/tests/generated/grid the code of the file until where you have to start completion: #[test] fn grid_justify_items_sized_cen
fn grid_justify_items_sized_center() { #[allow(unused_imports)] use taffy::{prelude::*, tree::Layout, TaffyTree}; let mut taffy: TaffyTree<crate::TextMeasure> = TaffyTree::new(); let node0 = taffy .new_leaf(taffy::style::Style { grid_row: taffy::geometry::Line { start: line(1i16), end: taffy::style::GridPlacement::Auto }, grid_column: taffy::geometry::Line { start: line(1i16), end: taffy::style::GridPlacement::Auto }, size: taffy::geometry::Size { width: taffy::style::Dimension::Length(20f32), height: taffy::style::Dimension::Length(20f32), }, ..Default::default() }) .unwrap(); let node1 = taffy .new_leaf(taffy::style::Style { grid_row: taffy::geometry::Line { start: line(3i16), end: taffy::style::GridPlacement::Auto }, grid_column: taffy::geometry::Line { start: line(3i16), end: taffy::style::GridPlacement::Auto }, size: taffy::geometry::Size { width: taffy::style::Dimension::Length(60f32), height: taffy::style::Dimension::Length(60f32), }, ..Default::default() }) .unwrap(); let node = taffy .new_with_children( taffy::style::Style { display: taffy::style::Display::Grid, justify_items: Some(taffy::style::JustifyItems::Center), grid_template_rows: vec![length(40f32), length(40f32), length(40f32)], grid_template_columns: vec![length(40f32), length(40f32), length(40f32)], size: taffy::geometry::Size { width: taffy::style::Dimension::Length(120f32), height: taffy::style::Dimension::Length(120f32), }, ..Default::default() }, &[node0, node1], ) .unwrap(); taffy.compute_layout_with_measure(node, taffy::geometry::Size::MAX_CONTENT, crate::test_measure_function).unwrap(); println!("\nComputed tree:"); taffy.print_tree(node); println!(); #[cfg_attr(not(feature = "content_size"), allow(unused_variables))] let layout @ Layout { size, location, .. } = taffy.layout(node).unwrap(); assert_eq!(size.width, 120f32, "width of node {:?}. Expected {}. Actual {}", node, 120f32, size.width); assert_eq!(size.height, 120f32, "height of node {:?}. Expected {}. Actual {}", node, 120f32, size.height); assert_eq!(location.x, 0f32, "x of node {:?}. Expected {}. Actual {}", node, 0f32, location.x); assert_eq!(location.y, 0f32, "y of node {:?}. Expected {}. Actual {}", node, 0f32, location.y); #[cfg(feature = "content_size")] assert_eq!( layout.scroll_width(), 10f32, "scroll_width of node {:?}. Expected {}. Actual {}", node, 10f32, layout.scroll_width() ); #[cfg(feature = "content_size")] assert_eq!( layout.scroll_height(), 20f32, "scroll_height of node {:?}. Expected {}. Actual {}", node, 20f32, layout.scroll_height() ); #[cfg_attr(not(feature = "content_size"), allow(unused_variables))] let layout @ Layout { size, location, .. } = taffy.layout(node0).unwrap(); assert_eq!(size.width, 20f32, "width of node {:?}. Expected {}. Actual {}", node0, 20f32, size.width); assert_eq!(size.height, 20f32, "height of node {:?}. Expected {}. Actual {}", node0, 20f32, size.height); assert_eq!(location.x, 10f32, "x of node {:?}. Expected {}. Actual {}", node0, 10f32, location.x); assert_eq!(location.y, 0f32, "y of node {:?}. Expected {}. Actual {}", node0, 0f32, location.y); #[cfg(feature = "content_size")] assert_eq!( layout.scroll_width(), 0f32, "scroll_width of node {:?}. Expected {}. Actual {}", node0, 0f32, layout.scroll_width() ); #[cfg(feature = "content_size")] assert_eq!( layout.scroll_height(), 0f32, "scroll_height of node {:?}. Expected {}. Actual {}", node0, 0f32, layout.scroll_height() ); #[cfg_attr(not(feature = "content_size"), allow(unused_variables))] let layout @ Layout { size, location, .. } = taffy.layout(node1).unwrap(); assert_eq!(size.width, 60f32, "width of node {:?}. Expected {}. Actual {}", node1, 60f32, size.width); assert_eq!(size.height, 60f32, "height of node {:?}. Expected {}. Actual {}", node1, 60f32, size.height); assert_eq!(location.x, 70f32, "x of node {:?}. Expected {}. Actual {}", node1, 70f32, location.x); assert_eq!(location.y, 80f32, "y of node {:?}. Expected {}. Actual {}", node1, 80f32, location.y); #[cfg(feature = "content_size")] assert_eq!( layout.scroll_width(), 0f32, "scroll_width of node {:?}. Expected {}. Actual {}", node1, 0f32, layout.scroll_width() ); #[cfg(feature = "content_size")] assert_eq!( layout.scroll_height(), 0f32, "scroll_height of node {:?}. Expected {}. Actual {}", node1, 0f32, layout.scroll_height() ); }
485,154
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: order_book.rb path of file: ./repos/cryptoexchange/lib/cryptoexchange/exchanges/bitsten/services the code of the file until where you have to start completion: module Cryptoexchange::Exchanges
def adapt_orders(orders) orders.collect do |order_entry| Cryptoexchange::Models::Order.new(price: order_entry['price'], amount: order_entry['amount'], timestamp: nil) end end
644,107
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: exif_A300_file_source.go path of file: ./repos/gotosocial/vendor/github.com/dsoprea/go-exif/v3/undefined the code of the file until where you have to start completion: package exifundefined import ( "fmt" "encoding/binary" "github.com/dsoprea/go-logging" "github.com/dsoprea/go-exif/v3/common" ) type TagExifA300FileSource uint32 func (TagExifA300FileSource) EncoderName() string { return "CodecExifA300FileSource" } func (af
func (CodecExifA300FileSource) Decode(valueContext *exifcommon.ValueContext) (value EncodeableValue, err error) { defer func() { if state := recover(); state != nil { err = log.Wrap(state.(error)) } }() valueContext.SetUndefinedValueType(exifcommon.TypeLong) valueLongs, err := valueContext.ReadLongs() log.PanicIf(err) return TagExifA300FileSource(valueLongs[0]), nil }
25,634
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: factory.go path of file: ./repos/milvus/internal/storage the code of the file until where you have to start completion: package storage import ( "context" "github.com/cockroachdb/errors" "github.com/milvus-io/milvus/pkg/util/paramtable"
func (f *ChunkManagerFactory) newChunkManager(ctx context.Context, engine string) (ChunkManager, error) { switch engine { case "local": return NewLocalChunkManager(RootPath(f.config.rootPath)), nil case "minio", "opendal": return newMinioChunkManagerWithConfig(ctx, f.config) case "remote": return NewRemoteChunkManager(ctx, f.config) default: return nil, errors.New("no chunk manager implemented with engine: " + engine) } }
13,934
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: lock_test.go path of file: ./repos/restic/cmd/restic the code of the file until where you have to start completion: package main import ( "context" "fmt" "runtime" "strings" "sync" "testing" "time" "github.com/r
func TestLockUnlockAll(t *testing.T) { repo, cleanup, env := openLockTestRepo(t, nil) defer cleanup() lock, wrappedCtx := checkedLockRepo(context.Background(), t, repo, env) _, err := unlockAll(0) test.OK(t, err) if wrappedCtx.Err() == nil { t.Fatal("canceled parent context did not cancel context") } // unlockRepo should not crash unlockRepo(lock) }
533,882
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: rate_limit.rb path of file: ./repos/forem/app/lib/constants/settings the code of the file until where you have to start completion: module Constants modu
def self.details { spam_trigger_terms: { description: I18n.t("lib.constants.settings.rate_limit.spam.description"), placeholder: I18n.t("lib.constants.settings.rate_limit.spam.placeholder") }, user_considered_new_days: { description: I18n.t("lib.constants.settings.rate_limit.new_days.description"), placeholder: ::Settings::RateLimit.user_considered_new_days } } end
627,515
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: querying_examples.rb path of file: ./repos/mobility/spec/support/shared_examples the code of the file until where you have to start completion: shared_examples_for "AR Model with translated scope" do |model_class_name, a1=:title, a2=:content| let(:backend) { model_class.ancestors.grep(Mobility::Translations).first.backend } let(:model_class) { model_class_name.constantize } let(:query_scope) { model_class.i18n } let(:ordered_results) { query_scope.order("#{model_class.table_name}.id asc") } describe ".where" do context "querying on one translated attribute" do before do @instance1 = model_class.create(a1 => "foo") @instance2 = model_class.create(a1 => "bar") @instance3 = model_class.create(a1 => "baz", published: true) @instance4 = model_class.create(a1 => "baz", published: false) @instance5 = model_class.create(a1 => "foo", published: true) end it "returns correct result searching on unique attribute value" do expect(query_scope.where(a1 => "bar")).to eq([@instance2]) end it "returns correct results when query matches multiple records" do expect(query_scope.where(a1 => "foo")).to match_array([@instance1, @instance5]) end it "returns correct result when querying on translated and untranslated attributes" do expect(query_scope.where(a1 => "baz", published: true)).to eq([@instance3]) end it "returns correct result when querying on nil values" do instance = model_class.create(a1 => nil) expect(query_scope.where(a1 => nil)).to eq([instance]) end context "with content in different locales" do before do Mobility.with_locale(:ja) do @ja_instance1 = model_class.create(a1 => "foo ja") @ja_instance2 = model_class.create(a1 => "foo") end end it "returns correct result when querying on same attribute value in different locale" do expect(query_scope.where(a1 => "foo")).to match_array([@instance1, @instance5]) Mobility.with_locale(:ja) do expect(query_scope.where(a1 => "foo ja")).to eq([@ja_instance1]) expect(query_scope.where(a1 => "foo")).to eq([@ja_instance2]) end end it "returns correct result when querying with locale option" do expect(query_scope.where(a1 => "foo", locale: :en)).to match_array([@instance1, @instance5]) expect(query_scope.where(a1 => "foo ja", locale: :ja)).to eq([@ja_instance1]) expect(query_scope.where(a1 => "foo", locale: :ja)).to eq([@ja_instance2]) end it "returns correct result when querying with locale option twice in separate clauses" do @ja_instance1.update(a1 => "foo en") expect(query_scope.where(a1 => "foo ja", locale: :ja).where(a1 => "foo en", locale: :en)).to eq([@ja_instance1]) expect(query_scope.where(a1 => "foo", locale: :ja).where(a1 => nil, locale: :en)).to eq([@ja_instance2]) end end context "with exists?" do it "returns correct result searching on unique attribute value" do aggregate_failures do expect(query_scope.where(a1 => "bar").exists?).to eq(true) expect(query_scope.where(a1 => "aaa").exists?).to eq(false) end end end end context "with two translated attributes" do before do @instance1 = model_class.create(a1 => "foo" ) @instance2 = model_class.create(a1 => "foo", a2 => "foo content" ) @instance3 = model_class.create(a1 => "foo", a2 => "foo content", published: false) @instance4 = model_class.create( a2 => "foo content" ) @instance5 = model_class.create(a1 => "bar", a2 => "bar content" ) @instance6 = model_class.create(a1 => "bar", published: true ) end # @note Regression spec it "does not modify scope in-place" do query_scope.where(a1 => "foo") expect(query_scope.to_sql).to eq(model_class.all.to_sql) end it "returns correct results querying on one attribute" do expect(query_scope.where(a1 => "foo")).to match_array([@instance1, @instance2, @instance3]) expect(query_scope.where(a2 => "foo content")).to match_array([@instance2, @instance3, @instance4]) end it "returns correct results querying on two attributes in single where call" do expect(query_scope.where(a1 => "foo", a2 => "foo content")).to match_array([@instance2, @instance3]) end it "returns correct results querying on two attributes in separate where calls" do expect(query_scope.where(a1 => "foo").where(a2 => "foo content")).to match_array([@instance2, @instance3]) end it "returns correct result querying on two translated attributes and untranslated attribute" do expect(query_scope.where(a1 => "foo", a2 => "foo content", published: false)).to eq([@instance3]) end it "works with nil values" do expect(query_scope.where(a1 => "foo", a2 => nil)).to eq([@instance1]) expect(query_scope.where(a1 => "foo").where(a2 => nil)).to eq([@instance1]) instance = model_class.create
def query(*args, **kwargs, &block); model_class.i18n(*args, **kwargs, &block); end context "single-block querying" do let!(:i) { [ model_class.create(a1 => "foo" ), model_class.create( ), model_class.create( a2 => "bar"), model_class.create( a2 => "foo"), model_class.create(a1 => "bar" ), model_class.create(a1 => "foo", a2 => "bar"), model_class.create(a1 => "foo", a2 => "baz") ] } describe "equality" do it "handles (a EQ 'foo')" do expect(query { __send__(a1).eq("foo") }).to match_array([i[0], *i[5..6]]) end it "handles (a EQ NULL)" do expect(query { __send__(a1).eq(nil) }).to match_array(i[1..3]) end it "handles (a EQ b)" do matching = [ model_class.create(a1 => "foo", a2 => "foo"), model_class.create(a1 => "bar", a2 => "bar") ] expect(query { __send__(a1).eq(__send__(a2)) }).to match_array(matching) end context "with locale option" do it "handles (a EQ 'foo')" do post1 = model_class.new(a1 => "foo en", a2 => "bar en") Mobility.with_locale(:ja) do post1.send("#{a1}=", "foo ja") post1.send("#{a2}=", "bar ja") end post1.save post2 = model_class.new(a1 => "baz en") Mobility.with_locale(:'pt-BR') { post2.send("#{a1}=", "baz pt-br") } post2.save expect(query(locale: :en) { __send__(a1).eq("foo en") }).to match_array([post1]) expect(query(locale: :en) { __send__(a2).eq("bar en") }).to match_array([post1]) expect(query(locale: :ja) { __send__(a1).eq("foo ja") }).to match_array([post1]) expect(query(locale: :ja) { __send__(a2).eq("bar ja") }).to match_array([post1]) expect(query(locale: :en) { __send__(a1).eq("baz en") }).to match_array([post2]) expect(query(locale: :'pt-BR') { __send__(a1).eq("baz pt-br") }).to match_array([post2]) end end end describe "not equal" do it "handles (a NOT EQ 'foo')" do expect(query { __send__(a1).not_eq("foo") }).to match_array([i[4]]) end it "handles (a NOT EQ NULL)" do expect(query { __send__(a1).not_eq(nil) }).to match_array([i[0], *i[4..6]]) end context "with AND" do it "handles ((a NOT EQ NULL) AND (b NOT EQ NULL))" do expect(query { __send__(a1).not_eq(nil).and(__send__(a2).not_eq(nil)) }).to match_array(i[5..6]) end end context "with OR" do it "handles ((a NOT EQ NULL) OR (b NOT EQ NULL))" do expect(query { __send__(a1).not_eq(nil).or(__send__(a2).not_eq(nil)) }).to match_array([i[0], *i[2..6]]) end end end describe "AND" do it "handles (a AND b)" do expect(query { __send__(a1).eq("foo").and(__send__(a2).eq("bar")) }).to match_array([i[5]]) end it "handles (a AND b), where a is NULL-valued" do expect(query { __send__(a1).eq(nil).and(__send__(a2).eq("bar")) }).to match_array([i[2]]) end it "handles (a AND b), where both a and b are NULL-valued" do expect(query { __send__(a1).eq(nil).and(__send__(a2).eq(nil)) }).to match_array([i[1]]) end end describe "OR" do it "handles (a OR b) on same attribute" do expect(query { __send__(a1).eq("foo").or(__send__(a1).eq("bar")) }).to match_array([i[0], *i[4..6]]) end it "handles (a OR b) on same attribute, where a is NULL-valued" do expect(query { __send__(a1).eq(nil).or(__send__(a1).eq("foo")) }).to match_array([*i[0..3], *i[5..6]]) end it "handles (a OR b) on two attributes" do expect(query { __send__(a1).eq("foo").or(__send__(a2).eq("bar")) }).to match_array([i[0], i[2], *i[5..6]]) end it "handles (a OR b) on two attributes, where a is NULL-valued" do expect(query { __send__(a1).eq(nil).or(__send__(a2).eq("bar")) }).to match_array([*i[1..2], i[3], i[5]]) end it "handles (a OR b) on two attributes, where both a and b are NULL-valued" do expect(query { __send__(a1).eq(nil).or(__send__(a2).eq(nil)) }).to match_array(i[0..4]) end end describe "combination of AND and OR" do it "handles a AND (b OR c)" do expect(query { __send__(a1).eq("foo").and( __send__(a2).eq("bar").or(__send__(a2).eq("baz"))) }).to match_array(i[5..6]) end it "handles a AND (b OR c), where c is NULL-valued" do expect(query { __send__(a1).eq("foo").and( __send__(a2).eq("bar").or(__send__(a2).eq(nil))) }).to match_array([i[0], i[5]]) end it "handles (a AND b) OR (c AND d), where b and d are NULL-valued" do expect(query { __send__(a1).eq("foo").or(__send__(a1).eq(nil)).and( __send__(a2).eq("baz").or(__send__(a2).eq(nil))) }).to match_array([*i[0..1], i[6]]) end end describe "LIKE/ILIKE (matches)" do it "includes partial string matches" do foobar = model_class.create(a1 => "foObar") barfoo = model_class.create(a1 => "barfOo") expect(query { __send__(a1).matches("foo%") }).to match_array([i[0], *i[5..6], foobar]) expect(query { __send__(a1).matches("%foo") }).to match_array([i[0], *i[5..6], barfoo]) end if ENV['DB'] == 'postgres' && ::ActiveRecord::VERSION::STRING >= '5.0' it "works with case_sensitive option" do foobar = model_class.create(a1 => "foObar") barfoo = model_class.create(a1 => "barfOo") expect(query { __send__(a1).matches("foo%", nil, true) }).not_to include(foobar) expect(query { __send__(a1).matches("foO%", nil, true) }).to include(foobar) expect(query { __send__(a1).matches("%foo", nil, true) }).not_to include(barfoo) expect(query { __send__(a1).matches("%fOo", nil, true) }).to include(barfoo) end end end describe "LOWER" do it "matches lowercase string values" do foobar = model_class.create(a1 => "foObar") expect(query { __send__(a1).lower.eq("foobar") }).to match_array([foobar]) end end end
17,137
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: comment_lock_policy.rb path of file: ./repos/open-build-service/src/api/app/policies the code of the file until where you have to start completion: class CommentLockPolicy < ApplicationPolicy def create? return false unless Flipper.enabled?(:content_moderation, user) return t
def create? return false unless Flipper.enabled?(:content_moderation, user) return true if user.is_moderator? || user.is_admin? case record # Maintainers of Package or Project can lock comments when Package, Project return record.maintainers.include?(user) # Request receivers (maintainers of target package) can also lock comments when BsRequest return record.is_target_maintainer?(user) when BsRequestAction return record.bs_request.is_target_maintainer?(user) end
734,950
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: e12_pairing.go path of file: ./repos/gnark/std/algebra/native/fields_bls12377 the code of the file until where you have to start completion: package fields_bls12377 import "github.com/consensys/gnark/frontend" // nSquareKarabina2345 repeated compressed cyclotmic square func (e *E12) nSquareKarabina2345(api frontend.API, n int) { for i := 0; i < n; i++
func Mul01234By034(api frontend.API, x [5]E2, z3, z4 E2) *E12 { var a, b, z1, z0, one E6 var zero E2 zero.SetZero() one.SetOne() c0 := &E6{B0: x[0], B1: x[1], B2: x[2]} c1 := &E6{B0: x[3], B1: x[4], B2: zero} a.Add(api, one, E6{B0: z3, B1: z4, B2: zero}) b.Add(api, *c0, *c1) a.Mul(api, a, b) c := *Mul01By01(api, z3, z4, x[3], x[4]) z1.Sub(api, a, *c0) z1.Sub(api, z1, c) z0.MulByNonResidue(api, c) z0.Add(api, z0, *c0) return &E12{ C0: z0, C1: z1, } }
76,947
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: wizard.rb path of file: ./repos/quik/lib/quik the code of the file until where you have to start completion: # encoding: utf-8 ## note: ## use global $QUIK_WIZARD_STDIN ## lets you redirect stdin for testing e.g $QUIK_WIZARD_STDIN = StringIO.new( 'test/n' ) $QUIK_WIZARD_IN = $stdin module Quik module Wizard ## use a different name e.g. WizardHelpers, Form
def yes?( question ) ## defaults to yes - why, why not?? ## todo: strip trailing question mark (?) if present (gets auto-included) print( "Q: #{question} (y/n)? [y]: " ) str = getstr if str.empty? || str =~ YES_REGEX true elsif str =~ NO_REGEX false else ## warn: unknown value?? true end
594,157
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: errmissingkustomization.go path of file: ./repos/kubernetes/vendor/sigs.k8s.io/kustomize/api/internal/target the code of the file until where you have to start completion: // Copyright 2019 The Kubernetes Authors. // SPDX-License-Identifier: Apache-2.0 packa
func quoted(l []string) []string { r := make([]string, len(l)) for i, v := range l { r[i] = "'" + v + "'" } return r }
355,128
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: privilege_escalation_check.rb path of file: ./repos/API-fuzzer/lib/API_Fuzzer the code of the file until where you have to start completion: require 'API_Fuzzer/vulnerability' require 'API_Fuzzer/error' require 'API_Fuzzer/request' module API_Fuzzer class PrivilegeEscalationCheck class << self def scan(options = {}) @url =
def fuzz_privileges id = /\A\d+\z/ uri = URI(@url) path = uri.path query = uri.query url = @url base_uri = query.nil? ? path : [path, query].join("?") fragments = base_uri.split(/[\/,?,&]/) - [''] fragments.each do |fragment| if fragment.match(/\A(\w)+=(\w)*\z/) key, value = fragment.split("=") if value.match(id) value = value.to_i value += 1 url = url.gsub(fragment, [key, value].join("=")).chomp fuzz_identity(url, @params) end elsif fragment.match(id) value = fragment.to_i value += 1 url = url.gsub(fragment, value.to_s).chomp if url fuzz_identity(url, @params, url) end
241,300
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: SetBrushSize.m path of file: ./repos/ImageM/ImageM/+imagem/+actions/+image the code of the file until where you have to start completion: classdef SetBrushSize < imagem.gui.Action % Change the size of the brush. % % Class SetBrushSizeAction % % Example % SetBrushSizeAction % % See also % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2011-12-15,
function run(obj, frame) %#ok<INUSL,INUSD> disp('set brush size'); answer = inputdlg(... 'Enter the brush size (in pixels):', ... 'Input Brush size', ... 1, {num2str(frame.Gui.App.BrushSize)}); if isempty(answer) return; end
676,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: typesetter.go path of file: ./repos/kubeedge/vendor/k8s.io/cli-runtime/pkg/printers the code of the file until where you have to start completion: /* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not
func (p *TypeSetterPrinter) ToPrinter(delegate ResourcePrinter) ResourcePrinter { if p == nil { return delegate } p.Delegate = delegate return p }
416,980
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tag.rb path of file: ./repos/moebooru/app/models the code of the file until where you have to start completion: class Tag < ApplicationRecord include Tag::TypeMethods include Tag::CacheMethods include Tag::RelatedTagMethods
def self.count_by_period(start, stop, options = {}) options[:limit] ||= 50 options[:exclude_types] ||= [] tag_types_to_show = TAG_TYPE_INDEXES - options[:exclude_types] Tag.group(:name).joins(:_posts) .where(posts: { created_at: start..stop }, tag_type: tag_types_to_show) .order("count_all DESC").limit(options[:limit]) .count .map { |name, count| { "post_count" => count, "name" => name } } end
511,489
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: service.go path of file: ./repos/tegola/vendor/github.com/aws/aws-sdk-go/service/sts the code of the file until where you have to start completion: // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sts import ( "github.com/aws/aws-sdk-go/aws" "githu
func (c *STS) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
95,542
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: block.go path of file: ./repos/markdown/parser the code of the file until where you have to start completion: package parser import ( "bytes" "html" "regexp" "st
func (p *Parser) quotePrefix(data []byte) int { i := 0 n := len(data) for i < 3 && i < n && data[i] == ' ' { i++ } if i < n && data[i] == '>' { if i+1 < n && data[i+1] == ' ' { return i + 2 } return i + 1 } return 0 }
512,606
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: utf32_test.go path of file: ./repos/gitkube/vendor/golang.org/x/text/encoding/unicode/utf32 the code of the file until where you have to start completion: // Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package utf32 import ( "testing" "golang.org/x/text/encoding" "golang.org/x/text/encoding/internal/enctest" "golang.org/x/text/transform" ) var ( utf32LEIB = UTF32(LittleEndian, IgnoreBOM) // UTF-32LE (atypical interpretation) utf32LEUB = UTF32(LittleEndian, UseBOM) // UTF-32, LE // utf32LEEB = UTF32(LittleEndian, ExpectBOM) // UTF-32, LE, Expect - covered in encoding_test.go utf32BEIB = UTF32(BigEndian, IgnoreBOM) // UTF-32BE (atypical interpretation) utf32BEUB = UTF32(BigEndian, UseBOM) // UTF-32 default utf32BEEB = UTF32(BigEndian, ExpectBOM) // UTF-32 Expect ) func TestBasics(t *testing.T) { testCases := []struc
func TestBasics(t *testing.T) { testCases := []struct { e encoding.Encoding encPrefix string encSuffix string encoded string utf8 string }{{ e: utf32BEIB, encoded: "\x00\x00\x00\x57\x00\x00\x00\xe4\x00\x01\xd5\x65", utf8: "\x57\u00e4\U0001d565", }, { e: UTF32(BigEndian, ExpectBOM), encPrefix: "\x00\x00\xfe\xff", encoded: "\x00\x00\x00\x57\x00\x00\x00\xe4\x00\x01\xd5\x65", utf8: "\x57\u00e4\U0001d565", }, { e: UTF32(LittleEndian, IgnoreBOM), encoded: "\x57\x00\x00\x00\xe4\x00\x00\x00\x65\xd5\x01\x00", utf8: "\x57\u00e4\U0001d565", }, { e: UTF32(LittleEndian, ExpectBOM), encPrefix: "\xff\xfe\x00\x00", encoded: "\x57\x00\x00\x00\xe4\x00\x00\x00\x65\xd5\x01\x00", utf8: "\x57\u00e4\U0001d565", }} for _, tc := range testCases { enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, tc.encPrefix, tc.encSuffix) } }
508,563
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: goversion_makemap_unsafe_gte_go110.go path of file: ./repos/podman/vendor/github.com/ugorji/go/codec the code of the file until where you have to start completion: // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved. // Use of this source code is governed by a MIT licen
func makeMapReflect(typ reflect.Type, size int) (rv reflect.Value) { t := (*unsafeIntf)(unsafe.Pointer(&typ)).ptr urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) urv.typ = t urv.flag = uintptr(reflect.Map) urv.ptr = makemap(t, size, nil) return }
103,674
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: event.rs path of file: ./repos/conrod/conrod_core/src the code of the file until where you have to start completion: //! Contains all types used to describe the input events that `Widget`s may handle. //! //! The two primary types of this module are: //! //! - `Input`: conrod's input type passed by the user to `Ui::handle_event` in order to drive the //! `Ui`. //!
pub fn relative_to(&self, xy: Point) -> Motion { let motion = match self.motion { input::Motion::MouseCursor { x, y } => input::Motion::MouseCursor { x: x - xy[0], y: y - xy[1], }, motion => motion, }; Motion { motion: motion, ..*self } }
373,002
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: encryption.rs path of file: ./repos/librevault/src/common-rs/src the code of the file until where you have to start completion: use crate::proto::meta::{EncryptedData, EncryptionMetadata}; use aes_gcm_siv::aead::{Aead, NewAead}; use aes_gcm_siv::{Aes256GcmSiv, Key, Nonce}; use r
pub fn decrypt(data: &EncryptedData, key: &[u8]) -> Option<Vec<u8>> { let metadata = data.metadata.as_ref()?; let key = Key::from_slice(key); let cipher = Aes256GcmSiv::new(key); let nonce = Nonce::from_slice(metadata.iv.as_slice()); cipher.decrypt(nonce, &*data.ciphertext).ok() }
158,418
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: auditor_spec.rb path of file: ./repos/audited/spec/audited the code of the file until where you have to start completion: require "spec_helper" # not testing proxy_
def stub_global_max_audits(max_audits) previous_max_audits = Audited.max_audits previous_user_audited_options = Models::ActiveRecord::User.audited_options.dup begin Audited.max_audits = max_audits Models::ActiveRecord::User.send(:normalize_audited_options) # reloads audited_options yield ensure Audited.max_audits = previous_max_audits Models::ActiveRecord::User.audited_options = previous_user_audited_options end
22,935
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: create_contract.rs path of file: ./repos/solang/tests/solana_tests the code of the file until where you have to start completion: // SPDX-License-Identifier: Apache-2.0 use crate::{ account_new, build_solidity, create_program_address, Account, AccountState, BorshToken, }; use base58::{FromBase58, ToBase58}; use num_bigint::BigInt; #[tes
fn account_too_small() { let mut vm = build_solidity( r#" contract bar { int[200] foo1; }"#, ); let data_account = vm.initialize_data_account(); vm.account_data .get_mut(&data_account) .unwrap() .data .truncate(100); vm.function("new") .accounts(vec![("dataAccount", data_account)]) .expected(5 << 32) .call(); }
539,553
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: string-codec_test.go path of file: ./repos/go-flutter/plugin the code of the file until where you have to start completion: package plugin import ( "testing" "github.com/stretchr/testify/assert" ) func TestStringEncodeDecode(t *testing.T) { values := []interface{}{ nil, "", "hello", "
func TestStringEncodeDecode(t *testing.T) { values := []interface{}{ nil, "", "hello", "special chars >☺😂<", } codec := StringCodec{} for _, v := range values { data, err := codec.EncodeMessage(v) if err != nil { t.Fatal(err) } v2, err := codec.DecodeMessage(data) if err != nil { t.Fatal(err) } assert.Equal(t, v, v2) } }
348,671
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: hamming.go path of file: ./repos/teller/vendor/github.com/xrash/smetrics the code of the file until where you have to start completion: package smetrics import ( "fmt" ) // The Hamming distance is the minimum number of substitutions required to change string A into string B. Both strings must have the same size. If the strings have different sizes, the function
func Hamming(a, b string) (int, error) { al := len(a) bl := len(b) if al != bl { return -1, fmt.Errorf("strings are not equal (len(a)=%d, len(b)=%d)", al, bl) } var difference = 0 for i := range a { if a[i] != b[i] { difference = difference + 1 } } return difference, nil }
526,479
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ioctl_linux.go path of file: ./repos/wgnetwork/vendor/github.com/vishvananda/netlink the code of the file until where you have to start completion: package netlink import ( "syscall" "unsafe" "golang.org/x/sys/unix" ) // ioctl for
func newIocltStringSetReq(linkName string) (*Ifreq, *ethtoolSset) { e := &ethtoolSset{ cmd: ETHTOOL_GSSET_INFO, mask: 1 << ETH_SS_STATS, } ifreq := &Ifreq{Data: uintptr(unsafe.Pointer(e))} copy(ifreq.Name[:unix.IFNAMSIZ-1], linkName) return ifreq, e }
427,282
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _review_template_answer_summary.rs path of file: ./repos/aws-sdk-rust/sdk/wellarchitected/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>The summary of review template answers.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct ReviewTemplateAnswerSummary { /// <p>The ID of the question.</p> pub question_id: ::std::option::Option<::std::string::String>, /// <p>The ID used to identify a
pub fn build(self) -> crate::types::ReviewTemplateAnswerSummary { crate::types::ReviewTemplateAnswerSummary { question_id: self.question_id, pillar_id: self.pillar_id, question_title: self.question_title, choices: self.choices, selected_choices: self.selected_choices, choice_answer_summaries: self.choice_answer_summaries, is_applicable: self.is_applicable, answer_status: self.answer_status, reason: self.reason, question_type: self.question_type, } }
806,980
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: properties.rb path of file: ./repos/nii/nii-core/lib/nii/formats the code of the file until where you have to start completion: # frozen_string_literal: true module Nii::Formats # Both Java .properties and Mozilla .properties
def compile(bundle, source, **options) Nii::Parser.properties(source).each do |key, value| template = message_format.compile(bundle, value) message = Nii::Message.new(key, template) bundle.add(message, **options) end end
78,002