text
string
label_name
string
labels
int64
_balance = USER_LOCKED_BALANCES .load(deps.as_mut().storage, &user) .unwrap(); assert_eq!( new_user_locked_balance, UserLockedBalance { deposited_amount: Uint128::from(deposit_amount * 2), end_lock_time: user_locked_balance.end_lock_time, start_lo...
Rust
0
fn peb_native(&self) -> Option<Address> { self.peb_native } pub fn peb_wow64(&self) -> Option<Address> { self.peb_wow64 } /// Return the module list information of process native architecture /// /// If the process is a wow64 process, module_info_wow64 is returned, otherwise, ...
Rust
0
# ------------------------------------------------------------------ # Copyright (c) 2020 PyInstaller Development Team. # # This file is distributed under the terms of the GNU General Public # License (version 2.0 or later). # # The full license is available in LICENSE, distributed with # this software. # # SPDX-Licens...
Python
1
FromMetadata, request_filter::Service< PermitNamesInSuffixes, resolve::Service<recover::Resolve<BackoffUnlessInvalidArgument, R>>, >, > where R: Resolve<DstAddr, Endpoint = Metadata> + Clone, S: IntoIterator<Item = Suffix>, { map_endpoint::Resolve::new( endpoint::FromMetadata...
Rust
0
return related[:max_queries] def create_query_plan(user_query: str) -> Dict: """Create comprehensive query plan from user input""" constraints = parse_constraints(user_query) intent = decompose_intent(user_query) plan = { "original_query": user_query, "constraints": { ...
Python
1
host), )?; let target_dir = if let Some(path) = env::var("CARGO_LLVM_COV_TARGET_DIR")? { path.into() } else if show_env { metadata.target_directory.clone() } else { // If we change RUSTFLAGS, all dependencies will be recompiled. Therefore, ...
Rust
0
xt = "").pack() Button(pantalla2, text = "Inicio de Sesion Tradicional", width = 20, height = 1, command = verificacion_login).pack() #------------ Vamos a crear el boton para hacer el login facial -------------------- Label(pantalla2, text = "").pack() Button(pantalla2, text = "Inicio de Sesion Facial...
Python
1
; // #[repr(C)] // #[derive(Debug, Copy, Clone)] // pub struct clingo_model { // _unused: [u8; 0], // } // #[doc = "! Object representing a model."] // pub type clingo_model_t = clingo_model; // #[repr(C)] // #[derive(Debug, Copy, Clone)] // pub struct clingo_ast { // _unused: [u8; 0], // } // #[doc = "! This s...
Rust
0
f.add_startup_system(sys).add_system(system) } } pub(crate) struct TerminalState { pub(crate) buf: String, pub(crate) scrollback: Vec<String>, pub(crate) history: VecDeque<String>, pub(crate) history_index: usize, } impl Default for TerminalState { fn default() -> Self { TerminalState ...
Rust
0
crate_name="brainfuck_macros"] #![crate_type="dylib"] #![feature(quote, plugin_registrar, rustc_private, core)] extern crate syntax; extern crate rustc; use syntax::ast; use syntax::ptr::P; use syntax::codemap; use syntax::ext::base::{ExtCtxt, MacResult, MacExpr}; use syntax::ext::build::AstBuilder; use syntax::pars...
Rust
0
# Write your solution after the class ExamSubmission # Do not make changes to the class! class ExamSubmission: def __init__(self, examinee: str, points: int): self.examinee = examinee self.points = points def __str__(self): return f'ExamSubmission (examinee: {self.examinee}, points: {se...
Python
1
ational { pub fn updates<A: Clone + Send + 'static>(ca: &Cell<A>) -> Stream<A> { Stream { impl_: ca.impl_.updates(), } } pub fn value<A: Clone + Send + 'static>(ca: &Cell<A>) -> Stream<A> { Stream { impl_: ca.impl_.value(), } } pub fn defer<A...
Rust
0
&mut Unstructured, module: &ConfiguredModule<C>, builder: &mut CodeBuilder<C>, ) -> Result<Instruction> { builder.pop_operands(&[ValType::I32]); builder.allocs.operands.push(Some(ValType::I32)); Ok(Instruction::I32Load8_S(mem_arg(u, module, &[0])?)) } fn i32_load_8_u<C: Config>( u: &mut Unstru...
Rust
0
n_seedgen is not rng2.gen_seedgen def test_random_state_transfer(self): """ Test that random state can be transferred from one theano graph to another. """ class Graph: def __init__(self, seed=123): self.rng = RandomStreams(seed) self.y = ...
Python
1
::td(&[], &[ html::a(&[attrs::href(&site_url)], &[html::text(&domain.to_string())]), ]), html::td(&[], &[ html::a(&[attrs::href(&manage_route.to_string())], &[html::text("Manage")]), ]), ]) } use wasm_bindgen::prelude::*; // This is our state -- just a `value` of typ...
Rust
0
`SSKJr SSKrSSKJr SSKJr SSKJr SSK J r J r SSK J r SSKrSS KJr /S Qr/S QrS rS r"SS5r"SS\5r"SS\5r"SS\5r"SS5rSSjrSSjr\R8S5...
Python
1
# Copyright 2015 The TensorFlow 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 applica...
Python
1
veTime::from_num_seconds_from_midnight(value as u32, 0), )) } } deserializer.deserialize_u32(TimeVisitor) } } impl Deref for DBDayTime { type Target = chrono::NaiveTime; fn deref(&self) -> &Self::Target { &self.0 } } impl From<chrono::NaiveTime> fo...
Rust
0
{ error!(e); } } if let Some(matches) = matches.subcommand_matches(EDIT_COMMAND) { edit_goal(matches.value_of("editor").map(|s| s.to_string())).unwrap_or_else(|e| error!(e)); } match matches.subcommand_name() { Some(REMOVE_COMMAND) => { remove_goal().un...
Rust
0
import torch words = open('names.txt', 'r').read().splitlines() chars = sorted(list(set(''.join(words)))) stoi = {s: i + 1 for i, s in enumerate(chars)} stoi['.'] = 0 itos = {i: s for s, i in stoi.items()} xs, ys = [], [] for w in words: for ch1, ch2 in zip(w, w[1:]): ix1 = stoi[ch1] ix2 = stoi[ch2...
Python
1
.eval("y")); assert_eq!(72, circuit.eval("d")); assert_eq!(507, circuit.eval("e")); assert_eq!(492, circuit.eval("f")); assert_eq!(114, circuit.eval("g")); assert_eq!(65412, circuit.eval("h")); assert_eq!(65079, circuit.eval("i")); } use crate::elasticsearch::Elasticsearch; use crate::zdbquery:...
Rust
0
<O2, T2>(&self, x: &BitSlice<O2, T2>) -> bool where O2: BitOrder, T2: BitStore, { let len = x.len(); if len > self.len() { return false; }; self.windows(len).any(|s| s == x) } /// Returns `true` if `needle` is a prefix of the slice. /// /// # Original /// /// [`slice::starts_with`](https://doc.r...
Rust
0
agent.epsilon = 0.01 # load trained weights agent.load(f'{models_folder}/dqn.ckpt') # play the game num_episodes times for e in range(num_episodes): t0 = datetime.now() val = play_one_episode(agent, env, args.mode) dt = datetime.now() - t0 print(f"episode: {e + 1}/{num_episodes}, episode e...
Python
1
import duckdb import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit con = duckdb.connect() # Convergence for inductive (success rate per N) df_inductive = con.sql("SELECT scramble_n, AVG(solved::INT) AS success_rate, AVG(best_score) AS avg_score, COUNT(*) AS runs FROM 'data/runs.parqu...
Python
1
boundaries .iter_mut() .all(|shell| shell.remove_vertex_by_concat_edges(vertex_id)); #[cfg(debug_assertions)] Solid::new(self.boundaries.clone()); res } /// Creates display struct for debugging the solid. #[inline(always)] pub fn display(&self, format: So...
Rust
0
from discord import app_commands async def week_type_auto(interaction, current): week_types = [{'key': 'pre-season', 'value': 'pre'}, {'key': 'regular season', 'value': 'reg'}, {'key': 'playoffs', 'value': 'reg2'}] return [ app_commands.Choice(name=week_type['key'], value=week_type['value']) ...
Python
1
() .enumerate() .map(|(idx, rng)| { Self::train_subquantizer( idx, n_subquantizers, 2usize.pow(n_subquantizer_bits), n_iterations, n_attempts, instances.view(),...
Rust
0
2\x89\x22.\x81\x12\xd4\xcd\ \xcb\xe9\xf1L\xf4\xd8A(8\x06(\xe8\xd5H\xfb[\ \xf6z2\x9fv\xdd\x8ac\xaa\x04\xbd[%\xb4\xd4\x09\ \x1a5\xd6\x82\x1f\x18X#j\x1d\xbc\xd4\xf8\x8e,\x86\ \x00\xce\xfb#\xf5\xd6(\xbbz|J\xa3\xd3\xa0\x19\x98\ \x1d\x14\x06\x88\xf0\xfe\x93\xce\xba\xe3\xb9\x91\xd8\x16\xd9x\ \xf3\x96\xcd\xe5\xef\x95\xae}u\x9f...
Python
1
# Copyright 2025 © BeeAI a Series of LF Projects, LLC # SPDX-License-Identifier: Apache-2.0 import pytest from kink import di from kink.errors import ServiceError from beeai_server.configuration import Configuration from beeai_server.utils.docker import DockerImageID pytestmark = pytest.mark.integration @pytest.fi...
Python
1
ident, $len_len: literal) => { impl_tls_vec_generic!( $size, $name, $len_len, Serialize, Deserialize, Size, Zeroize ); impl_tls_vec_codec_generic!( $size, $name, $len_len, ...
Rust
0
""" SCAMP Example: Multi-Part Music Plays two coordinated but independent parallel parts, one for oboe and one for bassoon. """ # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # This file is part of SCAMP (Suite for Computer-Assisted Music in Python) ...
Python
1
# GPLv3 License # # Copyright (C) 2021 Ubisoft # # 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 program is dis...
Python
1
# Add the parent directory to import sys import os import sys import unittest import numpy as np from scipy.ndimage import gaussian_filter1d sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))...
Python
1
if ~ignore & VARKWARG: if (item_kwarg is None) ^ (stubitem_kwarg is None): if item_kwarg: print( f"{path} {item.name} varkwarg differ: " f"{item_kwarg.arg} vs {stubitem_kwarg}" ) else: print( ...
Python
1
/// Transpose vectors #[inline] #[target_feature(enable = "neon")] #[cfg_attr(test, assert_instr(trn1))] #[stable(feature = "neon_intrinsics", since = "1.59.0")] pub unsafe fn vtrn1_u8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t { simd_shuffle8!(a, b, [0, 8, 2, 10, 4, 12, 6, 14]) } /// Transpose vectors #[inline] #[...
Rust
0
) } else { lines_to_skip = lines_after_iMCU_row .wrapping_div(lines_per_iMCU_row) .wrapping_mul(lines_per_iMCU_row) } /* Calculate the number of lines that remain to be skipped after skipping all * of the full iMCU rows that we can. We will not read these lines unless w...
Rust
0
) } else { Self::make_qualified_name_part(x.to_string(), true) } }) .collect(); if has_leading { let backslash = SyntaxType::make_list_item( &(), Self::make_missing(), Self::ma...
Rust
0
ith open(filePath, readmode) as f: text = f.read() if(CommonDefs.pyVer == 2): text = unicode(text, 'utf-8') except Exception as e: errormsg("Error reading the file specified in Text File input box."+ str(e)) return if(text[0]...
Python
1
type RpcClient = client::IndexService<Buffer<Connection<Body>, http::Request<Body>>>; pub type Buf = Buffer<AddOrigin<Connection<TcpStream, DefaultExecutor, BoxBody>>, http::Request<BoxBody>>; pub type RpcClient = client::IndexService<Buf>; /// RPC Services should "ideally" work on only local indexes, they shouldn't...
Rust
0
et key = "doctest_client_hash_hexists_1"; /// #[derive(serde::Serialize)] /// struct Fields { /// field1: String, /// } /// let res = client.hset(key, &Fields { field1: "foo".into() }).await?; /// assert_eq!(1, res); /// let res = client.hexists(key, "field1").await?; /// assert!(res...
Rust
0
def sum_and_adverage(numbers): total_sum=sum(numbers) avg = total_sum/len(numbers) return total_sum,avg numbers=[1,2,3,4,5,6,7,8,9,10] total_sum,avg=sum_and_adverage(numbers) print("The Total sum is :", total_sum) print("The averge is :,", avg)
Python
1
# ======================================================== # =============== 发布/订阅连接器,在qml调用 =============== # ======================================================== from PySide2.QtCore import QObject, Slot from .pubsub_service import PubSubService class PubSubConnector(QObject): def __init__(self, *args): ...
Python
1
&str { match self { QueryType::A => "a", QueryType::AAAA => "aaaa", QueryType::AFSDB => "afsdb", QueryType::Other(s) => s, } } } impl PartialEq for QueryType { fn eq(&self, rhs: &Self) -> bool { self.name() == rhs.name() } } /// The d...
Rust
0
m::geodesic_distance::GeodesicDistance; pub use crate::algorithm::geodesic_length::GeodesicLength; pub use crate::algorithm::haversine_destination::HaversineDestination; pub use crate::algorithm::haversine_distance::HaversineDistance; pub use crate::algorithm::haversine_intermediate::HaversineIntermedia...
Rust
0
up a1p3 | plookup a2p3 | plookup a1p5 /// \ / 5 | copy a0p4 | copy a1p4 | crumb a2c0 | crumb a2c10 /// ' 6 | copy a0p5 | copy a1p5 | crumb a2c1 | crumb a2c11 /// 7 | crumb a0c0 | crumb a1c0 | crumb a2c2 | crumb a2c12 /// 8 | crumb a0c1 | crumb a1c1 | crumb a2c3 | crumb a2c13 /// ...
Rust
0
::create() .table(Alias::new("cakes_bakers")) .col(ColumnDef::new(Alias::new("cake_id")).integer().not_null()) .col(ColumnDef::new(Alias::new("baker_id")).integer().not_null()) .primary_key( Index::create() .col(Alias::new("cake_id")) .col(Alia...
Rust
0
class Parent: def method(self): pass def wrong(self): pass class Child(Parent): def method(self): parent = super() # ok super().method() # ok Parent.method(self) # ok Parent.super(1, 2) # ok def wrong(self): parent = super(Child, self) # w...
Python
1
class TaskFamily: @staticmethod def get_tasks() -> dict[str, dict]: return { "1": { "product_name": "EcoClean", "product_description": "A new line of environmentally friendly cleaning products that use natural ingredients to effectively clean various surfaces ...
Python
1
} } } } mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response api = VidiqAPI("test_token") results = api.analyze_multiple_keywords(["keyword1", "keyword2"]) assert "keyword1" in results ...
Python
1
utor, epoch_mgr, event_processor, timeout_receiver, network_task, all_events, network_data_request_sender, network_data_receiver, ); debug!("Chained BFT SMR started."); Ok(()) } /// Stop is synchronous:...
Rust
0
M, N> where ItemKey: Codec + EncodeLike, Item: Codec + EncodeLike, C: StorageValue<Bracket, Query = Bracket>, B: StorageMap<Bracket, (BufferIndex, BufferIndex), Query = (BufferIndex, BufferIndex)>, M: StorageDoubleMap<Bracket, BufferIndex, ItemKey, Query = ItemKey>, N: StorageDoubleMap<Bracket, ItemKey, Item, Qu...
Rust
0
ref())) } pub fn apply(&self, proc: &Process) -> Result<()> { self.apply_nice(proc)?; self.apply_io(proc) } pub fn apply_nice(&self, proc: &Process) -> Result<()> { if let Some(nice) = self .nice .or_else(|| self.proc_type.as_ref().and_then(|t| t.nice)) ...
Rust
0
skip_serializing_if = "Option::is_none")] pub passkey: Option<String>, } impl DataBoxDiskJobDetails { pub fn new(job_details: JobDetails) -> Self { Self { job_details, preferred_disks: None, copy_progress: Vec::new(), granular_copy_progress: Vec::new(), ...
Rust
0
eamCommoditySettlDayType #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "41987")] pub underlying_stream_commodity_settl_day_type: Option<UnderlyingStreamCommoditySettlDayType>, /// UnderlyingStreamCommoditySettlPeriodGrp #[serde(flatten)] pub underlying_stream_commodity_settl_period_grp: Optio...
Rust
0
.push(sd); receivers.push(Rc::new(RefCell::new(rv))); } (senders, receivers) }; // Channel to send peers "Socket Address" received from Tracker's Announce Response to them let (sender_peers, receiver_peers) = { let (sd, rv) = mpsc::channel::<V...
Rust
0
ushort; pub type uint32_t = ::std::os::raw::c_uint; pub type uint64_t = ::std::os::raw::c_ulonglong; pub type int_least8_t = int8_t; pub type int_least16_t = int16_t; pub type int_least32_t = int32_t; pub type int_least64_t = int64_t; pub type uint_least8_t = uint8_t; pub type uint_least16_t = uint16_t; pub type uint_l...
Rust
0
.is_some(), uvs.is_some() ); } }; let texture_index = primitive .material() .pbr_metallic_roughness() .base_color_texture() .map(|x| x.texture().index()); let ...
Rust
0
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import time import os import numpy as np import faiss os.system("grep -m1 'model name' < /proc/cpuinfo") def format_...
Python
1
n('--loglevel', '-l', default='warning', help='Logging level') @click.option('--ids', flag_value=True, help='Include numeric ids in output') @click.argument('symbol', required=True) @click.pass_context def contracts(ctx, loglevel, broker, symbol, ids): ''' Get list of all option contracts for symbol ''' ...
Python
1
}, true, ) { Ok(resp) => resp .ip_domain_string .parse() .map_err(|_e| nb::Error::Other(Error::Illegal)), Err(e) => { error!("get_host_by_name failed: {:?}", e); Err(nb::Error::Other(Err...
Rust
0
) else: interpolated_feats = known_feats.expand( *(known_feats.size()[0:2] + [unknown.size(1)]) ) if unknow_feats is not None: new_features = torch.cat( [interpolated_feats, unknow_feats], dim=1 ) # (B, C2 + C1, n) ...
Python
1
len! { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 64, 128, 256, 512, 1024, 2048, 4096, } use std::error::Error; use std::process::exit; use structopt::StructOpt; use capn::config::Config; use capn::fs::LiveFs; use capn::git::{Git, LiveGi...
Rust
0
275.0 / 81.0, 1036.0 / 243.0, 3773.0 / 729.0, 13378.0 / 2187.0, 46439.0 / 6561.0, 158_488.0 / 19_683.0, ]; assert!( ewma(input.iter(), alpha) - expected[expected.len() - 1] < EPSILON ); } #[test] fn test...
Rust
0
lp(fromchat) else: commandlist.commandhelp(fromchat) if __name__ == '__main__': # 更新判断 global my_name, system, update_sign update_sign = False my_path = sys.argv[0] system = platform.system() if os.path.isfile("upgrade.bat"): os.remove("upgrade.bat") update_sign = T...
Python
1
import numpy as np import matplotlib.pyplot as plt def cepstral_analysis(signal, frame_size, overlap, sampling_rate): step = frame_size - overlap num_frames = (len(signal) - overlap) // step frames = np.array([signal[i*step:i*step+frame_size] for i in range(num_frames)]) cepstral_coeffs = [] ...
Python
1
format!("{}", error)) } fn set_invalid_input(name: &str, id: i32) { addClass(&get_element(id, name), "s_invalid_input"); } fn unset_invalid_input(name: &str, id: i32) { removeClass(&get_element(id, name), "s_invalid_input"); } fn set_error(id: i32, message: &str) { set_value(&get_element(id, "i_error"),...
Rust
0
pe", )); } } // BSD platform doesn't have any special logic TcpListener::bind(addr).await } } impl TcpStreamRedirExt for TcpStream { fn destination_addr(&self, ty: RedirType) -> io::Result<SocketAddr> { match ty { #[cfg(any( ...
Rust
0
{'metadata': {f'abc-{numstr}': f'xyz-{apikey}-{numstr}'}}, expected_code=200, ) # Refresh modeldata.refresh_from_db() self.assertEqual( modeldata.get_metadata(f'abc-{numstr}'), f'xyz-{apikey}-{numstr}' ) def test_metadata(self): """Test al...
Python
1
From<u4> for RegAR { fn from(val: u4) -> Self { match val.as_u8() { 0..=7 => RegAR::A(RegA::from(u3::with(val.as_u8()))), _ => RegAR::R(RegR::from(u3::with(val.as_u8() - 8))), } } } impl From<RegA2> for RegAR { #[inline] fn from(reg: RegA2) -> Self { Self::A(reg....
Rust
0
let mut writer = io::BufWriter::new(stdout); io::copy_buf(&mut reader, &mut writer).await?; Ok(()) } <reponame>unipro/hls_m3u8 use std::fmt; use std::str::FromStr; use crate::attribute::AttributePairs; use crate::tags::ExtXKey; use crate::types::{ByteRange, ProtocolVersion}; use crate::utils::{quote, tag...
Rust
0
&Program, queue: Queue, ) -> Result<Array2<f32>> where A: Dimension, W: Dimension, { let ((m, _), (_, n)) = (a_shape, w_shape); let res = matmul_ocl_vec(a, w, a_shape, w_shape, prg, queue)?; // the shape of the matmul Ok(Array2::from_shape_vec((m, n), res)?) } /// multiply A*W into a vec /...
Rust
0
arameters ---------- label : str A short label explaining to the user what this button is for. Defaults to "Submit". help : str or None A tooltip that gets displayed when the button is hovered over. Defaults to None. on_click : callable ...
Python
1
def escape_json_string(json_string: str) -> str: json_string = ( json_string.replace("\n", "") .replace("\r", "") .replace("\t", "") .replace(" ", "") .replace(": [", ":[") .replace('", "', '","') .replace('], "', '],"') ) input_json = json_string ...
Python
1
assign_minus_prev_ref() { expect(":a = 3; a -= a; a").to_yield(0) } #[test] fn assign_times_prev_ref() { expect(":a = 3; a *= a; a").to_yield(9) } #[test] fn assign_divide_prev_ref() { expect(":a = 3; a /= a; a").to_yield(1) } #[test] fn assign_and_prev_ref_true() { expect(":a = true; a &&= a; a").t...
Rust
0
a module function call; either nothing (functions are only called for "side effects") /// or an error message. pub type Result = result::Result<(), &'static str>; /// A lazy call (module function and argument values) that can be executed via its dispatch() /// method. pub trait Dispatchable { /// Every function call...
Rust
0
import numpy as np from torch import nn from models.gs.embedder import * class LinModule(nn.Module): def __init__(self, d_in, d_out, dims, multires=0, act_fun=None, last_act_fun=None, weight_norm=False, weight_zero=False, weight...
Python
1
alWorldSize(width=xyz2[0][0] - xyz1[0][0], height=xyz2[1][0] - xyz1[1][0]) def main(): # Initialize the ROS node rospy.init_node('panda_vision') try: # Create the PandaVision object panda_vision = PandaVision() # Create a subscriber to the camera topic rospy.Subscriber('/p...
Python
1
idth(5) .fill_color(Gray8::new(10)) .stroke_color(Gray8::new(60)) .build(), ); b.iter(|| object.into_pixels().collect::<Vec<Pixel<Gray8>>>()) }); } criterion_group!( primitives, filled_circle, filled_rect, empty_rect, line, th...
Rust
0
ed(futures): file_pbar.update(1) future.result() # 获取结果(如果有异常会在这里抛出) file_pbar.close() self.add_language_root_title(lang_k) lang_pbar.close() print( f"\n翻译完成! Succ: {total_tasks-self.fail_count}, Fail: {self.fail_count}")...
Python
1
import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set_theme() ''' 2.1 Minimizing a quadratic function and the curse of dimensionality ''' N = 100 def minimize(n: int, p: int): points = np.random.rand(p, n) * 2 - 1 return np.apply_along_axis(lambda w: np.dot(w, w), axis=1, arr=points)...
Python
1
soupt = BeautifulSoup(t.text, "html.parser") title = soupt.select('meta[property^="og:description"]') gd_txt += f"{no}. <code>{(title[0]['content']).replace('Download ' , '')}</code>\n{gdlk}\n\n" asleep(1.5) return gd_txt elif "taemovies" in link: gd_txt, no ...
Python
1
import serial port = '/dev/ttyUSB0' baud_rate = 9600 timeout = 1 ser = serial.Serial(port, baud_rate, timeout=timeout) ser.write(input().encode("ascii"))
Python
1
out, &mut main_depth); } _ => (), } } }); // draw a frame encoder.clear(&data.out, CLEAR_COLOR); encoder.draw(&slice, &pso, &data); encoder.flush(&mut device); window.swap_buffers().unwrap(); dev...
Rust
0
bias=False, ), "input_fn": lambda: torch.rand(size=(3, 2, 5, 13, 17)), }, { "module_fn": lambda: torch.nn.Conv3d( in_channels=2, out_channels=4, kernel_size=2, padding=1, stride=2, groups=2, bias=F...
Python
1
ative, helpful, detailed and polite answers. " "这是一个好奇的人类和一个人工智能助手之间的对话。假设你扮演这个AI助手的角色。" "仔细阅读所有的图像,并对人类的问题做出信息丰富、有帮助、详细的和礼貌的回答。\n\n" ), stop_words=["###"], efficient_eos=True, mm_plugin=get_mm_plugin(name="llava", image_token="<image>"), ) register_template( name="yuan", forma...
Python
1
X: set ℤ, f {1, 2, 3} → f X → X = {1, 2, 3}"); } #[test] fn pretty_names() { parse_pretty("∀ salam x2: ℤ, salam < x2"); parse_not_pretty( "∀ x: Universe, x → ∀ x: ℤ, x < x", "∀ x: Universe, x → ∀ x0: ℤ, x0 < x0", ); } #[test] fn abstr_infer() { parse_not_pretty("∃ x, 2 < x", "∃ x: ℤ, 2...
Rust
0
if G.is_directed(): lap_matrix = nx.directed_laplacian_matrix(G, nodes, weight, walk_type, alpha) else: lap_matrix = nx.laplacian_matrix(G, nodes, weight).toarray() full_energy = np.sum(lap_matrix**2) # calculate laplacian centrality laplace_centralities_dict = {} for i, node in e...
Python
1
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::new(100u128), msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(), }); let mut env = mock_env(); let info = mock_info(Addr::unchecked("lp_token").as_str(), &[]); let _res = execute(d...
Rust
0
gen::sub(&mut bytes, n), ASTNode::Loop(nodes) if nodes.len() < INLINE_THRESHOLD => { bytes.extend(Self::compile_loop(nodes, promises.clone())) } ASTNode::Loop(nodes) => bytes.extend(Self::defer_loop(nodes, promises.clone())), }; } ...
Rust
0
lf.cosine_similarity( dynamic_prompt[i].unsqueeze(0), action_embedding.unsqueeze(0) ) similarities.append(similarity) similarities_tensor = torch.stack(similarities) loss = -similarities_tensor.mean() return loss class C...
Python
1
path, 0o755) # Generate change log if available change_log_content = None try: from config_diff import create_change_log logging.info("Generating configuration change log...") config = {"system_info": MOCK_SYSTEM_INFO, "containers": MOCK_CONTAINERS} ...
Python
1
ecutor.spawn(Task::new(keyboard::print_keypresses())); executor.run(); } fn main() { vga_println!("Hello, {}!", "World"); } async fn async_number() -> u32 { 42 } async fn example_task() { let number = async_number().await; vga_println!("async number: {}", number); } #[cfg(test)] mod tests { ...
Rust
0
pub const PRIXFAST16: &'static [u8; 3usize] = b"hX\0"; pub const PRIdFAST32: &'static [u8; 2usize] = b"d\0"; pub const PRIiFAST32: &'static [u8; 2usize] = b"i\0"; pub const PRIoFAST32: &'static [u8; 2usize] = b"o\0"; pub const PRIuFAST32: &'static [u8; 2usize] = b"u\0"; pub const PRIxFAST32: &'static [u8; 2usize] = b"...
Rust
0
_vec()) } use crate::stats::{self, Normal, Regression}; use crate::BenchmarkResult; #[derive(Debug)] pub struct Summary { pub elapsed_time: Normal, } pub fn summarize(result: &BenchmarkResult) -> Summary { let mut sec_per_iters: Vec<f64> = result .measurements .iter() .map(|(i, t)| t /...
Rust
0
] fn mul(mut self, other: BigDigit) -> BigUint { self *= other; self } } impl MulAssign<BigDigit> for BigUint { #[inline] fn mul_assign(&mut self, other: BigDigit) { if other == 0 { self.data.clear(); } else { let carry = scalar_mul(&mut self.data[...
Rust
0
id, result_flags: result_flags, delegation_type: delegation_type, delegate_read: delegate_read, } ) )); named!(nfs4_res_open<Nfs4ResponseContent>, do_parse!( status: be_u32 >> open_data: cond!(status == 0, nfs4_res_open_ok) >> ( Nfs4Respon...
Rust
0
import time from lumibot.brokers import Bitunix from lumibot.credentials import BITUNIX_CONFIG # Assuming Bitunix config is in credentials from lumibot.entities import Asset, Order from lumibot.strategies.strategy import Strategy class BitunixFuturesExample(Strategy): # =====Overloading lifecycle methods=======...
Python
1
# %% [markdown] # ## Embedding Visuals # # Colight supports exporting visuals for embedding in websites: # # ### HTML Export # # You can export any visualization as a standalone HTML file: # %% import colight.plot as Plot # Create a simple visualization data = [ {"category": "A", "value": 10}, {"category": "...
Python
1
.bboxes_event.clear() continue cfg.img_event.wait(timeout=5) cfg.bboxes_event.wait(timeout=5) if (labels_exists(cfg.bboxes, Labels_ID['Confirm']) or text_exists(cfg.img_src, r'确认')) and text_exists( cfg.img_src, r'获得.+饰品.*'): if text_exists(cfg.img_src, r...
Python
1
BindingResolver, ScopeChainBinder, TopLevelDeclarationBinder, VariableBinder}; pub fn analyze<'a>(arena: &'a BumpaloArena, node: &'a Program<'a>) -> Vec<SemanticError<'a>> { // Assign `.r#type()` with new type variables or primitive concrete type. let mut visitor = InitialTypeBinder::new(arena); traverse(a...
Rust
0