text
string
label_name
string
labels
int64
N8 => { let mode = cmd - RS_OP_COPY_N1_N1; let offset_len = 1 << (mode / 4) as usize; let len_len = 1 << (mode % 4) as usize; let offset = read_varint!(offset_len, "copy offset"); let len = read_varint!(len_len, "copy length"); ...
Rust
0
""" Creates an IC for the particle splitting test. This test creates a single heavy particle, that should split into 16 counterparts, surrounded by a grid of 16 * 16 * 16 particles. """ import numpy as np import unyt from swiftsimio import Writer NUMBER_OF_PARTICLES = 16 # in 1D TOTAL_NUMBER_OF_PARTICLES = NUMBER_...
Python
1
std::time::Duration::from_millis(100)); let (c, r) = { (self.0.mock_cwnd, self.0.mock_rate) }; self.0.load_primitives( libccp::Primitives::default() .with_packets_acked(0) .with_rtt_sample_us(2) .with_bytes_acked(ACKED_PRIMITIVE) ...
Rust
0
nst a hardware Cortex-M0 to make sure it's actually up to spec? */ // String representation of ops for use in debug output const OPCODES: &'static [&'static str] = &[ "SXTB <Rd>,<Rm> T1", "SXTH <Rd>,<Rm> T1", "UXTB <Rd>,<Rm> T1", "UXTH <Rd>,<Rm> T1", ]; // Simple constant for number of opcodes tested...
Rust
0
import openai import json # 读取 OpenAI API Key from utils import config_manager config_manager = config_manager.ConfigManager() api_key = config_manager.get_api_key("openai") # 初始化 OpenAI 客户端 client = openai.OpenAI(api_key=api_key) # 替换为你的微调模型 ID fine_tuned_model = "ft:gpt-4o-2024-08-06:personal:balanced:B3kEd6za" #...
Python
1
_PrivateKey( bio_ptr, ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), ); assert_ne!(pkey_ptr, ptr::null_mut()); evp::mesalink_EVP_PKEY_free(pkey_ptr); bio::mesalink_BIO_free(bio_ptr); } #[test] fn pem_read_private_key() { ...
Rust
0
""" Unibot, an open-source colorbot. Copyright (C) 2025 vike256 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 3 of the License, or (at your option) any later ...
Python
1
is_empty() && self.got_max_timestamp.is_empty() } pub fn tas_recoverer( &mut self, write_id: Uuid, recoverer: Box<(Uuid, Box<[OrderIndex]>)>, old_recoverer: Option<Uuid>, ) -> Result<u64, Option<Uuid>> { use std::collections::hash_map; match (self.re...
Rust
0
y_static! { static ref UID: AtomicU64 = AtomicU64::new(1); } pub fn NewUID() -> u64 { return UID.fetch_add(1, atomic::Ordering::SeqCst); } pub fn Init() { //self::fs::Init(); } #[derive(Clone, Copy, Debug)] pub struct WaitingMsgCall { pub taskId: TaskIdQ, pub addr: u64, pub len: usize, pu...
Rust
0
, T_CHOICE, T_PROMPT, T_MENU, T_COMMENT, T_SOURCE, T_MAINMENU)) # Matches the initial token on a line; see _tokenize(). Also eats trailing # whitespace as an optimization. _initial_token_re_match = re.compile(r"[^\w]*(\w+)\s*").match # Matches an identifier/keyword optionally preceded by white...
Python
1
ncomplete dates will be completed for you e.g. "2002-04".', "type": PartialISODatetimeType(as_string=True), "default": None, }, ], ) YOUTUBE_CHANNELS_SUBCOMMAND = youtube_api_subcommand( "channels", "minet.cli.youtube.channels", title="YouTube Channels Command", desc...
Python
1
ill = Permill::from_percent(0); pub const MaxApprovals: u32 = 100; } impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = NativeCurrency; type ApproveOrigin = EnsureRoot<AccountId>; type RejectOrigin = EnsureRoot<AccountId>; type Event = Event; type O...
Rust
0
def derivative(xs: list): """ xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] """ return [x * (len(xs) - 1 - i) fo...
Python
1
info!("Adding block {}", entity.hash); repository.save_next(&mut entity, &mut previous)?; Ok(()) }, None => { info!("Adding block {}", entity.hash); repository.save(&entity)?; match block.previous().is_empty() { tru...
Rust
0
# n = 0 # c = 0 # for i in range(5): # n = int(input('Digite um numero: ')) # if n % 2 == 0: # print(f'Numero par encontrado: {n}, laço interrompido.') # break # else: # print(f'Numero impar, segue o laço.') # else: # print('Apenas impares.') # -------------------------------------------------------...
Python
1
}, }; if from_json { return utils::executable_or_exists(cmd.as_path(), Some(data.json.root.as_path())) .wrap_err("Invalid configuration for field 'command'") .suggestion( "When using relative paths for the field 'command' please \ mak...
Rust
0
- Message Link: {future_task['message_link']}\n\n" future_message += f"Total {future_active} Future Tasks, type '/stop future (active ID)' to stop any future task!" file_name = f"{round(time.time())}.txt" if not active_message and not future_message: await message.reply("__No any task ❕__") ...
Python
1
st_refresh.text(f"Last refreshed at: {time.strftime('%Y-%m-%d %H:%M:%S')}") # Fetch voting statistics voters_count, candidates_count = fetch_voting_stats() # Display total voters and candidates metrics st.markdown("""---""") col1, col2 = st.columns(2) col1.metric("Total Voters", voters_count) ...
Python
1
releases/download/{}/{}", org, name, version, artifact ), ) } } impl<'a> DownloadManager<'a> { pub fn android_jar(&self) -> Result<()> { let dir = self.env.android_sdk(); let sdk = self.env.target_sdk_version(); let path = dir .join("platf...
Rust
0
8]) -> Token { token - Blinding::new(data) } /// Removes a blinding factor to the token #[wasm_bindgen] pub fn remove_blinding(token: Token, data: &[u8]) -> Token { token + Blinding::new(data) } /// Creates a proof using a nonce received from a verifier #[wasm_bindgen] pub fn create_proof(token: Token, id: &[...
Rust
0
etime = time.strftime('%Y-%m-%d %X') # sql查询日志目录 log_dir = '{}/logs/sql_log/{}'.format(_BASE_DIR, time.strftime('%Y%m')) # 目录不存在时创建 if not os.path.exists(log_dir): os.makedirs(log_dir, 0o600) with open('{}/{}.log'.format(log_dir, cur_datetime[8:10]), 'a') as fp: ...
Python
1
= from / (self.map_max_column + 1); let max_x = to_row.max(from_row); let min_x = to_row.min(from_row); let max_y = to_column.max(from_column); let min_y = to_column.min(from_column); let temp_min = (max_x - min_x).min(max_y - min_y); let temp_max = (max_x - min_x)...
Rust
0
_abs_taylor_rule def _select_n_taylor_rule(primal_in, series_in, **params): b, *cases = primal_in primal_out = lax.select_n(b, *cases) sel = lambda _, *xs: lax.select_n(b, *xs) series_out = [sel(*terms_in) for terms_in in zip(*series_in)] return primal_out, series_out jet_rules[lax.select_n_p] = _select_n_t...
Python
1
Ok(()) } pub fn create_account( &self, account_create: &sessionsrv::AccountCreate, ) -> SrvResult<sessionsrv::Account> { let conn = self.pool.get(account_create)?; let rows = conn.query( "SELECT * FROM select_or_insert_account_v1($1, $2)", &[&ac...
Rust
0
).await, Ok(Some(fidl_fuchsia_net_interfaces::Event::Changed( fidl_fuchsia_net_interfaces::Properties { id: Some(id), online: Some(false), .. }, ))) if id == loopback_id => () ); } enum ForwardingConfiguration { BothIfaces(...
Rust
0
n(self._q_values, {self._state: state}) return np.argmax(q_values) def store(self, state, action, reward, next_state, terminal, eval=False, curr_reward=False): if not eval: self._replay_buffer.add(state, action, reward, next_state, terminal) def update(self): states, action...
Python
1
, w = decoder_initial(x.size(0)) # out_list to store outputs out_list=[] for j in range(y.size(1)): # for all sequences """ decoder_in (Variable): [b] encoded (Variable): [b x seq x hid] input_out (np.array): [b x seq] s (Variable): [b...
Python
1
tion", STORED | INDEXED); builder.new_attribute("timestamp", STORED); builder.build() }; let database = Database::create(&rocksdb_path, schema.clone())?; let tokenizer_builder = DefaultBuilder::new(); let update_path = dir.path().join("update.sst"); let...
Rust
0
#!/usr/bin/env python3 import serial import sys import time import os import curses from pynput import keyboard active = 1 command = 0 def on_press(key): global ser,command if key == keyboard.Key.up: command = command | 1 if key == keyboard.Key.down: command = command | 2 if key == keyboard.Key.righ...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayInsSceneClaimApplyResponse(AlipayResponse): def __init__(self): super(AlipayInsSceneClaimApplyResponse, self).__init__() self._claim_report_no = None se...
Python
1
| (_, "xz", _) | (_, "html", _) => None, // Some weird directories that happen to match the locale (n, s, "5man") | (n, s, "c") | (n, s, "man1") | (n, s, "man2") | (n, s, "man3") | (n, s, "man4") | (n, s, "man5")...
Rust
0
arr = [1, 2, 3,4,5] total_sum = sum(arr) result = 0 for num in arr: total_sum -= num print(total_sum) result += num * total_sum print("Sum of product of all pairs:", result) # Example usage
Python
1
-local address returned is constructed from this device's MAC /// address. pub(crate) fn get_ipv6_link_local_addr<D: EventDispatcher>( ctx: &mut Context<D>, device_id: u64, ) -> Ipv6Addr { // TODO(brunodalbo) the link local address is subject to the same collision // verifications as prefix global addr...
Rust
0
''' 该程序说明:使用点亮一颗 LED 在线文档:https://docs.geeksman.com/esp32/MicroPython/04.esp32-micropython-LED.html ''' from machine import Pin # 声明一个引脚对象 pin_12 = Pin(15, Pin.OUT) # 输出高电平 pin_12.value(1)
Python
1
ogram_object.license.clone(), program_object.kernel_version, ) .expect("Could not load test program"); let p_type = std::fs::read_to_string((*PMU_KTYPE_FILE).as_path()) .unwrap_or("6".to_string()) // when using debugfs .trim() .to_string() ...
Rust
0
AX_TEXTURE_2D_LINEAR_PITCH = 72 CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_MIPMAPPED_WIDTH = 73 CU_DEVICE_ATTRIBUTE_MAX_MAX_TEXTURE_2D_MIPMAPPED_HEIGHT = 74 CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75 CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76 CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_1D_MIPMAPPED_WIDTH = 77 CU_DEVICE_ATTRI...
Python
1
} => assert_eq!(msg, "Temporarily unavailable"), err => panic!("Incorrect error returned: {:?}", err), }; } #[test] fn do_addr_humanize_fails_for_input_too_long() { let api = MockApi::default(); let (env, mut instance) = make_instance(api); let sour...
Rust
0
_max="1") with self.assertRaises(ValueError): _ = AdversarialPatchPyTorch(ptc, patch_type="triangle") # AdversarialPatchNumpy with self.assertRaises(ValueError): _ = AdversarialPatchNumpy(ptc, rotation_max="1") with self.assertRaises(ValueError): _ ...
Python
1
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # myapp path('', include('mysite.urls', namespace='mysite')), ]
Python
1
hi_cell); // Imported Part { let imported_expected = (u128::from(constants::INITIAL_TOTAL_SUPPLY) * 725 / 1000) as u64; let mut imported_cells = data::GENESIS_ALLOCATE .lines() .map(|line| { let mut part = line.split(','); let addr = part ...
Rust
0
= sub_matches .value_of("file_concurrency") .map(FromStr::from_str) .unwrap_or(Ok(8)) .expect("failed to parse file concurrency"); let part_concurrency = sub_matches .value_of("part_concurrency") .map(FromStr::from_str) .unwrap_or(Ok(8)) .expect("fail...
Rust
0
blurz! Is the bluetooth service running?", "blurz_err" => e ))?; let stat_adapter: &'static BlurzBluetoothAdapter = Box::leak(Box::new(adapter)); Ok(Self { opts, session: stat_session, adapter: stat_adapter, }) } } impl<'a, O...
Rust
0
state.require_path.clone() }) } pub fn init(target_option:Option<PathBuf>) -> Result<()> { // TODO: Check fused exe first if let Some(target) = target_option { print_nonfatal(mount(target))?; } set_identity("rovr".to_string()); set_require_path("?.lua;?/init.lua".to_string()); Ok(()) } <reponame>Eric-Arel...
Rust
0
let mut data = BTreeMap::new(); let user = User { id: Uuid::new_v4(), mail: "<EMAIL>".to_string(), name: "<NAME>".to_string(), password: "<PASSWORD>".to_string(), }; data.insert("user".to_string(), user.to_json()); data } #[allow(dead_code)] fn main() { let ...
Rust
0
::SymbolPercent => 9, TokenInner::SymbolMinus | TokenInner::SymbolPlus => 8, TokenInner::SymbolDoubleLt | TokenInner::SymbolDoubleGt => 7, TokenInner::SymbolAmp => 6, TokenInner::SymbolCaret => 5, TokenInner::SymbolPipe => 4, TokenInner::SymbolDoubleEq | TokenInn...
Rust
0
peration.rotate_point_cloud_and_gt(batch_input_data, batch_data_gt) batch_input_data, batch_data_gt, scales = point_operation.random_scale_point_cloud_and_gt(batch_input_data, batch_data_gt, ...
Python
1
w model and save the annotated video.""" model = load_roboflow_model() # Run inference on the video file job_id, signed_url, expire_time = model.predict_video( input_path, fps=5, prediction_type="batch-video", ) # Poll for results until video inference is complete resul...
Python
1
* abstracts over the hard-fork. #[superstruct( variants(Base, Altair, Merge), variant_attributes( derive( Debug, Clone, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom, Derivative, ...
Rust
0
name = { srgb: $srgb, vert: $filename, frag: $filename }); }; } use std::env; use std::fs::File; use std::io::{BufRead, BufReader}; use std::usize; fn read_input() -> Vec<usize> { let args: Vec<String> = env::args().collect(); let input = File::open(&args[1]).expect("Cannot open file"); let input = Buf...
Rust
0
data): if desc["type"].value == ASF_Descriptor.TYPE_BYTE_ARRAY: # Skip binary data return key = desc["name"].value if "/" in key: # Replace "WM/ToolName" with "ToolName" key = key.split("/", 1)[1] if key in self.SKIP_EXT_DESC: #...
Python
1
let names = entries.iter().map(|r| r.file_name()).collect::<Vec<_>>(); assert_eq!(names, ["long.txt", "short.txt", "very", "very-long-dir-name", "moved-file.txt"]); assert!(root_dir.rename("moved-file.txt", &root_dir, "moved-file.txt").is_ok()); let new_stats = fs.stats().unwrap(); assert_eq!(new_s...
Rust
0
::BoxStream; use sqlx::{Database, Executor, Result}; pub use ormx_macros::*; #[doc(hidden)] pub mod exports { pub use crate::query2::map::*; pub use futures; } #[cfg(any(feature = "mysql", feature = "postgres"))] mod query2; #[cfg(feature = "mysql")] pub type Db = sqlx::MySql; #[cfg(feature = "postgres")] p...
Rust
0
8], Self, ParserError> { let (rem, length) = be_u32(input)?; let (rem, branch) = { let (rem, branch) = take(32usize)(rem)?; (rem, array_ref!(branch, 0, 32)) }; let (rem, endorsement_tag) = be_u8(rem)?; if endorsement_tag != 0x00 { return Err(Pa...
Rust
0
64::<86400>")] pub intermediate_key_rotation_seconds: u64, #[serde(default = "make_default_u64::<31536000>")] pub customer_key_rotation_seconds: u64, #[serde(default = "make_default_u64::<1>")] pub customer_key_rotation_throttle_qps: u64, #[serde(default = "make_default_u64::<86400>")] pub d...
Rust
0
_corners() { common::check_text_corners(&FONT_6X8); } #[test] fn correct_inverse_colored_m() -> Result<(), core::convert::Infallible> { let font = &FONT_6X8; let mut display = MockDisplay::new(); let style = MonoTextStyleBuilder::new() .font(font) .text_color(BinaryColor::Off) ....
Rust
0
#[test] fn build_acceptance_mechanisms_request_with_context() { let ledger_service = LedgerService::new(); let expected_result = json!({ "type": TXN_AUTHR_AGRMT_AML, "aml": _aml(), "version": VERSION, "amlContext": CONTEX...
Rust
0
x00" as *const u8 as *const i8) } unsafe extern "C" fn do_cidrange( mut cmap: *mut CMap, mut input: *mut ifreader, mut count: i32, ) -> i32 { let mut tok: *mut pst_obj = 0 as *mut pst_obj; let mut codeLo: [u8; 127] = [0; 127]; let mut codeHi: [u8; 127] = [0; 127]; let mut dim: i32 = 0; l...
Rust
0
from tkinter import Frame, Canvas, Scrollbar from tkinter import VERTICAL, FLAT, NS, NW, EW def scroll_cont(frame, canvas_size="8c"): """Return Scrollable Container""" # Frame for holding Canvas frame_canvas = Frame(frame, bd=5, relief=FLAT) frame_canvas.rowconfigure(0, weight=1) frame_canvas.colu...
Python
1
/// let message = client /// .create_message(channel_id) /// .content("Twilight is best pony")? /// .tts(true) /// .exec() /// .await?; /// # Ok(()) } /// ``` /// /// # Errors /// /// The method [`content`] returns an error of type /// [`MessageValidat...
Rust
0
pub struct PbsJobRunner { job_no: Option<u32>, exec_node: Option<String>, } impl PbsJobRunner { pub fn create() -> Result<PbsJobRunner, String> { Ok( PbsJobRunner{ job_no: None, exec_node: None, } ) } fn write_starter_file(&s...
Rust
0
as f32, }, seed: passed_frames as f32 / FRAMERATE as f32, }; common.frame_data_buffer.upload(devcon, common.frame_data); let mut player_generator_map = PlayerGeneratorMap::new(generator_map); for active_clip in player_clip_map.active_clips() { player_generator_map.take( ...
Rust
0
print(stdOutput("error")+"Java 8 is required, Java version found "+version_no);exit() print(stdOutput("info")+"\033[0mGenerating APK") outFileName = output if output else "karma.apk" que = queue.Queue() t = threading.Thread(target=executeCMD,args=["java -jar Jar_utils/apktool.jar b Compiled_apk -o "+ou...
Python
1
import gym import random import numpy as np import time from collections import deque import pickle from collections import defaultdict EPISODES = 20000 LEARNING_RATE = .1 DISCOUNT_FACTOR = .99 EPSILON = 1 EPSILON_DECAY = .999 def default_Q_value(): return 0 if __name__ == "__main__": random.seed(1) ...
Python
1
or not found_pred_col: raise ValueError("Could not find the required columns in the DataFrame.") evaluator = EvaluationMetrics( np.asarray(predictions_df[found_true_col].values, dtype=int), np.asarray(predictions_df[found_pred_col].values, dtype=int) ) confusion = evaluator.get...
Python
1
: rulox [script]"); exit(64); } len if len == 2 => { clirulox.run_file(&args[1]); } _ => { clirulox.run_prompt(); } } } fn main() { let _ = r#" this is a very long string exceeded maximum width in this case maximum 100. (current this li...
Rust
0
erialize)] #[allow(missing_docs)] pub struct ThrottlingData { pub periods: u64, pub throttled_periods: u64, pub throttled_time: u64, } /// General CPU statistics for the container. #[derive(Debug, Clone, Serialize, Deserialize)] #[allow(missing_docs)] pub struct CPUStats { pub cpu_usage: CPUUsage, ...
Rust
0
MetaType(metaobject, name_ba, alignof(void *), sizeof(void *), QMetaType::RelocatableType | QMetaType::PointerToQObject, [](const QtPrivate::QMetaTypeInterface *, void *dst) { *static_cast<void**>(dst) = nullptr; }, [](const QtPrivate::QMetaTypeInterface *...
Rust
0
ter', va'center', fontsize14, color'666666') Add legend legend_elements [ mpatches.Patch(color'4ECDC4', label'Fractal-Quantum Synthesis'), mpatches.Patch(color'45B7D1', label'Consciousness Mathematics'), mpatches.Patch(color'96CEB4', label'Topological-Cryst...
Python
1
Some(var_480) = &input.accept_any_date { object.key("AcceptAnyDate").boolean(*var_480); } if let Some(var_481) = &input.after_connect_script { object.key("AfterConnectScript").string(var_481.as_str()); } if let Some(var_482) = &input.bucket_folder { object.key("BucketFolder").st...
Rust
0
use crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen}; use tui::backend::CrosstermBackend; use crate::error::AppError; pub type Backend = CrosstermBackend<Stdout>; pub type Term = tui::Terminal<Backend>; pub struct Terminal { terminal: Term, } impl Terminal { pub fn new() -> Result<Self, App...
Rust
0
from datetime import date from sqlalchemy import and_, func, or_, select from app.bookings.models import Bookings from app.dao.base import BaseDAO from app.database import async_session_maker from app.hotels.rooms.models import Rooms class RoomDAO(BaseDAO): model = Rooms @classmethod async def find_all...
Python
1
#!/usr/bin/env python3 """Convert vocabulary JSON to compressed metadata for ONNX models.""" import argparse import json import base64 import gzip import hashlib from pathlib import Path def main(): parser = argparse.ArgumentParser(description="Convert vocabulary to ONNX metadata format") parser.add_argument("...
Python
1
#!/usr/bin/env python3 """Test script to verify repository handling.""" import os import sys import argparse from pathlib import Path # Add src to Python path script_dir = os.path.dirname(os.path.abspath(__file__)) src_path = os.path.join(script_dir, "src") if src_path not in sys.path: sys.path.insert(0, src_path...
Python
1
nfig.AWSCredentialValidator.validate_credentials') def test_resource_health_check(self, mock_validate_creds, mock_get_account): """Test resource health checking""" mock_validate_creds.return_value = True mock_get_account.return_value = "123456789012" deployer = CompleteProdu...
Python
1
'macd_slow': strat_params.macd_slow, 'divergence_window': strat_params.divergence_window }) # Generate buy signal with NaN handling df['rsi_div_macd_buy_signal'] = ( (df['bullish_div'].fillna(False).infer_objects(copy=False)) & (df['MACD'] > df['MACD_signal']) & (df...
Python
1
corners(&path, &corners, outset_ratio, segment_length); path = result.0; corners = result.1; if result.2 { // Can terminate early break; } } path } } impl PathF64 { pub fn smooth( &self, corner_threshold: f64, outset_ratio:...
Rust
0
} } pub async fn execute_by_where_call<'c,RB,E>( &self, where_sql: &str, where_bind: RB, executor:E, ) -> Result<<DB as Database>::QueryResult, Error> where for<'q> RB: FnOnce( Query<'q,DB,<DB as HasArguments<'q>>::Arguments> , &'q ...
Rust
0
-> (usize, usize) { match history_item.operation { Operation::Add | Operation::Modify => (history_item.start_index, history_item.end_index), Operation::Remove => { let index = min(history_item.start_index, history_item.end_index); if index == 0 || list_length == 0 { (0, 0) } else if index >...
Rust
0
de>(); unsafe { &mut *dip.add((inum as usize) % IPB) } } /// Allocate an inode on device dev. pub(crate) fn ialloc(dev: u32, typ: InodeType, major: u16, minor: u16) -> Arc<RwLock<Inode>> { let sb = superblock::get(); for inum in 1..(sb.ninodes) { let mut bcache = buf::buf_cache(); let mut ...
Rust
0
# If this is one of our list of string fields, then we can just assign # the value, since email *only* has strings, and our get_all() call # above ensures that this is a list. elif raw_name in _LIST_STRING_FIELDS: raw[raw_name] = value # Special Case: Keywords # The...
Python
1
LCellOwner::scope(|mut owner2| { //! let c1 = Rc::new(owner1.cell(100u32)); //! let c1mutref2 = owner2.rw(&c1); // Compile error //! println!("{}", *c1mutref2); //! }); //! }); //! ``` //! //! You can't have two separate mutable borrows active on the same //! owner at the same time: //! ...
Rust
0
t(g) => write!(f, "¬ {}", g), Form::Bct(b,g,h) => write!(f, "({} {} {})", g, b, h), Form::Qtf(true,g) => write!(f, "∃ {}", g), Form::Qtf(false,g) => write!(f, "∀ {}", g), Form::Rel(r,ts) => write!(f, "{}{}", r, Terms(ts)) } } } pub enum FormPart { Cst(bool), Not, Qtf(bool), Bct(B...
Rust
0
#!/usr/bin/env python3 from rest_framework import status as http_status from unittest import mock import pytest from addons.base.tests.views import ( OAuthAddonAuthViewsTestCaseMixin, OAuthAddonConfigViewsTestCaseMixin ) from addons.figshare.tests.utils import FigshareAddonTestCase from tests.base import OsfTestC...
Python
1
rt "portfolio_value" in data["data"] assert "volatility" in data["data"] @patch("src.api.middleware.auth.verify_token") @patch( "src.core.risk_management_service.RiskManagementService.calculate_risk_metrics" ) def test_get_position_risk_metrics_success( self, mock_calculate_metr...
Python
1
h: impl AsRef<Path>) -> Result<()> { let path = path.as_ref(); return fs::remove_dir(path) .map_err(|_| format!("failed to remove directory {}", path.display())); } /// rename file pub fn rename(path: impl AsRef<Path>, new: impl AsRef<Path>) -> Result<()> { let path = path.as_ref(); return fs::rename(path, ...
Rust
0
f field names as unicode strings @return list of field values as unicode strings. """ return [x[2] for x in self.list_fields_and_values(field_names)] def get(self, field_name): """Extract the contents of this field from the file. @param field_name unicode string: name of a...
Python
1
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-30 20:35 from __future__ import unicode_literals from django.db import migrations, models def forwards_split_unified_job_template_any(apps, schema_editor): UnifiedJobTemplate = apps.get_model('main', 'unifiedjobtemplate') for ujt in UnifiedJobT...
Python
1
s sufficient for 1 execution minimum let call_balance_used = self.task_balance_uses(&item); assert!(call_balance_used <= item.total_deposit, "Not enough task balance to execute job, need at least {}", call_balance_used); let hash = self.hash(&item); log!("Task Hash (as bytes) {:?}", &ha...
Rust
0
r_t) -> c_int; fn rust_uv_malloc_buf_base_of(sug_size: size_t) -> *u8; fn rust_uv_free_base_of_buf(buf: uv_buf_t); fn rust_uv_get_stream_handle_from_connect_req(connect_req: *uv_connect_t) -> *uv_stream_t; fn rust_uv_get_stream_handle_from_write_req(write_req: *uv_write_t) -> *uv_stream_t; fn rust_...
Rust
0
size_code: usize) -> Scaled { let f = MATH_FONT(2 + size_code); match &FONT_LAYOUT_ENGINE[f] { Some(Otgr(e)) if e.is_open_type_math_font() => get_native_mathsy_param(f, 13), _ => Scaled(FONT_INFO[(13 + PARAM_BASE[f]) as usize].b32.s1), } } unsafe fn sup2(size_code: usize) -> Scaled { let...
Rust
0
, h], &[!a, !c, !e, !g], &[!b, !c, !e, !g], &[!a, !d, !e, !g], &[!b, !d, !e, !g], &[!a, !c, !f, !g], &[!b, !c, !f, !g], &[!a, !d, !f, !g], &[!b, !d, !f, !g], &[!a, !c, !e, !h],...
Rust
0
s.pop() } else { //swap the removed element wit the last. let removed = self.elements[removed_pos].clone(); let last_entry = self.elements.pop().unwrap(); self.key2idx.insert(last_entry.0.clone(), removed_pos); self.elements[r...
Rust
0
import random lChars = "abcdefghijklmnopqrstuvwxyz" uChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" digits = "1234567890" specialChars = "!@#$%^&*-_+=" passLen = 10 # actual generated password length will be this length + 1 myPass = "" for i in range(passLen): while (len(myPass)) <= 2: index = random.randrange(le...
Python
1
index + 1) % self.num_frames() } pub unsafe fn destroy(&mut self, device: &ash::Device) { for frame in &mut self.frame_queue { frame.destroy(device); } } } impl QueuedFrame { fn new() -> Self { Self { buffers: Vec::new(), memory: Vec::new(), ...
Rust
0
); println!("sample nr: {}", i); let createproof_now = Instant::now(); let (rangeproof_vec, commit_vec_vec): (Vec<RangeProof>, Vec<RistrettoPoint>) = create_rangeproof(&value_vec, &blinding_vec, black_box(*r), N_PARTITION).unwrap(); let create_elapsed = c...
Rust
0
n(right), _ => Err(EvalError::new(format!( "unknown prefix operator: {}", expr.operator ))), } } fn eval_minus_prefix_expression(right: Rc<Object>) -> Result<Rc<Object>, EvalError> { match *right { Object::Integer(val) => Ok(Rc::new(Object::Integer(-val))), ...
Rust
0
#!/usr/bin/env python # encoding: utf-8 """ @author: ZhouLixuan @file: 010_maximum-subarray-of-geometric-mean.py @time: 2023/8/14 @project: huawei-od-python @desc: 010 几何平均值最大子数组 """ import math def calc_geo_mean(numbers): value = 1.0 for num in numbers: value *= num return math.pow(value, 1.0 / l...
Python
1
e into its components. Args: toolgroup_name: The toolgroup name to parse (e.g. "builtin::rag/knowledge_search") Returns: A tuple of (tool_type, tool_group, tool_name) """ split_names = toolgroup_name_with_maybe_tool_name.split("/") if len(split_names) ==...
Python
1
# 输入银行名称,返回银行代码 # --- # 2018.12.18 create by David Yi, add in v1.1.4, github issue #159 # 2019.1.5 edit, v1.1.6 github issue #188, 修改函数名称 @classmethod @lru_cache() def get_bank_info(cls, bankname): """ 银行名称,返回银行代码; :param: * bankname: (string) 要查询的银行 名称...
Python
1
None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[218, 143, 193, 79], OperandSize::Word) } #[test] fn fimul_2() { run_test(&Instruction { mnemonic: Mnemonic::FIMUL, operand1: Some(IndirectScaledIndexed(EBX, EBX, Four, Some(OperandSize::Dword), N...
Rust
0