text
string
label_name
string
labels
int64
ffsets(&input); assert_eq!(1068781, find_first_contiguous_time(&parse)); } #[test] fn test_gcd() { assert_eq!((-9,2), bezout_coefficients(15, 69)); assert_eq!((2,-1), bezout_coefficients(7, 13)); assert_eq!((1,19), bezout_coefficients(77, -4)); assert_eq!((1,-3), bezout_coefficients(-14, -4...
Rust
0
_apdu::{APDUAnswer, APDUCommand, APDUErrorCodes}; /// APDU Errors pub mod errors; #[cfg(target_arch = "wasm32")] /// APDU Transport wrapper for JS/WASM transports pub mod apdu_transport_wasm; #[cfg(target_arch = "wasm32")] pub use crate::apdu_transport_wasm::{APDUTransport, TransportWrapperTrait}; #[cfg(not(target_...
Rust
0
N> where T: core::simd::SimdElement + Pod, core::simd::LaneCount<N>: core::simd::SupportedLaneCount, { } <reponame>strangemoodfoundation/solana-program-library<gh_stars>1-10 //! Solana Farm Client RefDB Instructions use { crate::error::FarmClientError, solana_farm_sdk::{ farm::Farm, id::{ma...
Rust
0
_alternate(), //tx pa2 for GPS rx gpioa.pa3.into_alternate(), ), //rx pa3 for GPS tx Config::default().baudrate(9600.bps()), &clocks, ) .unwrap() .split(); let gpiob = p.GPIOB.split(); // can have (scl, sda) using I2C1 on (PB8 _af4, PB9 _af4) or on (PB6 _af...
Rust
0
AttachArguments::new(init_arguments.version()), /// |token: NoException| { /// unsafe { token.env().raw_env() }; /// ((), token) /// }, /// ); /// # } /// # /// # #[cfg(not(feature = "libjvm"))] /// # fn main() {} /// ``` /// The method also provides a [`NoException`](struct.NoException.html) to...
Rust
0
f): sheet = tool.GFX[c.BIRD_SHEET] frame_rect_list = [(141, 443, 85, 85), (228, 441, 85, 85), (313, 438, 85, 85), (400, 439, 85, 85), (564, 439, 85, 85)] self.frames = self.load_frames(sheet, frame_rect_list, c.BIRD_MULTIPLIER) def attacking(self, level, mouse_pre...
Python
1
ationTimeInPast); } #[test] fn test_update_at_case_11() { // Given value and next value with activation_time in future. let (_, mut contract) = setup_with(KEY, VALUE); contract .update_at(KEY, VALUE_2, Some(AT_DAY_THREE)) .unwrap(); // When update_at with activation_time in future. ...
Rust
0
import os import shutil prepend = 'PATH_TO_SCENEFLOW/SceneFlow/FlyingThings3D/frame_finalpass' unused_dir = os.path.join(prepend, 'UNUSED') if not os.path.isdir(unused_dir): os.mkdir(unused_dir) if not os.path.isdir(os.path.join(unused_dir, 'TRAIN')): os.mkdir(os.path.join(unused_dir, 'TRAIN')) if not os.path....
Python
1
to_sexpr)); }, grit::Op::AllocClos(ref var_closs) => { list = vec![ident("alloc-clos")]; list.extend(var_closs.iter().map(|&(ref var, ref fun_name, ref captures)| { let mut list =vec![var_to_sexpr(var), fun_name_to_sexpr(fun_name)]; list.extend(captures.iter().map(val_to_sexpr));...
Rust
0
e", ], [ "ノーズユラン県", "North Jutland", "Nord-Jütland", "Jutland du nord", "Distrito de Jutlandia Septentrional", "Jutland Settentrionale", "Noord-Jutland", ], [ "デンマーク", "Denmark", "Dänemark", "Danemark", "Dina...
Python
1
ormalize_text) heat_df = heat_source.merge(mun_aux[["_key", lat_mun, lon_mun, "nome_mun", "uf"]], on="_key", how="left").dropna(subset=[lat_mun, lon_mun]) tooltip = {"html": f"<b>Município:</b> {{nome_mun}} {{uf}}<br/><b>{heat_label}:</b> {{weight}}"} lon_col, lat_col = lon_mun, lat_mun else...
Python
1
game.do_move(); } while game.cups[0] != 1 { game.cups.rotate_left(1); } game.cups .into_iter() .skip(1) .map(|d| d.to_string()) .collect() } struct Cup { value: u64, next: Option<Rc<RefCell<Cup>>>, } impl Cup { fn new(va...
Rust
0
HardcodedError::NoAnswer => sink.write_all(b"NO ANSWER"), HardcodedError::Delayed => sink.write_all(b"DELAYED"), HardcodedError::Blacklist => sink.write_all(b"BLACKLIST"), } } } <gh_stars>0 mod identity; use identity::TestApp; use serde_json::{json, Value}; use tankersdk::*; #[t...
Rust
0
import pytest from conftest import mock_fetch_cls import micropip @pytest.mark.asyncio async def test_list_pypi_package(mock_fetch: mock_fetch_cls) -> None: dummy = "dummy" mock_fetch.add_pkg_version(dummy) await micropip.install(dummy) pkg_list = micropip.list() assert dummy in pkg_list ass...
Python
1
), ] .iter() .cloned() .collect(), ), ] } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum AddressType { Version, XPosition, YPosition, ZPosition, XLookAt, YLookAt, ZLookAt, // TODO: Work out a more sensible...
Rust
0
) -> ::std::os::raw::c_int; } extern "C" { pub fn Fl_message_title(title: *const ::std::os::raw::c_char); } extern "C" { pub fn Fl_message_title_default(title: *const ::std::os::raw::c_char); } <filename>tokio/src/runtime/spawner.rs cfg_rt! { use crate::runtime::basic_scheduler; use crate::task::JoinHa...
Rust
0
<= 3 { get_or_calc(mem, input, idx + 3) } else { 0 }; a + b + c } else if idx == input.len() - 3 { let a = if input[idx + 1] - input[idx] <= 3 { get_or_calc(mem, input, idx + 1) } else { 0 }; let b = if input[idx + 2] - input[idx] <= 3 { get_or_calc(mem, input, idx + 2) } else { 0 ...
Rust
0
# ----------------------------------------------------------------------------- # Configuration file for the Sphinx documentation builder. # For the full list of built-in configuration values, see: # https://www.sphinx-doc.org/en/master/usage/configuration.html # # SPDX-License-Identifier: Apache-2.0 # ----------------...
Python
1
wSize: u32, pub lpDDCallbacks: *mut DDHAL_DDCALLBACKS, pub lpDDSurfaceCallbacks: *mut DDHAL_DDSURFACECALLBACKS, pub lpDDPaletteCallbacks: *mut DDHAL_DDPALETTECALLBACKS, pub vmiData: VIDMEMINFO, pub ddCaps: DDCORECAPS, pub dwMonitorFrequency: u32, pub GetDriverInfo: LPDDHAL_GETDRIVERINFO, ...
Rust
0
from prowler.lib.check.models import Check, Check_Report_GCP from prowler.providers.gcp.services.compute.compute_client import compute_client class compute_instance_shielded_vm_enabled(Check): def execute(self) -> Check_Report_GCP: findings = [] for instance in compute_client.instances: ...
Python
1
&[Panel]) -> u32 { panels.iter().fold(0, |acc, panel| { let mut digits = [0; 10]; // Known digits. digits[1] = panel.signals[0]; digits[7] = panel.signals[1]; digits[4] = panel.signals[2]; digits[8] = panel.signals[9]; // Numbers with 5 segments let...
Rust
0
close = ConnectionClose { reply_code: u16::from(REPLY_SUCCESS), reply_text: "goodbye".to_string(), class_id: 0, method_id: 0, }; self.handle.call_connection_close(close).map(|_| ()) } pub(crate) fn open_channel(&mut self, channel_id: Option<u16>)...
Rust
0
t rng = &mut thread_rng(); let params = Bn256RescueParams::new_2_into_1::<BlakeHasher>(); let input: Vec<Fr> = (0..params.rate()).map(|_| rng.gen()).collect(); let output = rescue_hash::<Bn256>(&params, &input[..]); assert!(output.len() == 1); } #[test] fn output_bn256_rescu...
Rust
0
e1 ).unwrap(); let result1 = cql_db::read_value::<U64>( DATABASE_LOCATION, &point1 ).unwrap(); assert_eq!(result1, value1); } #[test] #[serial] fn _2d_u64_database_allows_for_first_item_to_be_written_checked() { let point1 = [1, 1]; let value1 = 42; cql_db::create_db_unch...
Rust
0
class Restaurant: def __init__(self, restaurant_name, cuisine_type): # Initialize the restaurant's name and cuisine type self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): # Method to describe the restaurant print(f"Res...
Python
1
<'ducc>, A: ToValues<'ducc>, R: FromValue<'ducc>, { let value: Value = self.get(key)?; if let Some(func) = value.as_function() { func.call_method(self.clone(), args) } else { Err(Error::not_a_function()) } } /// Returns an iterator ove...
Rust
0
return att_ws def calculate_all_ctc_probs(self, xs_pad, ilens, ys_pad): """E2E CTC probability calculation. :param torch.Tensor xs_pad: batch of padded input sequences (B, Tmax) :param torch.Tensor ilens: batch of lengths of input sequences (B) :param torch.Tensor ys_pad: batch of ...
Python
1
r'^(添加|add).*$', r'^(移除|remove).*$', r'^(更新|update).*$', r'^(清理|clean).*$', r'^(保存|save).*$', r'^(加载|load).*$', r'^(监听|listen).*$', r'^(回退|fallback).*$', r'^(优先|prefer).*$', ...
Python
1
NM_SETTING_WIRELESS_SECURITY_LEAP_PASSWORD_FLAGS) .to_str() .unwrap() }); #[doc(alias = "NM_SETTING_WIRELESS_SECURITY_LEAP_USERNAME")] pub static SETTING_WIRELESS_SECURITY_LEAP_USERNAME: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe { CStr::from_ptr(f...
Rust
0
t not_rectangles(aM0A); } rM0A_7 @= { @ "M0A.7 : Minimum vertical overlap between M0A and ACTIVE >= 11 nm"; //Sushant gGRM0A7_check = and(aM0A, aACT); internal1 (gGRM0A7_check, < 0.011, direction = VERTICAL, extension = NONE); } rM0A_8 @= { @ "M0A.8 : M0A may not exitst without ACTIVE "; //Sushant //gGR...
Rust
0
.map(|p| intensity_to_ascii(&p.0[0])) .fold(String::new(), |s, p| s + p); // let subs = ascii_art // .as_bytes() // .chunks(img_buf.width() as usize) // .map(from_utf8) // .collect::<Result<Vec<&str>, _>>() // .unwrap() // .into_iter() // .map...
Rust
0
ODY_COMPRESSED) @mock.patch.object(botocore.compress, 'gzip_compress', static_compress) @mock.patch.object(botocore.compress, 'COMPRESSION_MAPPING', MOCK_COMPRESSION) @pytest.mark.skipif( sys.version_info < (3, 8), reason='requires python3.8 or higher' ) def test_only_compress_once(): request_dict = _request_...
Python
1
.encode(USERINFO_ENCODE_SET).for_each(|s| url.push_str(s)); } // Qualifiers: percent-encode the values if !self.qualifiers.is_empty() { url.push('?'); let mut items = self.qualifiers.iter().collect::<Vec<_>>(); items.sort(); let ref mut it = item...
Rust
0
# used for the distortion calculation # May want to output for determining # number of clusters in system if not args.tsne: centroids, distortion = kmeans(data, args.num_means) idx, dists = vq(data, centroids) subset = allTrajs.frame() dists *= 1.0 dists /= len(subset) else: ...
Python
1
import pandas as pd import talib as ta import zipline from zipline.api import symbol, record, order_target_percent, schedule_function from zipline.utils.events import date_rules, time_rules """ KDJ指标叫随机指标 """ def initialize(context): print("init") context.asset = symbol('IBM') # 快线回看周期为9 context.fast...
Python
1
pub fn rppi(&mut self) -> RPPI_W { RPPI_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "CIR Receiver Pulse Configure Register\n\nThis register you can ...
Rust
0
ightX, GamepadAxis::RightStickY => SdlAxis::RightY, GamepadAxis::RightTrigger => SdlAxis::TriggerRight, } } } impl From<SdlAxis> for GamepadAxis { fn from(axis: SdlAxis) -> GamepadAxis { match axis { SdlAxis::LeftX => GamepadAxis::LeftStickX, SdlA...
Rust
0
from ..default_models import ModelConfig, get_all_model_configs from ..model_quality import QualityMetricsCollection, MMLU, MATH, GSM8K, IFEval, GPQA, Hellaswag, TLDR, TriviaQA, BIG_Bench ##### Nvidia Models ######## # https://huggingface.co/nvidia/Nemotron-4-340B-Instruct/blob/main/model_config.yaml nemotron_340b_c...
Python
1
be executed in a thread /// pool is called Task. There can be different definitions of Task. Some people /// may choose `Future` as Task, some may just want callbacks, or even Actor /// messages. But no matter what a Task is, there should be some role know how /// to execute it. The role is call `Runner`. /// /// The ...
Rust
0
!( xdiff_dist( a.iter().map(|s| s.as_str()).collect_vec().as_slice(), b.iter().map(|s| s.as_str()).collect_vec().as_slice() ), 5 ); } pub mod event_bus; mod hasher; pub use hasher::ImageHashWorker; <reponame>nic-hartley/redshell<filename>src/io/input/ansi_cli.rs use ...
Rust
0
b_get_map_map_t, ) -> xcb_generic_iterator_t, >, xcb_xkb_get_map_map_explicit_rtrn: LazySymbol<unsafe fn(s: *const xcb_xkb_get_map_map_t) -> *mut xcb_xkb_set_explicit_t>, xcb_xkb_get_map_map_explicit_rtrn_length: LazySymbol< unsafe fn(r: *const xcb_xkb_get_map_reply_t, s: *const xcb_...
Rust
0
, 1, 31)).unwrap(); /// assert_eq!(january.start(), NaiveDate::from_ymd(2020, 1, 1)); /// assert_eq!(january.end(), NaiveDate::from_ymd(2020, 1, 31)); /// ``` pub fn start(self) -> NaiveDate { self.0 } /// The last day of the interval /// /// # Examples /// ``` /// use r...
Rust
0
); } #[test] fn test_ldabsh() { test_interpreter_and_jit_asm!( " ldabsh 0x3 exit", [ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, // 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, // ], (), { |_vm, res: Result| { res.unwrap() ==...
Rust
0
eachable!("AcpiOsStall") } #[no_mangle] #[linkage = "external"] pub unsafe extern "C" fn AcpiOsReadPort( address: ACPI_IO_ADDRESS, value: *mut UINT32, width: UINT32, ) -> ACPI_STATUS { let port = address as u16; match width { 8 => { *value = io::inb(port) as u32; AE_...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "DHL Express Shipping", 'description': "Send your shippings through DHL and track them online. This version of the DHL connector is" "compatible with the DHL REST API available at https://developer.dhl.com/. ...
Python
1
ingle upstream route') # If egress_port is not specified (None), we can also can return a # "half" route if egress_port_no is None: for (ingress, egress), route in self._routes.iteritems(): if ingress == ingress_port_no: return [route[0], None] ...
Python
1
# encoding: utf-8 """ @author: Dechao Meng @contact: dechao.meng@vipl.ict.ac.cn """ import glob import re import os.path as osp from pathlib import Path import time import numpy as np import pickle as pkl from vehicle_reid_pytorch.data.datasets.bases import ReIDMetaDataset, relabel, get_imagedata_info class CommonR...
Python
1
# Copyright © 2024 Pathway from __future__ import annotations import pytest from .utils import KafkaTestContext @pytest.fixture def kafka_context(): kafka_context = KafkaTestContext() yield kafka_context kafka_context.teardown()
Python
1
from dxr.testing import DxrInstanceTestCase, menu_on SEARCH = '/code/search?q=%s%%3A%s' class IdlMenusTest(DxrInstanceTestCase): """Test that menu links point to the right places.""" def test_include(self): menu_on(self.source_page("nsIDownloadHistory.idl"), 'nsISupports.idl', {'html...
Python
1
ro_grad() # forward # track history if only in train with torch.set_grad_enabled(False): outputs = model(inputs) # backward + optimize only if in training phase if index == 0: outputs_test = outputs labels_test = labels ...
Python
1
/// Index in the final output WebAssembly module's table. This is the **Virtual Class ID**. pub id: u32, } /// Unified virtual method table for all classes in a module. /// /// Java supports dynamic dispatch. A common approach to implementing this is to define a virtual /// method table per class, mapping eac...
Rust
0
from apps.report.info.UHE.NEWAVE.estruturas import Estruturas from apps.indicadores.eco_indicadores import EcoIndicadores from inewave.newave import Pmo from inewave.newave import Dger from inewave.newave import Cvar class InfoUHENewave(Estruturas): def __init__(self, data, par_dados): Estruturas.__init_...
Python
1
[doc = "Bit 7 - P2SELC_7"] #[inline(always)] pub fn p2selc_7(&mut self) -> P2SELC_7_W { P2SELC_7_W { w: self } } #[doc = "Writes raw bits to the register."] pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { self.0.bits(bits); self } } #[doc = "Port 2 Complement Selec...
Rust
0
: Option<StateId>, delta: f32, ) -> Self { Self { sd_opts: ShortestDistanceInternalConfig::new_with_default( EpsilonTrFilter {}, queue, delta, ), connect, weight_threshold, state_threshold, ...
Rust
0
TimeClue { /// Now. Now, /// Time without date: "19:43:42", "18", "8", "7pm", "3am" Time(HMS, Option<AMPM>), /// Relative (past) time clue: "4 minutes ago" Relative(usize, Quantifier), /// last/next `<day>` at `<time>`: "last friday at 12" RelativeDayAt(Modifier, Weekday, Option<HMS>, O...
Rust
0
any(feature = "v2_30", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))] #[doc(alias = "is-muted")] fn connect_is_muted_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[cfg(any(feature = "v2_8", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_8...
Rust
0
;94m 3 |  father User  4 |  son User  |  "#]]; expect.assert_eq(&datamodel::parse_schema(dml).map(drop).unwrap_err()); } #[test] fn should_fail_on_ambiguous_self_relation_with_two_fields() { let dml = indoc! {r#" model User { id In...
Rust
0
> for TCRef { fn can_cast_from(scalar: &Scalar) -> bool { if let Scalar::Ref(_) = scalar { true } else { false } } fn opt_cast_from(scalar: Scalar) -> Option<TCRef> { if let Scalar::Ref(tc_ref) = scalar { Some(*tc_ref) } else { ...
Rust
0
must trust the given bytes do indeed contain a valid `Frame`. pub unsafe fn root_as_frame_unchecked(buf: &[u8]) -> Frame { flatbuffers::root_unchecked::<Frame>(buf) } #[inline] /// Assumes, without verification, that a buffer of bytes contains a size prefixed Frame and returns it. /// # Safety /// Callers must tru...
Rust
0
import math from panda3d.core import Point3 from toontown.toonbase import ToontownGlobals InputTimeout = 15 TireMovieTimeout = 120 MinWall = (-20.0, -15.0) MaxWall = (20.0, 15.0) TireRadius = 1.5 WallMargin = 1 + TireRadius StartingPositions = (Point3(MinWall[0] + WallMargin, MinWall[1] + WallMargin, TireRadius), Poin...
Python
1
AND ti2.indicator_type = 'SMA_20' LEFT JOIN technical_indicators ti3 ON ti1.timestamp = ti3.timestamp AND ti1.timeframe = ti3.timeframe AND ti3.indicator_type = 'EMA_12' LEFT ...
Python
1
(Some(rev_reg), Some(tails_file), Some(max_creds), Some(issuer_did)) => { let tag = format!("tag{}", rev_reg.tag + 1); let (rev_reg_id, rev_reg_def, rev_reg_entry) = anoncreds::generate_rev_reg(&issuer_did, &self.id, &tails_file, *max_creds, tag.as_str()) ...
Rust
0
let event = Event { pair: order.pair, event_type: EventType::Sell, memo: format!( "market sell completed! `{} {}`", pair.to_string(), match order.amount { Some(v) => format!("{:.3}", v), None => "...
Rust
0
:%M:%S') now = datetime.now() if d2 > now: return True else: return False def create_config_ini(): print('base_path基础路径', basePath) config_path = os.path.join(basePath, 'config.ini') if not os.path.exists(config_path): with open(config_path, 'a+')as f: f.wri...
Python
1
# encoding: utf-8 """ Example of simple stochastic synapses """ import matplotlib matplotlib.use('Agg') import numpy as np from pyNN.utility import get_simulator, init_logging, normalized_filename # === Configure the simulator ================================================ sim, options = get_simulator(("--plot-f...
Python
1
fault for TimerOpts { fn default() -> Self { TimerOpts::Default } } #[cfg(test)] mod tests { use super::*; use {Duration, ZX_SIGNAL_LAST_HANDLE, ZX_TIMER_SIGNALED}; use deadline_after; #[test] fn create_timer_invalid_clock() { assert_eq!(Timer::create(TimerOpts::Default, Cl...
Rust
0
::LoadOptions { single_index: true, triangulate: true, ..Default::default() }, ); let rate = 7.0 * 10.0 * 1.9; let (models, _materials) = cornell_box.expect("Failed to load OBJ file"); for (_i, m) in models.iter().enumerate() { ...
Rust
0
4); } } pub fn execute(){ let collector = tracing_subscriber::fmt() // filter spans/events with level TRACE or higher. .with_max_level(Level::TRACE) // build but do not install the subscriber. .finish(); tracing_subscriber::fmt::init(); let rt = Arc::new(Runtime::new()...
Rust
0
kDirection::Absolute(pos) => format!("{}", pos), SeekDirection::Relative(delta) => { format!("{}{}", if delta > &0 { "+" } else { "" }, delta) } }; write!(f, "{}", repr) } } #[derive(Clone, Serialize, Deserialize, Debug)] pub enum Command { Quit, Togg...
Rust
0
ONE/SVM_scaler_RAV,TESS,EMODB,SAVEE,EMOFILM e audio del bilanciamento (GIOvsSOR).joblib') # carico il modello CNN PER RICONOSCERE LA VALENCE: json_file = open('model-indiano-SOLO VALENCE(128,128)-(normale,GN-0-02)-60 epoche-paura 2 e neutro 1.json', 'r') loaded_model_json = json_file.read() json_file.c...
Python
1
as changed as expected: assert_eq!(grid.rows()[0]["id"].as_bool().unwrap(), true); assert_eq!( grid.rows()[1].as_object().unwrap().contains_key("id"), false ); assert_eq!(grid.rows()[2]["id"].as_bool().unwrap(), true); // Check the other column has not ch...
Rust
0
import cv2 import numpy as np # from sklearn.neighbors import NearestNeighbors def knn_merge(segmented_images, area_thresh_pixels=1): # 识别大区域和小区域 large_regions = [] small_regions = [] for i, img in enumerate(segmented_images): num_pixels = np.count_nonzero(img) if num_pixels > area_thr...
Python
1
} #[test] fn completes_qualified_macros() { check( r#" #[macro_export] macro_rules! foo { () => {} } fn main() { let _ = crate::$0 } "#, expect![[r#" fn main() fn() ma foo!(…) macro_rules! foo "#]], ); } #[test] fn does_not_complete_non_fn_macros(...
Rust
0
hMap<Node<T>, Vec<NodeWithCost<T, C>>>>>, } impl<T, C> AdjacencyMatrix<T, C> where T: Hash + PartialEq + Clone, C: PartialOrd + Clone, { pub fn new() -> Self { let matrix = Arc::new(Mutex::new(HashMap::new())); return Self { matrix }; } } /* Copyright 2017 <NAME> * * Licensed under th...
Rust
0
k yield prompter.get_response(decoded_output) return # early return for stream_output # Without streaming with torch.no_grad(): generation_output = model.generate( input_ids=input_ids, generation_config=generation_config, ...
Python
1
Function is called pub struct Args { pub register: u8, pub count: u8, } <filename>src/adder.rs pub fn adder(numbers: &Vec<u64>) -> u128 { let mut number_holder: u128 = 0; for &item in numbers.iter() { number_holder += item as u128; } number_holder } <gh_stars>0 //! Tock kernel for the N...
Rust
0
# indexing and slicing is used to iterate in the array and perform some operation and analysing data. # 👉Indexing - selecting a single element from a single array. # 👉Slicing - selecting multiple element from a single array. # 👉fancy indexing -selecting the multiple element using the list of indices. # 👉Boolean ma...
Python
1
.set_alignment_start(1) .set_read_length(4) .set_bases(b"TTCA".to_vec()) .set_quality_scores(vec![45, 35, 43, 50]) .build(); writer.write_record(record)?; let record = cram::Record::default(); writer.write_record(record)?; Ok(()) } <filename>pulse-sys/src/proplist.rs ...
Rust
0
template_text = """You are a bus travel services customer service bot. Your task is to assess customer query and recognize entities in customer inquiry after <<<>>> one of the following predefined entities: source destination time If the text doesn't have any of the above entities, reply as: not found You will only ...
Python
1
BACK: &str = "http://127.0.0.1"; const V6_LOOPBACK: &str = "http://[::1]"; const V4_LINK_LOCAL_1: &str = "http://169.254.0.1"; const V4_LINK_LOCAL_2: &str = "http://169.254.10.1:8080"; // IPv4-Mapped IPv6 addresses (IPv4 embedded in IPv6) const V6_MAPPED_V4_PRIVATE_CLASS_A: &str = "http://[::ffff:...
Rust
0
/ return Err(serde::de::Error::duplicate_field("list")); // } // list = Some(map.next_value::<Option<(usize, usize)>>()?); // } // } // } // let data = data...
Rust
0
(hidden)] pub fn new(client: Client) -> Self { UsergroupsUsers { client } } /** * This function performs a `GET` to the `/usergroups.users.list` endpoint. * * List all users in a User Group * * FROM: <https://api.slack.com/methods/usergroups.users.list> * * **Para...
Rust
0
test_labels = torch.Tensor(test_features['labels']).type(torch.long) test_filenames = test_features['filenames'] elapsed = time.time() - start print(f'Took {elapsed:.03f} seconds') """linear evaluation""" from panderm_model.downstream.eval_features.linear_probe import eval_linear_probe datase...
Python
1
import base64 import json from django.http import JsonResponse from rest_framework.decorators import api_view from PIL import Image import io from django.core.files.base import ContentFile from .models import UploadedImage # Import the model from django.shortcuts import render from .models import UploadedImage from d...
Python
1
reflect_trait_ident { pub fn get<'a>(&self, reflect_value: &'a dyn #bevy_reflect_path::Reflect) -> Option<&'a dyn #trait_ident> { (self.get_func)(reflect_value) } pub fn get_mut<'a>(&self, reflect_value: &'a mut dyn #bevy_reflect_path::Reflect) -> Option<&'a mut dyn ...
Rust
0
from __future__ import annotations from dataclasses import dataclass, replace from typing import Any from .._run_context import AgentDepsT, RunContext from .abstract import ToolsetTool from .wrapper import WrapperToolset @dataclass class RenamedToolset(WrapperToolset[AgentDepsT]): """A toolset that renames the ...
Python
1
class Solution: def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: minHeap = list(collections.Counter(arr).values()) heapq.heapify(minHeap) # Greedily remove k least frequent nums to have least # of unique integers. while k > 0: k -= heapq.heappop(minHeap) return len(minHea...
Python
1
] + s2d @memoized def log_once(message, func='info'): """ Log certain message only once. Call this function more than one times with the same message will result in no-op. Args: message(str): message to log func(str): the name of the logger method. e.g. "info", "warn", "error". ""...
Python
1
dt} INFO This is an info message. Its line number {count}\n", "{dt} WARN This is a warning message. Its line number {count}\n", "{dt} ERROR This is an error message. Its line number {count}\n", ]; let mut ts = begin; let mut count = rotations; while count >= 0 { let path = if co...
Rust
0
# Problem Statement # This program counts the number of times each number appears in a list. It uses a dictionary to keep track of the information. # An example run of the program looks like this (user input is in blue): # Enter a number: 3 Enter a number: 4 Enter a number: 3 Enter a number: 6 Enter a number: 4 Enter...
Python
1
fer: IndexBuffer<u32>, } <filename>src/types/user.rs use crate::types::{Guild, Pronouns}; use bitflags::bitflags; use serde::ser::SerializeStruct; #[derive(Deserialize, Clone)] pub struct User { /// The user's ID /// /// 128 bit unsigned integer pub id: u128, /// The user's name /// /// St...
Rust
0
g_level: sys.exit('logdir must be provided.') executable_path = os.path.join(os.path.dirname(__file__), EXECUTABLE) cmd = [executable_path] if FLAGS.logdir is not None: logdir = os.path.expandvars(os.path.expanduser(FLAGS.logdir)) cmd.append('--logdir=' + logdir) cmd.append('--service_addr=' + servi...
Python
1
def test_should_strip_auth_host_change(self): s = requests.Session() assert s.should_strip_auth( "http://example.com/foo", "http://another.example.com/" ) def test_should_strip_auth_http_downgrade(self): s = requests.Session() assert s.should_strip_auth("https://exam...
Python
1
#!/bin/python # Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
Python
1
l010O1l0ll1O1l1O00ll1) % 6 != 0, "\x06\x00\x0cN\x00lH0006N`*Z", ) ).join( Ol1l010O000lO0O0l0l0l( lO1l01OOll1lOOlOOOl0l( "".join( filter( lambda ll010110OOl00001Ol00l: ord(ll010110OOl00001Ol00l) % 6 != 0, "*<\x0cl\x00`\x1eB6<\x00...
Python
1
ext (str): 要分析的文本 Returns: float: 情緒分數,範圍為 -1 到 1,負數表示負面情緒,正數表示正面情緒 """ try: if not SNOWNLP_AVAILABLE: logger.warning("SnowNLP 未安裝,返回中性情緒分數") return 0.0 # 使用 SnowNLP 進行情緒分析 # SnowNLP 的情緒分數範圍是 0-1,0 表示負面,1 表示正面 ...
Python
1
# Copyright (C) 2005-2009, 2011, 2012, 2016 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This pro...
Python
1
<usize> for ColMut<'a, T> { fn index_mut<'b>(&'b mut self, idx: usize) -> &'b mut Self::Output { assert!(idx < self.matrix.cols); &mut self.matrix.elems[self.col + self.matrix.cols * idx] } } <filename>tooling/bundler/src/bundle/linux/mod.rs pub mod appimage; pub mod debian; pub mod rpm; use sup...
Rust
0
mid: NodeMeta::dummy(), name: "snot".into(), value: v("badger"), }; let f2 = super::Field { mid: NodeMeta::dummy(), name: "badger".into(), value: v("snot"), }; let r = super::Record { base: crate::Object::new(), mid: NodeMeta::dummy(), ...
Rust
0
2, ); } } // if we reach here numbers are <= 9999, so at most 4 chars long let mut n = n as isize; // possibly reduce 64bit math // decode 2 more chars, if > 2 chars ...
Rust
0