text
string
label_name
string
labels
int64
_fn(d, |(i, j)| 1. / (i + 2 * j) as f32); par_azip!((a in &mut a, &b in &b) { *a = b; }); } #[test] fn test_indices_1() { let mut a1 = Array::default(12); for (i, elt) in a1.indexed_iter_mut() { *elt = i; } let count = AtomicUsize::new(0); par_azip!((index i, &elt in &a1) { cou...
Rust
0
= env['F77FILESUFFIXES'] except KeyError: F77Suffixes = ['.f77'] try: F77PPSuffixes = env['F77PPFILESUFFIXES'] except KeyError: F77PPSuffixes = [] DialectAddToEnv(env, "F77", F77Suffixes, F77PPSuffixes) def add_f90_to_env(env) -> None: """Add Builders and construction var...
Python
1
futures::executor::block_on(async { let data = format!("test {:?}", i); stronghold .write_to_vault( loc, data.as_bytes().to_vec(), RecordHint::new(data).expect(line_error!()), vec![], ...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import os import sys from pathlib import Path import odoo from odoo.modules import get_modules, get_module_path, initialize_sys_path commands = {} class Command: name = None def __init_subclass__(cls): cls.name =...
Python
1
; pub mod pair; pub mod types; mod helpers; pub mod bitstamp; pub mod poloniex; pub mod kraken; extern crate rat; extern crate clap; use rat::config::*; use rat::errors::*; use rat::modules::centerdevice; use rat::modules::pocket; use rat::modules::slack; use rat::modules::stocks; use rat::utils::*; use clap::{Arg, ...
Rust
0
fn size(&self) -> usize { self.len() } fn dump(&self) -> Vec<u8> { self.$vec_field.clone() } fn dump_to_str(&self, radix: $crate::mem::DumpRadix) -> String { $crate::mem::format_str_dump(radix, self.iter().copied(...
Rust
0
from datetime import datetime from aiogram import Router, F from aiogram.types import Message from aiogram.filters import Command from data import PromoCode router = Router() @router.message(Command("add_promo")) async def add_promo(message: Message): # Проверяем, что команда введена правильно try: _,...
Python
1
PLATFORM_WEB = "web" ALL = 0 QUESTION = 1 NEWS = 2 TERM = 3 PUBLIC_BLOG = 4 COMPANY = 5 WEB = 6 FOR_CONTENT = ( (ALL, "All"), (QUESTION, "Question"), (NEWS, "News"), (TERM, "Term"), (PUBLIC_BLOG, "PublicBlog"), (COMPANY, "Company"), (WEB, "Web"), ) QUESTION_FOR_CONTENT = "question" NEWS_F...
Python
1
E // SOFTWARE. use super::*; use std::{slice, str}; use libc::{c_char, ptrdiff_t}; /// Converts a foreign string slice into a native string slice. /// /// # Safety /// /// Similar to `std::slice::from_raw_parts`, there is no guarantee that the provided slice /// is valid for as many bytes as it claims to be, nor is...
Rust
0
#[builder(default = Some(()), setter(skip))] r#enum: Option<()>, #[builder(setter(into))] r#union: String, } assert!( r#struct::builder().r#fn(1).r#union("two").build() == r#struct { r#fn: 1, r#type: None, r#en...
Rust
0
Create the triple with all information triple_info = [ head, relation, tail, entropy, yes_prob, no_prob, unknown_prob ] # Create subgraph (either containing the triple or empty) if entropy <= ent...
Python
1
line| !line.is_empty()) .filter(|line| !line.starts_with("//")) .map(parse_fn_desc) .collect(); // Generate the bios function trampolines let asm_file = "trampoline.s"; let asm = bios_functions .iter() .fold(String::new(), |s, f| s + &mk_bios_trampoline(f)); fs::...
Rust
0
ly drop a piece in col {}, \ which already has height {} and has no more room.", col, piece_height ); } self.set_piece(col, piece_height, piece); self.increment_col(col); let pos = Position { x: col, y: piece_height, ...
Rust
0
# Practical Machine learning # Support Vector Machines example # Chapter 6 # Example: ExImage Recognition with Support Vector Machines import sklearn as sk import numpy as np import matplotlib import matplotlib.pyplot as plt # print 'IPython version:', IPython.__version__ # print 'numpy version:', np.__version__ # p...
Python
1
''' saldo=input("Digite a quantia que voçe deseja aplicar ") onde=input( "Escolha a forma de aplicaçao poupança ou CDB ") poupança=0.5 CDB=1 saldo_float = float (saldo) poupança_float = float (poupança) CDB_float = float (CDB) if onde== "poupança": print({saldo} / {poupança} * 100) if onde=="CDB": print ({s...
Python
1
nalizador_Sintactico.py',146), ('valores -> array','valores',1,'p_valores','Analizador_Sintactico.py',147), ('valor -> NUMERO','valor',1,'p_valor','Analizador_Sintactico.py',150), ('valor -> FLOTANTE','valor',1,'p_valor','Analizador_Sintactico.py',151), ('valor -> CADENA','valor',1,'p_valor','Analizador_Sintact...
Python
1
from eventlet.green import time return [('time', time)] def _green_MySQLdb(): try: from eventlet.green import MySQLdb return [('MySQLdb', MySQLdb)] except ImportError: return [] def _green_builtins(): try: from eventlet.green import builtin return [('__buil...
Python
1
tensor). tx: Union[int, DataType] Type of elements in tensor x. tw: Union[int, DataType] Type of elements in tensor w. ty: Union[int, DataType] Type of elements in tensor y. compute_type: Union[int, cudnnDataType] The compute type of the operation. For cuDNN, ther...
Python
1
dag new_dag = DAGCircuit() new_dag.add_qubits(node.qargs) new_dag.add_clbits(node.cargs) # If appending re-apply original op node first if self._method == "append": new_dag.apply_operation_back(node.op, qargs=node.qargs, cargs=node.cargs) ...
Python
1
w(vec![Value::Int(7)]), None, true, ), ]; for (key, values, expected_result, expect_err) in cases { let key_cache = key.clone(); let result = new_boolean_func(key, values); match result { Ok(result) => { ...
Rust
0
rialized.len() as u64)); req.set_body(serialized); // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { let parsed: Result<::models::UnsignedTx, _>...
Rust
0
import logging import shutil from pathlib import Path import sys import traceback import numpy as np # Ensure chai_lab is installed or in PYTHONPATH try: from chai_lab.chai1 import run_inference except ImportError: print("Error: Cannot import 'chai_lab'. Please ensure it is properly installed or you are runnin...
Python
1
iptor. This is handled by the variable number_of_bytes. 2. For how long to read from the read descriptor. We wait for atmost 10 seconds for Xvfb to write the display number using the 'select' package. Args: xvfb_cmd (List): A list containing the command to run the Xvfb process ...
Python
1
from app import db from app.dao import DAOClass from app.models import Organisation, OrganisationUserPermissions, User class OrganisationUserPermissionsDao(DAOClass): class Meta: model = OrganisationUserPermissions def remove_user_organisation_permissions(self, user: User, organisation: Organisation)...
Python
1
# !/usr/bin/env python3 ''' 将1个channel的文件提取出来 ''' import os import subprocess from glob import glob import shutil import fire import re def split_channels(indir, outdir): files = glob(os.path.join(indir, '*.wav')) os.makedirs(outdir,exist_ok=True) c1_dir = os.path.join(outdir, 'c1') c2_dir = os.path.j...
Python
1
from app.internal.favorite_users.db.models import FavoriteUser from app.internal.users.db.models import User from typing import List from asgiref.sync import sync_to_async class FavoriteUserRepository: async def save_fav_user( self, user: User, favorite_user: User, username: str, method: str, value: str ...
Python
1
l:{}-c:{}-ft:{}'.format(feat_3d.shape,mask.shape,labels[mask].shape,coords[mask].shape,feats[mask].shape)) # import pdb # pdb.set_trace() # import pdb # pdb.set_trace() self.feat_emb=torch.cat(self.feat_all) # self.mask_emb=torch.cat(self....
Python
1
ent, sql, &[&ca.username]).await?; if c > 0 { return Err(AppError::is_exists("同名的管理员已存在")); } let sql = "INSERT INTO admin (username, password) VALUES ($1, $2) RETURNING id"; Ok(super::query_one( client, sql, &[&ca.username, &ca.password], Some("添加管理员失败"), ) ...
Rust
0
$f, $g, $h>; Fed6<$a, $c, $e, $f, $g, $h> => Fed8<$a, $b, $c, $d, $e, $f, $g, $h>; Fed6::T1, Fed6::T2, Fed6::T3, Fed6::T4, Fed6::T5, Fed6::T6); fed_promotion!(Fed7 => Fed8; <$b, $c, $d, $e, $f, $g, $h> => <$a, $b, $c, $d, $e, $f, $g, $h>; Fed7<$b, $c, $d, $e, $f, $g, $h> => Fed8<$a, $b, $c, $d, $e, $f, $g, $h...
Rust
0
#encoding:utf-8 from wtforms import StringField,IntegerField,TextAreaField,TextField from wtforms.validators import Length,InputRequired,regexp,Regexp,EqualTo from wtforms import Form class LoginForm(Form): email = StringField(validators=[Length(5,20,message='邮箱长度不正确'),InputRequired(message='请输入工号')]) passwor...
Python
1
: Non-public method // /// [StandardWatchEventKinds](https://developer.android.com/reference/java/nio/file/StandardWatchEventKinds.html#StandardWatchEventKinds()) // fn new<'env>(__jni_env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::java::nio::file:...
Rust
0
питера.", "Capricorn": "Известен своей ответственностью, дисциплинированностью и самоконтролем. Земной знак под управлением Сатурна.", "Aquarius": "Известен своей прогрессивностью, оригинальностью и независимостью. Воздушный знак под управлением Урана.", "Pisces": "Известен своим состраданием, х...
Python
1
test repository") } } <filename>src/game/tile_runs/mod.rs mod shared; pub mod color; pub mod sequential; use super::{CoverageArray, Covered, Subtable}; use crate::parse_prelude::*; /// Single substitution format 1. /// /// <https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#lookuptype-1-single-substitu...
Rust
0
import gensim import numpy as np word_vectors=gensim.models.KeyedVectors.load_word2vec_format('./tool/zhwiki_2017_03.sg_50d.word2vec',binary=False) vocab = word_vectors.wv.vocab print ('搜狗词向量语料加载,成功!') '''显示所有词向量,并其存储在变量中''' wordVectors = {} wordsList = [] wordIndexVector = [] for word in vocab: wordVectors[word]...
Python
1
#[allow(unused_variables)] let voting = admin_contract.get_voting(VotingId::from(1)).unwrap(); } test "address cannot perform action before voting finishes" { assert_eq!( reputation_token_contract.as_nth_account(1).mint(admin_contract.get_env().get_account(...
Rust
0
rget_cell in self.cells.values(): for target_pin in target_cell.pins: # 檢查是否為匹配的輸入管腳(名稱相同的輸入管腳) if target_pin.is_input and target_pin.name == pin.name: # 為這對管腳創建曼哈頓布線路徑 route =...
Python
1
import numpy as np import utils MAX_MARGIN = 2.4 MIN_MARGIN = -2.0 class StrategyAnalyzer(object): @classmethod def valid_margin(cls, margin): return margin <= MAX_MARGIN and margin >= MIN_MARGIN @classmethod def get_margin(cls, ex, price, agent, role, remove_outlier=True): agent_tar...
Python
1
_variants: uint, get_disr: extern unsafe fn(ptr: *Opaque) -> Disr, sz: uint, align: uint) -> bool; fn visit_enter_fn(&mut self, purity: uint, proto: uint, n_inputs: uint, retstyle: uint) -> bool; fn visit_fn_input(&mut self, i: uint, mode: u...
Rust
0
let y = parse_word!(1) - 1; row.push(x); col.push(y); data = parse_data_vals(data, 2); //println!("x: {} y: {} v: {:10.4e}", x, y, v); } } //println!("words: {:?}", words); } printl...
Rust
0
{}'", other_action ))); } } Ok(()) } } #[cfg(target_arch = "wasm32")] // Sabre apply must return a bool pub fn apply( request: &TpProcessRequest, context: &mut dyn TransactionContext, ) -> Result<bool, ApplyError> { let handler = StatusTr...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2024 Alibaba Group Holding Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache...
Python
1
ty::Packed => 1.0 }, UniverseSize::Medium => match density { UniverseDensity::Sparse => 1.0, UniverseDensity::Normal => 1.0, UniverseDensity::Dense => 1.0, UniverseDensity::Packed => 1.0 }, UniverseSize::Large => match density { ...
Rust
0
UTEX_TRYLOCK_PI => FutexOperation::TrylockPi, data::FUTEX_WAIT_BITSET => FutexOperation::WaitBitset, _ => unimplemented!("unrecognized futex op {}", futex_op), }; let old_timespec = if timeout.is_null() || !matches!(op, FutexOperation::Wait | Futex...
Rust
0
ntal memory leaks { self.get_backing_buffer_with_leaking_writes() } /// Same as [`.get_backing_buffer()`][`VecCapacity::get_backing_buffer`] /// but without the `Copy` bound. /// /// This means that extra care should be taken if /// `mem::needs_drop::<Self::Item>()`. Indeed, if the ...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: precisionlocation.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as...
Python
1
[token("function")] KwFn, //===--------------- Extras ---------------------=== #[regex(r"[ \t\n\f]+", logos::skip)] WhiteSpace, #[error] Error, } use chrono::{DateTime, TimeZone}; use std::fs::File; use std::path::Path; /// A loaded fixture file. pub struct FixtureFile<Tz: TimeZone + Send + S...
Rust
0
te(looper()) t = threading.Thread(target=threaded, args=(driver, stop_event, on_event_coro)) t.start() async def on_event(data): print("on_event") print("data:", data) def func_called(fn): def wrapped(*args, **kwargs): print( "func called! %...
Python
1
= unsafe { std::slice::from_raw_parts(self.data, self.size) }; for s in strs { target.push(s.to_str().to_owned()); } target } } // conversions from/to vectors of built in types macro_rules! primitive_sequence { ($ctype:ident, $element_type:ident) => { paste::item! {...
Rust
0
.file.name_str(), line.line, line.file.dir_str(), indent = self.1 * 2 )?; } write!(f, "{:?}", FunctionsDebug(&function.inlinees, self.1 + 1))?; } Ok(()) } } #[test] fn test_breakpad() -> Result<(),...
Rust
0
search methods #[derive(Debug, Clone, Copy)] pub enum Location { /// A byte offset in the file Point(Point), /// 1-based line and column indices. Coords(Coordinate), } impl From<Point> for Location { fn from(val: Point) -> Location { Location::Point(val) } } impl From<Coordinate> for...
Rust
0
g << 8) | b } } impl From<(u8, u8, u8)> for Color { /// Convert a tuple of u8's (R, G, B) into a color fn from((r, g, b): (u8, u8, u8)) -> Color { Color { r: r, g: g, b: b } } } impl Into<(u8, u8, u8)> for Color { /// Convert a color into a tuple of u8's (R, G, B) fn into(self) -> (u8,...
Rust
0
verbose=verbose, device=device, use_sde=use_sde, sde_sample_freq=sde_sample_freq, support_multi_env=True, monitor_wrapper=monitor_wrapper, seed=seed, stats_window_size=stats_window_size, tensorboard_log=tensorboard_l...
Python
1
from log import Log class ErrorLogger(Log): def __init__(self, successor=None): self.successor = successor self.severity = 3 def log(self, message, severity, history): if self.severity == severity: modified_message = f"\033[91m{message}\033[0m" print(modified_m...
Python
1
}; vec.push(push_v); } return vec; } /// Basic mergesort. NOT in-place pub fn mergesort<T : Ord + Clone>(slice : &[T]) -> Vec<T> { // TODO, once we get slicking syntax: // match slice { // [] => {return vec!();}, // [ref v] => {return vec!(v.clone());}, // _ => {} // } match slice.len() { 0 => {re...
Rust
0
=> { let error_code = match error_code_handler { Some(handler) => handler(status), None => anyhow!("{}", status), }; let bytes = match into_bytes(response) { Ok(bytes) => bytes, Err(e) => { return E...
Rust
0
(ReclaimPolicy::Delete), _ => Err(VolumeError::BadReclaimPolicy), } } } #[derive(Debug)] #[allow(clippy::enum_variant_names)] enum AccessMode { ReadOnlyMany, ReadWriteMany, ReadWriteOnce, } impl FromStr for AccessMode { type Err = VolumeError; // defines what type of acces...
Rust
0
from .base_trailing_indicator import BaseTrailingIndicator import numpy as np class InstantVolatilityIndicator(BaseTrailingIndicator): def __init__(self, sampling_length: int = 30, processing_length: int = 15): super().__init__(sampling_length, processing_length) def _indicator_calculation(self) -> f...
Python
1
= copy.deepcopy(layer) output, kv_cache = run_streamllm_context(hidden_states, attention_mask, past_key_value, hidden_size, num_attention_heads, max_seq_len, input_len, init_kvcache_size, clonded_layer, use_streaming_llm=True, is_context_stage=is_context_stage) trt_output, trt_kv_cache = run_trt_context(hidden...
Python
1
_info().unwrap(); for &(major, minor, product_type, name) in &test_data { info.dwMajorVersion = major; info.dwMinorVersion = minor; info.wProductType = product_type; let name = get_product_name(&info).unwrap(); assert_eq!(name, name); } }...
Rust
0
r.info(f"压缩图片: {access_path.name} -> {compressed_path.stat().st_size / 1024}KB") else: img_seg_pairs.append( ( f"<{one_time_code} | Image:{convert_filename_to_sandbox_upload_path(seg.file_name)}>", Conten...
Python
1
e[2], ti * dt:ti * dt + self.W.get_value(borrow=True).shape[3], :] = self.W.get_value(borrow=True)[hi, :, :, :, :] W_mat[qi, :] = placed_filter.reshape((n)) Hv_mat[qi, :] = Hv[:, ri, ci, ti, hi] for qi in xrange(0, batchSize): Vv_mat[:...
Python
1
a -o /tmp/out.7z foo.wav # Archives foo.wav to /tmp/out.7z", "a -b foo/bar # Archives foo/bar folder to bar.rar as small as possible", "a -p password foo.wav # Archives foo.wav to foo.rar with a password", "x foo.rar # Extracts fo...
Rust
0
3::new(r, g, b)) } } fn read_next_waveform_parameters<U: Read>( reader: &mut U, las_format: &Format, ) -> Result<Vector3<f32>> { if !las_format.has_waveform { Ok(Default::default()) } else { let px = reader.read_f32::<LittleEndian>()?; ...
Rust
0
TestEdit::apply(&mut delete_buffer, Delete); println!(); println!(); println!(); let mut buffer: TextBuffer = d!(); buffer.rope = delete_buffer.rope; dbg!(&buffer); let expected_line_suffix = "precious"; let expected_pre_chunk: &'static str = "\r\n precious"; let expected_post_c...
Rust
0
return Err(Box::new(FftError::new( format!( "Wrong length of input, expected {}, got {}", self.length / 2 + 1, input.len() ) .as_str(), ))); } if output.len() != self.length { ...
Rust
0
d.replace(buffer); } else { // Remove any pending previous read if we failed the last attempt. previous_read.take(); } delay.delay_ms(100); } panic!("Failed to read MAC address"); } <reponame>UlysseCorbeil/rust-wasm use serde::{Deserialize, Serialize}; #[derive...
Rust
0
'): name = name[1:] if name.endswith('-'): name = name[:-1] return name def initialise_from_config(self) -> None: """Load provider categories from config into database.""" try: provider_category_configs = json.loads(terrareg.config.Config().PROVID...
Python
1
########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is ho...
Python
1
ommonly-used to be informative; /// prevents display of this rule in parse errors, Common(Rc<FormPat>), /// Matches an atom or varref, but not if it's on the list of reserved words Reserved(Rc<FormPat>, Vec<Name>), /// Matches if the sub-pattern equals the given name Li...
Rust
0
# Copyright 2014-2017 ARM Limited # # 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 w...
Python
1
let mut out = Vec::with_capacity(base.len() * 2 + 1); out.extend(base.iter().clone()); out.push(0xf0); out.extend(base.into_iter()); Some(out) } else { let mut out = Vec::with_capacity(base.len() * ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A very short example experiment in 16 lines of pure code. Participants have to indicate the parity of digits by pressing the left arrow key for odd and the right arrow key for even numbers. """ from expyriment import control, stimuli, design, misc digit_list = [1,...
Python
1
(); let mut queue = vec![master_rev]; while let Some(mut cur) = queue.pop() { if !checked.insert(cur.id()) { continue; } let date = Utc.timestamp(cur.time().seconds(), 0); if date < Utc.ymd(2017, 1, 1).and_hms(0, 0, 0) { //i...
Rust
0
umber in enumerate(tqdm(range(num_questions), desc="Processing Questions from devset for Evaluation")): rand_idx = random.randint(0, len(devset)) example = devset[rand_idx] question = devset[rand_idx].question gold_titles = devset[rand_idx].gold_titles print(f"{BOLD_BEGIN}Questio...
Python
1
# Copyright HeteroCL authors. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import heterocl as hcl import numpy as np import math as mt def top_trisolv(N, dtype=hcl.Int(), target=None): hcl.init(dtype) L = hcl.placeholder((N, N), "L") b = hcl.placeholder((N,), "b") x = hcl.placeholder((N...
Python
1
\x9f\xc4fU\xf7kB\ E\x15\xacL\x5c\x13]\xca^\xd8+tB*\xad\xae\ \xf2mE\x1f\xd1\x96\x05\x08CCCZ4Fm\xf6\ }\xd3\x16Y\x1e\xb4\x8fZG\xab+\xb1\xcd\xb3s7\ 3&=\xfd\xc8a\xdb+-\x9b\x99\xb9\x9b\x99\xb9\x9b\ \x99\xb9\x9b\x99\xb9\x9b\x995\xba-\x1e\x81\x1e\xca\x96\xe6\ nb\x9bC\xcb&\xecy\xa4,\xb2b\xcd#6G\ \xc1\x14E\x10\x1cJ\xd2\x8a\x12\x...
Python
1
CFLAGS", cflags) .arg("-e") .arg("-f").arg(makefile) .arg(platform) .execute() } /// If a static Lua is not yet available from a prior run of this script, this /// will download Lua and build it. The cargo configuration text to link /// statically against lua.a is then printed to stdout...
Rust
0
.len() > 0"); Ok( result ) }, nom::IResult::Incomplete( .. ) => { return Err((EncodingErrorKind::Malformed, mail_type).into()); } nom::IResult::Error( .. ) => { return Err((EncodingErrorKind::Malformed, mail_type).into()); ...
Rust
0
curacy) merged_summary = tf.summary.merge_all() writer = tf.summary.FileWriter(filewriter_path) # saver saver = tf.train.Saver() # 定义一代的迭代次数 train_batches_per_epoch = int(np.floor(train_data.data_size / train_batch_size)) test_batches_per_epoch = int(np.floor(test_data.data_size / test_bat...
Python
1
OnSetFreezeState(bool), OnSetPos(Vec2f), OnPlayPositioned(&'a str), SetHasGrowID(bool, &'a str, &'a str), } impl<'a> VariantFunction<'a> { pub fn serialize(self) -> std::io::Result<VariantList<'a>> { let mut varlist = VariantList::new(&[]); // empty! match self { Self::...
Rust
0
(state_dict, self._ckpt_path) paddle.distributed.barrier() check_structure_name_mapping(self._ckpt_path, state_dict) expected_local_state_dict = {} need_load_state_dict = {} for k, v in state_dict.items(): expected_local_state_dict[k] = ( v._local_valu...
Python
1
from typing import Dict, Iterable, Optional, Any import torch from multimedeval.radgraph.allennlp.common.registrable import Registrable class Metric(Registrable): """ A very general abstract class representing a metric which can be accumulated. """ supports_distributed = False def __call__...
Python
1
, TlsConnectorBuilder}; use postgres_native_tls::MakeTlsConnector; use tokio_postgres::{Client, Config}; /// Wraps functionalities for the `tokio-postgres` crate #[derive(Debug)] pub struct TokioPostgres { conn: Client, } impl TokioPostgres { /// Creates a new instance from all necessary parameters. /// /// #...
Rust
0
as_branch(); let mut branch = branch::Branch::new(node.body); branch.initialize(&key, child_page_id, root_page_id); meta.header.root_page_id = new_root_buffer.page_id; meta_buffer.is_dirty.set(true); } Ok(()) } } pub struct Iter { buffer: Rc<Buffe...
Rust
0
s at any point. //! //! User ---- tx ---> Proxy ---------> Implementation_v0 //! | ------------> Implementation_v1 //! | ------------> Implementation_v2 #![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; #[ink::contract] pub mod upgradeable_contract { use ...
Rust
0
"raw_value": data.get("last_values", {}).get("raw", 0), "percentage": data.get("last_values", {}).get("percentage", 0.0)
Python
1
r, rect, width=0, *arg, **args): """ 兼容pygame接口的rect绘制。 target: SDLSurface 或 renderer color: (r,g,b,a) rect: (x, y, w, h) width: 0 填充,>0 画边框 """ rect = [int(i) for i in rect] if len(color) == 3: color = (color[0], color[1], color[2], 25...
Python
1
from __future__ import (absolute_import, division, print_function) # make plot of etopo bathymetry/topography data on # lambert conformal conic map projection, drawing coastlines, state and # country boundaries, and parallels/meridians. # the data is interpolated to the native projection grid. from mpl_toolkits.base...
Python
1
<T> { self.buffer.buffer.read_slice::<buffer::ArrayBuffer, T>(offset, size) } } impl<T> VertexBuffer<T> { /// Returns the number of bytes between two consecutive elements in the buffer. pub fn get_elements_size(&self) -> uint { self.buffer.elements_size } /// Returns the associated...
Rust
0
traint], bounds=Bounds(0, 1), integrality=1, options=milp_options ) if res.status == 2: print("Infeasible") selected = [ poles[i] for i, val in enumerate(res.x) if val >= 0.9 ] return selected, res def solve_set_cover( coverages: li...
Python
1
alidInput, "End point for Restartables is not known.", )), Current(_offset) => unimplemented!(), } } } #[cfg(not(feature = "library"))] use cosmwasm_std::{ attr, entry_point, to_binary, Addr, Binary, Coin, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Response, ...
Rust
0
nt } fn new_txn(&self) -> TxnType<Self::Client> { self.async_client_ref().new_txn() } async fn login<T: Into<String> + Send + Sync>( self, _user_id: T, _password: T, ) -> Result<AsyncAclClient<Self::Channel>, Error> { Ok(self.async_client) } } /// /// L...
Rust
0
.and(json()) .and(with_config()) .and_then(|document_spec, config| { endpoints::preview(document_spec, config) .map_err(EndpointError::into_rejection) .boxed() .compat() }); let routes = merge.or(submit).or(preview); heal...
Rust
0
# coding: utf-8 # flake8: noqa """ Identity and Access Managment (IAM) (Alpha) OpenAPI spec version: v2024.14.0 """ from __future__ import absolute_import # import models into model package from .any_ofperson_id import AnyOfpersonId from .any_ofperson_read_response_id import AnyOfpersonReadResponse...
Python
1
6 - 1): break return p * 6 - 1, p p, l = gen_prime() F = ExtendedFiniteField(p, "x^2+x+1") return EllipticCurve(F, 0, 1), F, l def find_point_by_order(E, l): """ Find a Elliptic Curve Point P which has order l. Args: E: The Elliptic Curve l: Order of Point ...
Python
1
'email' does not match required pattern" ): plugin.validate_function_params("email", {"email": "invalid-email"}) class TestPluginExecution: """Test plugin execution functionality.""" def test_plugin_execution_success(self): """Test successful plugin function execution.""" ...
Python
1
]): # exp(log(1 + fastemit_lambda) + ...) is numerically more stable than # multiplying (1.0 + fastemit_lambda) with result. grad -= math.exp(math.log1p(fastemit_lambda) + alphas[col] + logpk - logll[mb] + betas[col + 1]) # update grads[b, t, u, v] = grad ...
Python
1
rde_json as json; use std::io; use std::fs; use std::mem; use std::thread::sleep; use crate::client; // ############## // UTILITIES ### // ############ /// Identifies the an OAuth2 authorization scope. /// A scope is needed when requesting an /// [authorization token](https://developers.google.com/youtube/v3/guides/...
Rust
0
# This file is public domain, it can be freely copied without restrictions. # SPDX-License-Identifier: CC0-1.0 import cocotb from cocotb.triggers import Timer from cocotb.utils import get_sim_time import pandas as pd @cocotb.test() async def truth_table_test(dut): """Test for logic defined by the truth table""" ...
Python
1
) self.mock_pod_objects.return_value.filter.return_value = [ self.mock_pod ] self.mock_pod.exec.return_value = { "stdout": "instance-1", "stderr": "", } collector = nova.NovaObjectsCollector(args, "/workspace", "repor") collector.coll...
Python
1