text
string
label_name
string
labels
int64
ger): # WHEN get_registered_handlers is called @exception_manager.exception_handler(ValueError) def handle_error(e): return "Error handled" # GIVEN handlers have been registered handlers_copy = exception_manager.get_registered_handlers() # THEN a copy of the handlers dictionary is retu...
Python
1
lower, upper = [int (x) for x in input().split(" ")] if lower > upper or upper > 100: print("Invalid.") else: print("fahr celsius") tmp = lower while(tmp <= upper): print("%d%6.1f" % (tmp, (tmp - 32) / 1.8)) tmp += 2
Python
1
for i in range(num_returns): print("yield", i) yield np.ones(1_000_000, dtype=np.int8) * i @ray.remote(num_returns="streaming", max_retries=2) def dynamic_generator(num_returns): for i in range(num_returns): print("yield", i) yield np.ones(...
Python
1
etval ::NRF_SUCCESS"] #[inline(always)] pub unsafe fn sd_mutex_release(p_mutex: *mut nrf_mutex_t) -> u32 { let ret: u32; asm!("svc 46", inout("r0") to_asm(p_mutex) => ret, lateout("r1") _, lateout("r2") _, lateout("r3") _, lateout("r12") _, ); ret } #[doc = "@bri...
Rust
0
LAGS, read_classification_flags_in_default_layout ); make_get_reader_fn!( get_scanner_channel_reader, u8, SCANNER_CHANNEL, read_scanner_channel_in_default_layout ); make_get_reader_fn!( get_scan_direction_flag_reader, bool, SCAN_DIRECTION_FLAG, read_scan_direction_flag_in_default_l...
Rust
0
) => Debug, (Nothing, Show) => Show, _ => Nothing } } pub fn debug(self) -> bool { self == PrintLevel::Debug } } impl Default for PrintLevel { fn default() -> PrintLevel { PrintLevel::Nothing } }//---------------------------------------------------------------------------// // Copyri...
Rust
0
use num_integer::Integer; /// assert_eq!((8).mod_floor(&3), 2); /// assert_eq!((8).mod_floor(&-3), -1); /// ``` #[inline] pub fn mod_floor(self, other: &Self) -> Self { use num_integer::Integer; Self(self.0.mod_floor(&other.0)) } } macro_rules! impl_bigint_operator { ($op:i...
Rust
0
28), device='cuda') # Initialize with random noise with torch.no_grad(): for t in reversed(range(len(betas))): xt = reverse_process(model, xt, t, betas) # Remove noise at each step return xt transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) tra...
Python
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
Python
1
let snippet_indexes = snippet .highlighted() .iter() .map(|s| { let b = s.bounds(); (b.0 + snippet_base_location, b.1 + snippet_base_location) }) .collect::<Vec<_>>(); Ok(SearchResult { score, book_id: String:...
Rust
0
# acesso = '12qw' # chance = '' # cont = 0 # while chance != acesso: # chance = input('Digite a chave: ') # if chance == acesso: # print('---- Seja bem-vindo!! ----') # break # else: # print('Errou, tente novamente!') num_sec = '12qwe' tentativas = 3 jog1 = 0 jog2 = 0 while jog1 < tentativas and j...
Python
1
: &pb::EthSignRequest, params: &Params, ) -> Result<(), Error> { if request.data.is_empty() && request.value.is_empty() { // Must transfer non-zero value, unless there is data (contract invocation). return Err(Error::InvalidInput); } let recipient = parse_recipient(&request.recipient)?;...
Rust
0
from django.apps import AppConfig class StudentsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'students' def ready(self): import students.signals
Python
1
w(); selector.str_path(path)?; selector.value(self.val); let results = selector.select()?; Ok(results) } pub fn serialize_object<O: Serialize>( o: &O, indent: Option<&str>, newline: Option<&str>, space: Option<&str>, ) -> String { let ...
Rust
0
} } impl Render for Canvas { fn get_primitives(&mut self, primitives: &mut Vec<Primitive>, env: &mut Environment) { let context = Context::new(); let rectangle = Rect::new(self.position(), self.dimension()); let context = (self.context)(rectangle, context); let paths = context...
Rust
0
, curveList) ret = dialog.exec() if ret: newLegend = dialog.getText() wasActive = self.plot.getActiveCurve() is curve self.plot.removeItem(curve) curve.setName(newLegend) self.plot.addItem(curve) if w...
Python
1
BARINFO { pub_fn_bool_get_set!(fBarFocused, set_fBarFocused); pub_fn_bool_get_set!(fFocused, set_fFocused); } /// [`MENUINFO`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-menuinfo) /// struct. #[repr(C)] pub struct MENUINFO { cbSize: u32, pub fMask: co::MIM, pub dwStyle: co::M...
Rust
0
); if !op.succ.iter().any(|i| clock.covers(i)) { visible = true; } } OpType::Increment(inc_val) => { for id in &op.pred { // pred is always before op.id so we can see them if let Some(m...
Rust
0
today = 251 days = 16 * 365 + today print(f"pocet dni: {days}") print(f"pocet hodin: {days * 24}") print(f"pocet sekund: {days * 24 * 60 * 60}")
Python
1
impl realm::Widget for I { fn realm_id(&self) -> &'static str { "H.I" } } impl I { pub fn new(_req: &realm::Request) -> I { I {} } } <reponame>ubuntunux/Rust3DEngine<gh_stars>0 use std::fs; use std::rc::{Rc, Weak}; use std::cell::RefCell; use std::collections::HashMap; use std::path::{ ...
Rust
0
Public License for more details. // You should have received a copy of the GNU General Public License // along with Open Ethereum. If not, see <http://www.gnu.org/licenses/>. use std::collections::HashSet; use std::path::Path; use std::fs; use crypto::publickey::Address; use accounts_dir::{KeyDirectory, RootDiskDi...
Rust
0
# lists, sets, and tuples # collection = single "variable" used to store multiple values # List = [] ordered and changeable. Duplicates OK # Set = {} unordered and immutable , but Add/Remove OK. NO Duplicates # Tuple = () ordered and unchangeable. Duplicates OK. FASTER # Lists fruits = ["apple", "orange", "bana...
Python
1
--------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'ipyopenlayers', 'ipyopenlayers Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- ...
Python
1
# load modules from tableauscraper import TableauScraper as TS # Southwestern (SWH) url_swh = "https://public.tableau.com/views/COVID-19Dashboard-March2020/COVID-19Dashboard?:embed=y&amp;:showVizHome=no&amp;:host_url=https%3A%2F%2Fpublic.tableau.com%2F&amp;:embed_code_version=3&amp;:tabs=no&amp;:toolbar=yes&amp;:anima...
Python
1
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
Python
1
", "Browse my inventory, buy, sell or depart on your interstellar journey"]], ["Nebula Nova, The Cosmic Entrepeneur", "Nebula Nova", ["Salutations, fellow cosmic voyager!", "I am Nebula Nova, surveyor of all things celestial", "Looking to bargain or hoping to expand your cosmic collectio...
Python
1
is_alpha: bool) -> d3d12::D3D12_BLEND { use wgt::BlendFactor as Bf; match factor { Bf::Zero => d3d12::D3D12_BLEND_ZERO, Bf::One => d3d12::D3D12_BLEND_ONE, Bf::Src if is_alpha => d3d12::D3D12_BLEND_SRC_ALPHA, Bf::Src => d3d12::D3D12_BLEND_SRC_COLOR, Bf::OneMinusSrc if is_...
Rust
0
{:?}", why); } } } #[test] fn hamming_diff_multibyte() { match hamming("hamming", "h香mmüng") { Ok(distance) => { assert_eq!(2, distance); }, Err(why) => { panic!("{:?}", why); } } } #[test] fn hamming_unequal_length() { match hamming("ham...
Rust
0
# # Copyright OpenEmbedded Contributors # # SPDX-License-Identifier: MIT # import os from oeqa.selftest.case import OESelftestTestCase from oeqa.utils.commands import bitbake, get_bb_var import oeqa.utils.ftools as ftools class LayerAppendTests(OESelftestTestCase): layerconf = """ # We have a conf and classes di...
Python
1
te(|w| ..)` method takes [assist_debug_core_0_sp_min::W](assist_debug_core_0_sp_min::W) writer structure"] impl crate::Writable for ASSIST_DEBUG_CORE_0_SP_MIN {} #[doc = "ASSIST_DEBUG_CORE_0_SP_MIN"] pub mod assist_debug_core_0_sp_min; #[doc = "ASSIST_DEBUG_CORE_0_SP_MAX\n\nThis register you can [`read`](crate::generic...
Rust
0
# init_pg_checkpointer.py import os from langgraph.checkpoint.postgres import PostgresSaver, ConnectionPool from dotenv import load_dotenv from psycopg import Connection #https://github.com/langchain-ai/langgraph/issues/2887 load_dotenv() db_uri = os.getenv("DB_URI") if db_uri is None: print("DB_URI is not s...
Python
1
, corners_2d return corners_2d, np.transpose(corners_3d) def compute_orientation_3d(obj, calib): ''' Takes an object and a projection matrix (P) and projects the 3d object orientation vector into the image plane. Returns: orientation_2d: (2,2) array in image coord. orie...
Python
1
rmation about available fields see [mtdr](index.html) module"] pub struct MTDR_SPEC; impl crate::RegisterSpec for MTDR_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [mtdr::W](W) writer structure"] impl crate::Writable for MTDR_SPEC { type Writer = W; } #[doc = "`reset()` method sets MTDR to valu...
Rust
0
import os import unittest from betamax import Betamax from requests import Session class TestGZIPRegression(unittest.TestCase): def tearDown(self): os.unlink('tests/cassettes/gzip_regression.json') def test_saves_content_as_gzip(self): s = Session() with Betamax(s).use_cassette('gzip...
Python
1
the W_[16..51] // The lowest-index words involved will be W_[0..13] let mut new_word = |idx: usize, sigma_0_output: (CellValue16, CellValue16)| -> Result<Vec<(CellValue16, CellValue16)>, Error> { // Decompose word into (3, 4, 3, 7, 1, 1, 13)-bit chunks ...
Rust
0
import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty("voices") for voice in voices: print(voice, voice.id) engine.setProperty("voice", voice.id) engine.say("Hello World!") engine.runAndWait() engine.stop()
Python
1
import glob import pandas as pd import matplotlib.pyplot as plt import numpy as np import os # Define axial coordinates coords=[] for z in np.arange(32): coords.append((z/31)*180) # Obtain IPyC crack Rates path1_ipyc = r"./TRISO/results/particle*/_particle?_ipyc_cracking_0001.csv" path2_ipyc = r"./TRISO/results/pa...
Python
1
''' 题目描述 键盘输入一组整数(逗号分隔),编写程序对这些数据进行排序(不能直接调用Python中现成的sorted()函数或sort()方法, 自己选择冒泡排序、选择排序、插入排序中的一种算法),输出排序后的数据。 输入 键盘输入逗号间隔的整数 输出 排序后的列表 样例输入 12,34,8,13,21 样例输出 [8, 12, 13, 21, 34] ''' # nums=eval(input()) nums=[12,34,8,13,21] def bubble_sort(arr): """ 相邻两两比较,大的向右移动 从小到大 :param arr: :return: """...
Python
1
Clefs and transposition clef = { ( clef_spec | clef_middle | clef_transpose | clef_octave | clef_stafflines ) ~ ( WSP+ ~ clef )? } clef_spec = { ( ( ["clef="] ~ ( clef_note | clef_name ) ) | clef_name ) ~ clef_line? ~ ( ["+8"] | ["-8"] )? ~ ( WSP+ ~ clef_middle )? } clef_not...
Rust
0
} else { let x_priority = *self.priority.get(x).unwrap(); let y_priority = *self.priority.get(y).unwrap(); if x_priority <= 2 && y_priority <= 2 { // 演算子が連続する時 return Ok((false, pos)); } else if x_priority == ...
Rust
0
(&1.0)), delta_weights_row.iter_mut()) .foreach(|(prev_output, delta_weight)| { *delta_weight = // Individual input, magnified by the gradient and train rate learn_rate.0 * prev_output * gradient // Also add momentum which is a fraction of the previous delta weight + learn_mom.0 *...
Rust
0
present("exact") { sub_enabled |= Enabled::exact() } if matches.is_present("pattern") { sub_enabled |= Enabled::pattern() } // Default to all if nothing is set so far. if sub_enabled.is_empty() { sub_enabled |= Enabled::all() } ...
Rust
0
aths() step.context.settings = step.context.plugin.make_settings(from_dict=local_paths) # Also have to patch here to prevent real downloads. message = "Download from Hugging Face was attempted. Expected no downloads." patcher = mock.patch( "huggingface_hub.file_download._download_to_tmp_and_mov...
Python
1
pub fn drag<T: Num, T1: Into<Option<(T, T)>>>( &mut self, id: Id, label: &str, range: T1, data: &mut T, ) { let range = range.into(); Drag::new(id).label(label).range(range).ui(self, data) } } //! SM3 Cryptographic Hash Algorithm //! //! https://www...
Rust
0
0J\xfe\xe0\x0f\x02L}" b"\xd9\xed\xd2L\xa7\xcf" ) assert ( playbook >> events.DataReceived(tctx.client, data) << commands.Log( f"Client QUIC handshake failed. Invalid handshake received, roaming not supported. ({data.hex()})", ...
Python
1
h_options(model: &Model, options: &InterpreterOptions) -> Result<Self> { Self::create(model, Some(options)) } pub fn default_options() -> InterpreterOptions { InterpreterOptions::default() } pub fn allocate_tensors(&mut self) -> Result<()> { unsafe { bail!(@check C:...
Rust
0
uct FixedPart<BoundedString> { pub id: PartId, pub z: ZIndex, pub src: BoundedString, } #[derive(Encode, Decode, RuntimeDebug, TypeInfo, Clone, PartialEq, Eq, MaxEncodedLen)] pub enum EquippableList<BoundedCollectionList> { All, Empty, Custom(BoundedCollectionList), // Custom(Vec<CollectionId>), } // #[cfg_att...
Rust
0
import pandas as pd import matplotlib.pyplot as plt from prophet import Prophet # 读取CSV文件 file_path = r"C:\Users\23991\OneDrive\桌面\Python\venv\shuxuejianmo\shu_xue_jian_mo\Prophet\1.csv" df = pd.read_csv(file_path) # 重命名列以符合Prophet的要求 df = df.rename(columns={'DS': 'ds', 'Y': 'y'}) # 创建Prophet模型 model = Prophet() # ...
Python
1
s = {k: v for k, v in coeffs.items() if v is not None} # Raise error for invalid key combinations coeffs = _fix_coeffs(coeffs) if (not _have_c99_complex and any(np.iscomplexobj(v) for v in coeffs.values())): real_coeffs = {k: v.real for k, v in coeffs.items()} imag_coeffs = {k:...
Python
1
def solution(n, words): # 앞에 얘기한 단어를 중복해서 말하면 탈락이므로 집합으로 말한 단어를 저장 SET = {words[0]} for i in range(1, len(words)): # 전 단어의 끝말과 시작이 다른 단어를 얘기하거나 이미 말한 단어를 얘기하면 탈락 if words[i-1][-1] != words[i][0] or words[i] in SET: # 탈락자의 번호는 순서를 사람수로 나눈 나머지, 차례는 몫 return [i%n+1, i//n...
Python
1
def fizz_buzz(): # ✅↓ Write your code here ↓✅ for i in range(1, 101): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i) # ❌↓ DON'T CHANGE THE CODE BELOW ↓❌ ...
Python
1
t_key ^= zobrist_hasher.get_val_for_castling(CastlingType::BlackKingSide) } if board.black_queen_side_castle { board.zobrist_key ^= zobrist_hasher.get_val_for_castling(CastlingType::BlackQueenSide); } Ok(board) } fn piece_from_fen_string_char(piece: char) -> Option<...
Rust
0
#!/usr/bin/env python3 # =============================================================== # Plot \psi(x) for a chosen particle as a function of x # =============================================================== import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatabl...
Python
1
rent directions (forward/reverse). - Create two scenario objects, one with direction="forward" and another with direction="reverse". - Mock TokenCounter.count to allow all content to fit. - Assert that the direction-specific text (e.g., "【模式】\nforward" or "【模式】\nreverse") appears in the respective pro...
Python
1
: model_lora_1, clip_lora_1, vae = self.load_lora(ckpt_name, lora_name_1, strength_model_1, strength_clip_1) model_lora_2, clip_lora_2, = self.add_lora(model_lora_1, clip_lora_1, lora_name_2, strength_model_2, strength_clip_2) model_lora_3, clip_lora_3, = self.add_lora(model_lora_2, ...
Python
1
) pub fn builder() -> crate::input::get_bucket_policy_status_input::Builder { crate::input::get_bucket_policy_status_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for GetBucketPolicyStatus { type Output = ...
Rust
0
# DO NOT EDIT # This file is generated by the updatebundle commands.py command __plotlyjs_version__ = "3.1.0"
Python
1
# Avoid re-instantiating this class every time it's seen node._explicit_inference = lambda node, context: iter([class_def]) return iter([class_def]) def _looks_like_typing_cast(node: Call) -> bool: return isinstance(node, Call) and ( isinstance(node.func, Name) and node.func.name == "ca...
Python
1
.status()?; log::debug!("Checking ECP5 status after programming ({:08X})", status.0); match status.bse_error() { BSEError::NoError => (), error => { log::error!("BSE error present: {:?}", error); return Err(Error::BadStatus); } ...
Rust
0
-> dict[str, Any]: return self.full_video_clips.metadata def _select_fold(self, video_list: list[str], annotations_dir: str, fold: int, train: bool) -> list[int]: target_tag = self.TRAIN_TAG if train else self.TEST_TAG split_pattern_name = f"*test_split{fold}.txt" split_pattern_path...
Python
1
in [("go to ", "go "), ("to the ", "to "), ("from the ", "from "), ("to a ", "to "), ("from a ", "from "), ("with the ", "with "), ("with a ", "with ")]: new_txt = new_txt.replace(val_old, val_new) if new_txts[0] == "use" and "with" not in new_txts and actor is not None: # If no 'with'...
Python
1
_arr = ReadWrite_h5.get_RasterArr(r, lt_x=int(r_lt_x), lt_y=int(r_lt_y), rt_x=int(r_rb_y), rt_y=int(r_rb_x)) sp_arr = ReadWrite_h5.get_RasterArr(sp, lt_x=int(sp_lt_x), lt_y=int(sp_lt_y), rt_x=int(sp_rb_y), rt_y=int(sp_rb_x)) wd_arr = ReadWrite_h5.get_RasterArr(wd, lt_x=int(wd_lt_x), lt_y=int(wd_lt_y), rt_x=int(...
Python
1
ecode_binary(bytes: &[u8]) -> Self; } impl BinaryDecode for u16 { fn decode_binary(bytes: &[u8]) -> Self { LittleEndian::read_u16(bytes) } } pub trait Max { fn max() -> f32; } impl Max for u16 { fn max() -> f32 { u16::MAX as f32 } } impl GLTF { pub fn new(gltf_path: PathBuf) ...
Rust
0
# instance attribute agr likha ho tw wo pehly waly lass attribute ko over write kr deta hy means ke hta kr khud ajata hy class employee : lang = "py" salary = 12000 rohan = employee() rohan.name = "rohan" # this is instance attribute rohan.lang = "java" print(rohan.name , rohan.salary , rohan.lang)
Python
1
{ ($env:expr, $cls:expr, $mid:expr $(, $arg:expr )*) => ( jni_call_static_method!($env, CallStaticVoidMethodA, $cls, $mid $(, $arg)*); ); } #[macro_export] macro_rules! jni_call_static_boolean_method { ($env:expr, $cls:expr, $mid:expr $(, $arg:expr )*) => ( jni_call_static_method!($env, Cal...
Rust
0
, full_output, **kwargs): raise NotImplementedError( "Fantasy observation updates not yet supported for models using SGPRPredictionStrategy" ) def exact_prediction(self, joint_mean, joint_covar): from ..kernels.inducing_point_kernel import InducingPointKernel # Find the...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 更新合约列表脚本 根据当前主力合约和未来合约数据更新配置 """ import sys import json from pathlib import Path from datetime import datetime from typing import List, Dict, Set # 添加项目根目录到路径 project_root = Path(__file__).parent.parent sys.path.insert(0, str(project_root)) # 当前主力合约 current_main_con...
Python
1
diverge_at: Option<usize>, ) -> EpochIds<MockPeer> { let mut ids = vec![]; for i in first_epoch_number..first_epoch_number + len { let mut epoch_id = [0u8; 32]; epoch_id[0..8].copy_from_slice(&i.to_le_bytes()); if diverge_at ...
Rust
0
)); assert_eq!(actual.out, "spam.txt"); } #[test] fn returns_filestem_of_path_with_empty_prefix_and_suffix() { let actual = nu!( cwd: "tests", pipeline( r#" echo "menu/spam.txt" | path filestem -p "" -s "" "# )); assert_eq!(actual.out, "spam.txt")...
Rust
0
from odoo import http from odoo.http import request from odoo.addons.web.controllers.binary import Binary class PointOfSaleBinary(Binary): @http.route([ '/web/image/pos.config/<id>/<string:field>', '/web/image/pos.config/<id>/<string:field>/<int:width>x<int:height>'], type='http', auth="public") ...
Python
1
: str) -> int | None: logger.warning( f"DEPRECATED: load_message_id_from_file called for '{filename_key}'. " "Message IDs are now managed in bot_state.json via user_manager. Use chat_id specific functions." ) return None def save_message_id_to_file(message_id: int, filename_key: str): ...
Python
1
}; } if value.is_number() && value.is_f64() { return Ok(Some(value.as_f64().unwrap() as f32)); } Err(DeError::custom("Invalid value for field 'cvss'!")) } fn from_string<'de, T, D>(deserializer: D) -> StdResult<T, D::Error> where T: FromStr, T::Err: fmt::Display, D: Deserializer<'...
Rust
0
onSessionPerSec = _NsPlyMonSessionPerSec_Object( (1, 3, 6, 1, 4, 1, 3224, 10, 2, 1, 9), _NsPlyMonSessionPerSec_Type() ) nsPlyMonSessionPerSec.setMaxAccess("read-only") if mibBuilder.loadTexts: nsPlyMonSessionPerSec.setStatus("current") _NsPlyMonSessionPerMin_Type = Integer32 _NsPlyMonSessionPerMin_Object = ...
Python
1
dash = "-" design = ".|." welcome = "WELCOME" row , column = (input().split()) row = int(row) column = int(column) """ Size: 11 x 33 ---------------.|.--------------- ------------.|..|..|.------------ ---------.|..|..|..|..|.--------- ------.|..|..|..|..|..|..|.------ ---.|..|..|..|..|..|..|..|..|.--- ---...
Python
1
"Matrix multiply incompatible dimensions: A = {:#?}, B = {:#?}", dim1, dim2 ); let m = dim1.0; let k = dim1.1; let n = dim2.1; let mut res = $MatType::<$Scalar>::from_dimension(m, n); let rsa = self.ro...
Rust
0
import asyncio import threading import time from django.http import FileResponse, HttpResponse, StreamingHttpResponse from django.urls import path from django.views.decorators.csrf import csrf_exempt def hello(request): name = request.GET.get("name") or "World" return HttpResponse("Hello %s!" % name) def h...
Python
1
"use" ]; static UNSAFE_KEY_WORD: &'static [(&'static str, &'static str)] = &[ ("//extends", "enum"), ("//extends", "struct"), ]; static UNSTABLE_KEY_WORD: &'static [(&'static str, &'static str)] = &[ ("//box", "box"), ("//extends", "extends"), ]; #[derive(Debug)] pub enum Expr { Key(String),...
Rust
0
ew_to_asset_balance); // --------------------- 更新 --- ここまで } else { // --------------------- 更新 // 更新する値が正常であることが確認済みであることが必須! <MyAssetBalances<T>>::insert((sender.clone(), asset_id), new_my_asset_balance); <MyAssetBalances<T>>::insert((to.clone(), asset_id), new_to_asset_balance); // --...
Rust
0
tn_Net(L = size[1], D = size[2], dropout = dropout, n_classes = n_classes) fc.append(attention_net) self.attention_net = nn.Sequential(*fc) bag_classifiers = [nn.Linear(size[1], 1) for i in range(n_classes)] #use an indepdent linear layer to predict each class self.classifiers = nn.Modul...
Python
1
References ---------- .. [1] Parent, S.É., Parent, L.E., Egozcue, J.J., Rozane, D.E., Hernandes, A., Lapointe, L., Hébert-Gentile, V., Naess, K., Marchand, S., Lafond, J., Mattos, D., Barlow, P., Natale, W., 2013. The plant ionome revisited by the nutrient balance concept. Front. P...
Python
1
s will never actually modify or drop data in `self`. All /// that changes is the type, potentially making more methods available on /// the returned `Gbl`. /// /// This will not modify the encryption typestate `E`. It works with any `E` /// and simply passes it through. pub fn into_not_signed(se...
Rust
0
class Solution: def climbStairs(self, n: int) -> int: a = [0]*(n+1) a[0] = 1 a[1] = 1 for i in range(2,n+1): a[i] = a[i-1] + a[i-2] return a[n]
Python
1
pub close: bool, pub attribs: HashMap<~str, ~str>, pub transform: Option<Transform> } pub struct CubicBezier { } fn to_int(b: bool) -> int { if b == true { 1 } else { 0 } } <gh_stars>0 use crate::{ client_proxy::ClientProxy, commands::{subcommand_execute, Command}, }; use chrono::{DateTime, Utc...
Rust
0
ee into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'sentiment.tex', u'sentiment Documentation', u'lpty', 'manual'), ] # -- Options for manual page output --------------------------------------...
Python
1
from shared.models.proxy import AnthropicRequest, AnthropicResponse from shared.log_config import get_logger logger = get_logger(f"proxy.{__name__}") import httpx import json from fastapi import HTTPException, status async def send_to_anthropic(request: AnthropicRequest) -> AnthropicResponse: """ Send a pa...
Python
1
e) is None # and model_fields_set contains the field if self.price_high is None and "price_high" in self.model_fields_set: _dict['price_high'] = None # set to None if price_low (nullable) is None # and model_fields_set contains the field if self.price_low is None and...
Python
1
ection, class_embed_type=class_embed_type, addition_embed_type=addition_embed_type, addition_time_embed_dim=addition_time_embed_dim, num_class_embeds=num_class_embeds, upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shi...
Python
1
ersion::FIX42, 3 => FixVersion::FIX43, 4 => FixVersion::FIX44, 5 => FixVersion::FIXT11, _ => unimplemented!(), } } } // impl<const V1: u8, const V2: u8> From<FixVersion<V2>> for FixVersion<V1> { // fn from(other: FixVersion<V2>) -> Self { // match...
Rust
0
d_fn.to_path_buf(); json_fn.set_extension("json"); File::create(json_fn) .expect("Failed to open JSON output file") .write_all(json::to_string_pretty(&v).unwrap().as_bytes()) .expect("Failed to write to JSON output file"); } use liturgy::{Psalm, PsalmSection, PsalmVerse, Reference, Sourc...
Rust
0
import heapq # Define the matrix map of the city city_map = [ [float('inf'), float('inf'), 6, float('inf'), 7, float('inf'), 9, 4, 11], [float('inf'), 3, float('inf'), 6, 5, 3, 15, float('inf'), 3], [float('inf'), float('inf'), float('inf'), 4, float('inf'), 9, 1, 8, float('inf')], [15, 18, 1, 6, 5, 1...
Python
1
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implemen...
Python
1
ile-like object :param captions: Iterable of `Caption` objects :param styles: Iterable of `Style` objects :param header_comments: the comments for the header :param footer_comments: the comments for the footer """ f.write( to_str(captions, styles, header_com...
Python
1
_canvas().build().unwrap(); Self { canvas: canvas } } pub fn set_color(&mut self, color: DisplayColor) { self.canvas .set_draw_color(DisplayColor::to_sdl_color(color)) } pub fn draw_pixel(&mut self, x: i32, y: i32, color: DisplayColor) { self.set_color(color); ...
Rust
0
ited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unk...
Rust
0
= match localzone::get_local_zone() { Some(tz) => match tz.parse::<Tz>() { Ok(tz) => { let dt = Local::today().naive_local(); tz.offset_from_utc_date(&dt).abbreviation().to_string() } Err(_) => "UTC".to_string(), ...
Rust
0
import pytest from sqlframe.standalone import functions as F from sqlframe.standalone.window import Window, WindowSpec @pytest.mark.parametrize( "func, expected", [ (WindowSpec().partitionBy(F.col("cola"), F.col("colb")), "OVER (PARTITION BY cola, colb)"), (Window.partitionBy(F.col("cola"), F...
Python
1
""" Test that ALS initial memory footprint does not exceed a given amount of memory when runtime indexing is disabled. """ from drivers.pylsp import ( ALSLanguageClient, ALSClientServerConfig, test, get_ALS_memory_footprint, ) import os async def check_memory_footprint( lsp: ALSLanguageClient, ...
Python
1
import asyncio import io import os import sys from contextlib import ExitStack, redirect_stderr, redirect_stdout import pytest from mode.utils.mocks import patch def test_main(*, app, loop): from proj323 import main neu_loop = asyncio.set_event_loop(asyncio.new_event_loop()) # noqa # must use the event...
Python
1
#!/usr/bin/env python import sys from simple_agent.tools import ToolLibrary if __name__ == "__main__": tool = ToolLibrary() try: if len(sys.argv) > 1: tool_name = sys.argv[1] output = tool.get_tool_info(tool_name) else: output = tool.get_tool_info() ...
Python
1
mut XcmsColor, _2: *mut XcmsColor, _1: c_uint) -> c_int, pub fn XcmsCIELabWhiteShiftColors (_7: XcmsCCC, _6: *mut XcmsColor, _5: *mut XcmsColor, _4: c_ulong, _3: *mut XcmsColor, _2: c_uint, _1: *mut c_int) -> c_int, pub fn XcmsCIELuvClipL (_5: XcmsCCC, _4: *mut XcmsColor, _3: c_uint, _2: c_uint, _1: *mut c_int) -> ...
Rust
0