text
string
label_name
string
labels
int64
"ray_head_url should be in the format of hostname:port" if not ray_head_url.startswith("ray://"): ray_head_url = f"ray://{ray_head_url}" logger.info(f"Prompt: {prompt_template}") ray.init( address=ray_head_url, runtime_env={ "env_vars": { "VLLM_WORKER_MUL...
Python
1
import sys import re from collections import namedtuple Query = namedtuple('Query', 'ticker source string') def querify(ticker, source, string): return Query(ticker, source, '+'.join(string.split(' '))) def sysprint(text): """moves cursor down one line -- prints over the current line -- then back up one lin...
Python
1
# coding=UTF-8 # ex:ts=4:sw=4:et=on # ------------------------------------------------------------------------- # Copyright (C) 2014 by Mathijs Dumon <mathijs dot dumon at gmail dot com> # # mvc is a framework derived from the original pygtkmvc framework # hosted at: <http://sourceforge.net/projects/pygtkmvc/> # # ...
Python
1
0].to_owned(); let size = parts[1].to_owned(); Size { name, size } }).collect() } <reponame>timboldt/sphero-rs use bitflags::bitflags; use global_counter::primitive::exact::CounterU8; static SEQ_NO_COUNTER : CounterU8 = CounterU8::new(0); //use byteorder::{BigEndian, WriteBytesExt}; const ESC: u...
Rust
0
from qtpy.QtCore import Qt from qtpy.QtWidgets import ( QComboBox, QWidget, ) from napari._qt.layer_controls.widgets.qt_widget_controls_base import ( QtWidgetControlsBase, QtWrappedLabel, ) from napari._qt.utils import qt_signals_blocked from napari.layers import Vectors from napari.layers.vectors._vec...
Python
1
"A/365 (Fixed)", or "A/365F". // According to ISDA, "Actual/365" (without "Fixed") is // an alias for "Actual/Actual (ISDA)"DayCounter (see // ActualActual.) If Actual/365 is not explicitly // specified as fixed in an instrument specification, // you might want to double-check its meaning. // // http://en.wikipedia.or...
Rust
0
) { // Note: the logic is unaffected by the values of the keys, as long as they are // distinct. Greater test exposure can be sought by varying the patterns of // insertion, e.g. performing other operations between the insertion and the // retain command, calling retain several times and so on. Varyin...
Rust
0
pub fn available_bytes(&self) -> usize { self.arena.borrow().available_bytes() } fn alloc_raw<'v, 'v2: 'v2>(&'v self, x: impl AValue<'v2, ExtraElem = ()>) -> Value<'v> { let arena_ref = self.arena.borrow(); let arena = &*arena_ref; let v: &AValueRepr<_> = arena.alloc(x); ...
Rust
0
.try_into() .unwrap(); assert_eq!(ret, 60); } // This should really be in the stream module, // but `pub(crate)` isn't available until Rust 1.18, // and pre-1.18 there isn't a really good way to have a sub-module // available to the crate, but not without it. use core::marker::PhantomData; use {Pol...
Rust
0
try_from(buf.len()).unwrap_or(u16::MAX)) }; if rx_bytes != 0 { let ptr: u16 = self.sn_rx_rd(socket)?; self.sn_rx_buf(socket, ptr, &mut buf[..usize::from(rx_bytes)])?; self.set_sn_rx_rd(socket, ptr.wrapping_add(rx_bytes))?; self.set_sn_cr(socket, SocketComm...
Rust
0
class WriteImageCharacters: @classmethod def INPUT_TYPES(cls): hidden_inputs = {} for i in range(2, 6): # Notice the range starts at 2 and ends at 6 to include 5 hidden_inputs.update({ f"character_{i}": ("BJORNULF_CHARACTER", {"forceInput": True}), # ...
Python
1
print("\t\t\tWelcome to Caeser Cipher") while (True): # print("Enter your choice :") print("1. For Encrypting") print("0. For Exit") a = int(input("Enter the choice : ")) if (a == 1): message = input("Enter the message to encrypt: ") shift = int(input("Enter shift key (INT...
Python
1
trs_from_loc<T, D>(node: T, db: &D) -> Attrs where T: HasSource, T::Value: ast::AttrsOwner, D: DefDatabase, { let src = node.source(db); let hygiene = Hygiene::new(db, src.file_id); Attr::from_attrs_owner(&src.value, &hygiene) } // Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file i...
Rust
0
or(None, |a| Some(a + 1)); /// /// // Good /// opt.and_then(|a| Some(a + 1)); /// ``` pub OPTION_MAP_OR_NONE, style, "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`" } declare_clippy_lint! { /// **What it does:** Checks for usage of `_.map_or(None, S...
Rust
0
/// /// **NOTE** `--help` and `--version` are returned as errors. /// /// **NOTE** Note that first element of iteration is considered name of /// binary. fn parse_any<I : IntoIterator<Item = T>, T : Into<std::ffi::OsString> + Clone, E : From<Self::Error> + From<clap::Error>>(itr: I) -> Result<Se...
Rust
0
merged = dcmmeta.NiftiWrapper.from_sequence(input_nws) assert merged.nii_img.shape == (4, 4, 4, 3) assert(np.allclose(merged.nii_img.affine, np.diag((1.1, 1.1, 1.1, 1.0))) ) assert merged.meta_ext.get_values_and_class('PatientID') == ('Test', ('global', 'const')) assert ...
Python
1
} } impl<'a> DoubleEndedIterator for IntoIter { #[inline] fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back().map(|v| v.0) } } impl<'a> ExactSizeIterator for IntoIter { #[inline] fn len(&self) -> usize { self.iter.len() } } /////////////////////////////////...
Rust
0
rrange_micro_batches(batch=rm_data.batch, max_token_len=max_token_len) else: micro_batches = rm_data.batch.split(self.config.micro_batch_size_per_gpu) output = [] for micro_batch in micro_batches: rm_score = self._forward_micro_batch(micro_batch) ...
Python
1
age path does not exist: {image_path}" img_pil = PIL.Image.open(image_path) img_pil = exif_transpose(img_pil).convert("RGB") return np.array(img_pil) def resize_and_crop_cv2( rgb_img: np.ndarray, size: Literal[224, 512], square_ok: bool = False ) -> np.ndarray: """ Resize and crop an image fro...
Python
1
_input: ParseOrFindMethod, ) -> StringAndMethod { StringAndMethod { string: string_input, parse_method: parse_method_input, } } } pub const PAM_HEADER_EXPECTED_STRS_METHODS: [StringAndMethod; 7] = [ StringAndMethod::from("P7", ParseOrFindMethod::FIND_START), StringAndMethod::from("WIDTH", P...
Rust
0
args: Vec<LispVal>) -> Result<LispVal> { let mut it = args.into_iter(); let e = it.next().expect("expected 1 argument"); match e.as_atom().and_then(|a| self.keywords.get(&a)) { Some(Keyword::Add) => { self.add(elab, fsp, it)?; Ok(LispVal::undef()) } Some(Keyword::Finish) =...
Rust
0
lf::simulations::Simulation; mod velocities; pub use self::velocities::{InitVelocities, BoltzmannVelocities, UniformVelocities}; //! Example that definitely works on Raspberry Pi. //! Make sure you have "SPI" on your Pi enabled and that MOSI-Pin is connected //! with DIN-Pin. You just need DIN pin, no clock. WS2818 us...
Rust
0
#!/usr/bin/env python3 # encoding: utf-8 import os from distutils.core import setup, Extension strCompilerCommonFlagsSuffix = " -fpermissive -fPIC -std=c++11 -Wno-error=parentheses -Wno-error=char-subscripts" os.environ["CC"] = "gcc-7" + strCompilerCommonFlagsSuffix os.environ["CXX"] = "g++-7" + strCompilerCommonFlag...
Python
1
omplete": 1, "num_incomplete": 0, "num_leechs": 0, "num_seeds": 0, "priority": 0, "progress": 1, "ratio": 0, "ratio_limit": -2, "save_path": "/mnt/sdb/qb/downloads", "seeding_time": 615035, ...
Python
1
o ig @sxdZddgZddlZddlZddlZddlZddlmZddlm Z ddlm Z e j Z e j Z d dZ d d Zd d ZdS)a3Fortran to Python Interface Generator. Copyright 1999 -- 2011 Pearu Peterson all rights reserved. Copyright 2011 -- present NumPy Developers. Permission ...
Python
1
O) cdir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(cdir, "mapping.json"), encoding="utf-8") as f: mapping = json.load(f) job = functools.partial(process_mapping, outdir, partial) ncpu = multiprocessing.cpu_count() if os.getenv("CI"): logging.info("Pouze jedn...
Python
1
rid); if val < target { grid.insert(sq, val); } else { second = val; } } } println!("First: {}", sq.0.abs() + sq.1.abs()); println!("Second: {}", second); } use crate::lc::Solution; impl Solution { pub fn number_of_matches(n: ...
Rust
0
grene = 2 self.assertRaises(ValueError, bad_duplicates) def test_init(self): class Planet(Enum): MERCURY = (3.303e+23, 2.4397e6) VENUS = (4.869e+24, 6.0518e6) EARTH = (5.976e+24, 6.37814e6) MARS = (6.421e+23, 3.3972e6) JUPI...
Python
1
est Game", exe=long_path, dir=long_path[:-8] # Remove "game.exe" ) assert game.Exe == long_path assert len(game.Exe) > 260 # Longer than Windows MAX_PATH def test_special_characters_in_paths(self): """Test NonSteamGame with special characters i...
Python
1
) -> LY_ERR::Type; } extern "C" { pub fn lys_nodetype2str(nodetype: u16) -> *const ::std::os::raw::c_char; } extern "C" { pub fn lyxp_get_expr( path: *const lyxp_expr, ) -> *const ::std::os::raw::c_char; } pub mod LYD_FORMAT { pub type Type = ::std::os::raw::c_uint; pub const LYD_UNKNOW...
Rust
0
""" 配置管理服务 - 动态配置管理,支持TOML格式 """ import json import logging from datetime import datetime from pathlib import Path from typing import Dict, Any import toml logger = logging.getLogger(__name__) class ConfigManager: """配置管理器 - 支持动态配置和持久化,优先使用TOML格式""" def __init__(self): # 优先使用TOML格式,回退到JSON ...
Python
1
in_use.keys().cloned().collect(); ids.sort(); for id in ids { let allocation = &self.framebuffers_in_use[&id]; println!( "id {:?}: {:?} {:?}x{:?} {:?} ({:?} B)", id, allocation.tag, allocation.descriptor.width, ...
Rust
0
from __future__ import annotations from typing import Any, TYPE_CHECKING from functools import partial import pytest import numpy as np if TYPE_CHECKING: from collections.abc import Callable AR = np.array(0) AR.setflags(write=False) KACF = frozenset({None, "K", "A", "C", "F"}) ACF = frozenset({None, "A", "C", ...
Python
1
def count(d): return sum([count(v) if isinstance(v, dict) else 1 for v in d.values()])
Python
1
(y2 - y1) + (x2 - x1) * (x2 - x1)) ); } <filename>src/export.rs use crate::voltcraft::data::PowerEvent; use crate::voltcraft::stats::{BlackoutInfo, DailyPowerInfo, OverallPowerInfo}; use std::fs::File; use std::io::{self, Write}; pub fn save_parameter_history_txt( filename: &str, power_events: &[PowerEven...
Rust
0
}; #[derive(Debug)] pub struct MessageBuilder<'a> { function: &'a Function, inputs: Vec<Token>, } impl<'a> MessageBuilder<'a> { pub fn new(contract: &'a Contract, function_name: &str) -> Result<Self> { let function = contract .function(function_name) .map_err(|_| MessageBui...
Rust
0
ending_ledger_infos.push(create_ledger_info(epoch)); } let response_payload = DataClientPayload::EpochEndingLedgerInfos(epoch_ending_ledger_infos); // Return the ledger infos Ok(create_data_client_response(response_payload)) } fn get_global_data_summary(&self) -> Result<DataCli...
Rust
0
from shapely.affinity import translate from shapely.geometry import Polygon import vsketch class StrokeJoinSketch(vsketch.SketchClass): def draw(self, vsk: vsketch.Vsketch) -> None: vsk.size("a4", landscape=False) vsk.scale("cm") p = translate( Polygon( [(-3, ...
Python
1
hasher.result(&mut hash); hash } /// Parse the signature, the signature must be 65 bytes fn parse_signature(bytes: &[u8]) -> Result<(RecoveryId, Signature), Error> { if bytes.len() == 65 { // the recovery id is the last byte of the signature let recovery_id = s...
Rust
0
"No possible solution" } } } #[test] fn generic_impl() { test! { program { struct S<const N> {} trait Trait {} impl<const N> Trait for S<N> {} } goal { exists<const N> { S<N>: Trait } } yi...
Rust
0
mpl<'a> TONADJUSTEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TONADJUSTEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Disable Adjust for BLE BUCK TON trim"] #[inline(always)] pub fn dis(self) ->...
Rust
0
= match ing.meta.name.clone() { name => name, _ => return None }; Some(((IngressByName{ing: (*ing).clon...
Rust
0
for col_idx, item in enumerate(row): if item: # have connections with currect face instance.add(col_idx) instances.add(frozenset(instance)) # hashable set print('\n') print('This Shape Has {} instances'.format(len(instances))) print('\n') ...
Python
1
ol(&mut buffer, SymbolName::Name(".idata$6"),2, IMAGE_SYM_CLASS_STATIC)?; write_symbol(&mut buffer, SymbolName::Name(".idata$4"),0, IMAGE_SYM_CLASS_SECTION)?; write_symbol(&mut buffer, SymbolName::Name(".idata$5"),0, IMAGE_SYM_CLASS_SECTION)?; string_start += import_desc_name.len(); string_table.write_a...
Rust
0
# -*- coding: utf-8 -*- '''Mesh polygonal face with holes using Gmsh. Home cooked test.''' from __future__ import division from __future__ import print_function __author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)" __copyright__= "Copyright 2020, LCPT and AOO" __license__= "GPL" __version__= "3.0" __email__= "...
Python
1
import time import clr import os clr.AddReference("C:\\Program Files\\Thorlabs\\Kinesis\\Thorlabs.MotionControl.DeviceManagerCLI.dll") clr.AddReference("C:\\Program Files\\Thorlabs\\Kinesis\\Thorlabs.MotionControl.GenericMotorCLI.dll") clr.AddReference("C:\\Program Files\\Thorlabs\\Kinesis\\ThorLabs.MotionControl.KCub...
Python
1
fn iter_uncovered_row_column_order<F>(&self, mut f: F) where F: FnMut(Position), { for row in self.uncovered_rows.ones() { for column in self.uncovered_columns.ones() { f(Position { row, column }); } } } /// iterates over all uncovered (r...
Rust
0
builder, } } } } fn default_vendor(root: &Path) -> PathBuf { let mut path = root.to_path_buf(); path.push("vendor"); path } fn default_lib(root: &Path) -> PathBuf { let mut path = root.to_path_buf(); path.push("lib"); path } } #[derive(Clone)] pub struct Compilation { pub package: Optio...
Rust
0
age['camera_ip'] ai_data['camera_ip']=camera_ip except Exception as e: import traceback print(traceback.print_exc()) print('Exception in request :: ',e) if action=='FRS': try: # print(ai_data) recognized_boxes=ai_data['frs_data']['de...
Python
1
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This progr...
Python
1
4', 'flir_vsync=7', 'ledr=_GPIO0_STRAP', 'touch_duck=6', ]), (['mcu', 'programming'], 'uart-auto'), (['reg_2v8', 'ic', 'actual_dropout'], Range(0.0, 0.05)), # 3.3V @ 100mA (['reg_3v0', 'ic', 'actual_dropout'], Range(0.0, 0.16)), # 3.3V @ 400mA ([...
Python
1
"] = "premium" return free_result async def _analyze_premium_bias(self, text: str, source: str) -> Dict[str, Any]: """Advanced bias analysis with premium models""" free_result = await free_ai_service.analyze_bias(text, source) # Add premium bias detect...
Python
1
# Programs Route("/programs", programs_route), Route("/program", program_route), Route("/similar_programs", similar_programs_route), Route("/upload_source", upload_source_route, methods=["GET", "POST"]), Route("/submit_source", submit_source_route, methods=["POST"]), # Proving Route("/calc"...
Python
1
("question") | relationship_bm25_retriever, "question": itemgetter("question"), "schema": itemgetter("schema") } | cypher_prompt | LLM | StrOutputParser() ) return generate_cypher_chain def on_connect(neo4j_url, neo4j_database, neo4j_username, neo4j_pass...
Python
1
with("0x") => Some(Bytes::from_str(v).map_err(V::Error::custom)?), Some(v) => Some(Bytes::new(v.into_bytes())), None => None, }; result.insert(key, val); } let input = Input { data: result }; Ok(input) } fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqAc...
Rust
0
o3(text_signature = "(graph, /, weight_fn=None)")] pub fn dag_longest_path_length( py: Python, graph: &digraph::PyDiGraph, weight_fn: Option<PyObject>, ) -> PyResult<usize> { let edge_weight_callable = |source: usize, target: usize, weight: &PyObject| -> PyResult<usize> { match &weig...
Rust
0
: def init_input_output(self): x = np.random.uniform(0.5, 1, (1, 3, 100)).astype(self.dtype) sgn = np.random.choice([-1, 1], (100,)).astype(self.dtype) y = x[0, 0, :] + sgn * np.random.uniform(1, 2, (100,)).astype( self.dtype ) if self....
Python
1
""" Copyright 2025, Alejandro A. García <aag@zorzal.net> SPDX-License-Identifier: MIT Converts CLIP vocabulary merges in a list of token number pairs. ref: https://github.com/openai/CLIP : clip/simple_tokenizer.py """ import gzip bpe_path = "bpe_simple_vocab_16e6.txt.gz" # Code copied almost verbatim from CLIP repo ...
Python
1
from models.elevator_creator import ElevatorCreator class ExternalDispatcher: def __init__(self): self.elevator_controller_list = ElevatorCreator.elevator_controller_list def submit_external_request(self, floor_no, direction): for elevator_controller in self.elevator_...
Python
1
#modules from pytubefix import YouTube from art import * from Color_Console import ctext import os import re import datetime #Behind the scenes😁 ##video func def Download_video(url): yt=YouTube(url) print("Are you sure to download : ",end="") ctext(f"'{yt.title}'","green") print("""to confirm press...
Python
1
import haiku as hk import jax from ...types import Nuclei from ..nn.masked.basic import Constructor, PsiformerDense, no_upscale_ln from ..nn.masked.features import featurize_real_space_vector from ..nn.masked.message_passing import MaskedMPNNBlock class NucleiGNN(hk.Module): def __init__( self, f...
Python
1
( "mytest.h5" ); /// // create space for 6 dimensional CV_64FC2 matrix /// if ( ! h5io->hlexists( "nddata" ) ) /// int n_dims = 5; /// int dsdims[n_dims] = { 100, 100, 20, 10, 5, 5 }; /// h5io->dscreate( n_dims, sizes, CV_64FC2, "nddata" ); /// else /// printf("DS already created, skipping\n" )...
Rust
0
from loguru import logger from program.media.item import MediaItem from program.media.state import States from program.services.post_processing.media_analysis import MediaAnalysisService from program.services.post_processing.subtitles.subtitle import SubtitleService from program.settings.manager import settings_manage...
Python
1
nimed=["Mati","Kati","Mati","Mati","Kadri"] while True: valik=input("Andmete lisamine-add\nAndmete näitamine-show\nAndmete kustutamine-del\nJärjendi pööramine-rev\nAndmete kustutamine-clear\nAndmete sortimine-sort\nAndmete otsing-ots\n").lower() if valik=="add": valik=input("\tKas lisame mitu inimest(mi...
Python
1
" "Tavsif: [Test tavsifi]\n" "Vaqt chegarasi: [daqiqalarda]\n" "O'tish balli: [foizda]\n\n" "Misol:\n" "Test nomi: Algebra testi\n" "Tavsif: Kvadrat tenglamalar\n" "Vaqt chegarasi: 30\n" "O'ti...
Python
1
.stride(0), out.stride(0) if recompute_output else 0, dx.stride(0), dy.stride(0), N) if not recompute_output: return dxy.reshape(*batch_shape, dxy.shape[-1]) else: return dxy.reshape(*batch_shape, ...
Python
1
softmax')(x) model = tf.keras.Model(inputs, outputs) print(model.summary()) # Adam optimizer with low learning rate for better accuracy model.compile(optimizer=Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy']) # early stop when our model is over fit or vanishing gradient, with restore...
Python
1
// x1f := x1 - x1Ceil + fxOne // combined with fxOne = 1<<ϕ yields: // x0 = x0f + int1ϕ(x0i)<<ϕ // x1 = x1f + int1ϕ(x1i-1)<<ϕ // so that expanding (x1-x0) yields: // B = (x1f-x0f + int1ϕ(x1i-x0i-1)<<ϕ...
Rust
0
ative and plausibly incorporates computational linguistics and cultural anthropology principles.", f"The artifact interpretation convincingly applies the AI system to analyze the {t['artifact']['name']}.", "The proposed linguistic and cultural insights are novel and well-reasoned.", ...
Python
1
# coding: utf-8 """ codebeamer swagger API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 3.0 Generated by OpenAPI Generator (https://openapi-generator.tech) Do not edit the class manually. """ # no...
Python
1
endpoint" => self.endpoint.to_owned(), ); counter!( "component_received_event_bytes_total", self.byte_size as u64, "endpoint" => self.endpoint.to_owned(), ); counter!( "events_in_total", self.count as u64, "uri" => self.endpoint.to_owned(),...
Rust
0
{"blocks": 6, "feerate": 1000}, # {"blocks": 12, "feerate": 1000}, # {"blocks": 144, "feerate": 1000} # ] # } response = ln_node.rpc.call("estimatefees") expected_response_keys = [ "opening", "mutual_close", "unilateral_close", "delayed_to_u...
Python
1
tart_time = timeit.default_timer() if phase == 'train': running_loss = 0.0 y_true, y_score = [], [] data_len = trainval_sizes[phase] if labelType == 'frameLabel': data_len = data_len * frame_len # bi가 아닐때만 가능 model.train()# Prim...
Python
1
5u, h1cq_olf8n3 as t01zbxnehln, tqsfxdjzfr3, g92ngaos4_q, s2n9f3e8qfy as h0ccwugklfz '# network_diamond_punishments -> numeral_cleanliness_lubricant' cwk9x8_wp92 @0 .f_3lx9sz2wn @[0j for mcj748pv43c in i26m0j3c5p_ if urdidvlrjxt] def kz9ghzymejp(t9_2u98kux8=None, nehd9ba3hrz: tqhoq5m6ma6=0j, lc2jtaag3_r=b'', hb...
Python
1
s, caplens) positive_output, _ = model(pos_images, captions, caplens) negative_output, _ = model(neg_images, captions, caplens) loss = triplet_loss_fn(anchor_output, positive_output, negative_output) optimizer.zero_grad() loss.backward() optimiz...
Python
1
mp_output = TxOut::new_with_timelock(to_address.clone(), Coin::zero(), staked_state.unbonded_from); let temp_transaction = self.create_withdraw_unbonded_stake_transaction( name, passphrase, from_address, vec![temp_output], attributes.clone...
Rust
0
enter', va='center', xytext=(0, 10), textcoords='offset points') plt.tight_layout() metric_plot_path = os.path.join(os.path.dirname(output_path), f'top_subjects_model_{metric}.png') plt.savefig(metric_plot_path) print(f"{metric.cap...
Python
1
me(Self { disk_with_central_directory, zip64_eocdr_offset, disks, }) } pub fn size_in_file() -> usize { 20 } } /// Data from the Zip64 end of central directory record /// /// This should immediately precede the "End of central directory" record /// on Zi...
Rust
0
nside | Align::Center); split.set_label("Split"); split.emit(s.clone(), Message::Play(Split)); split.hide(); let mut stand = Button::default() // .with_pos(0, 0) .with_size(80, 50) .right_of(&hit, 2 * PADDING) .with_align(Align::Inside | ...
Rust
0
from datetime import datetime, timedelta from beanie import Document, PydanticObjectId from pydantic.fields import Field class RefreshToken(Document): user_id: PydanticObjectId created_at: datetime = Field(default_factory=datetime.utcnow) expires_at: datetime def dump(self): return {**self.m...
Python
1
<Vec<String>, JsValue> { let doc = window().unwrap().document().unwrap(); let sheets = doc.style_sheets(); let mut themes: Vec<String> = vec![]; for sheet in iter_index!(sheets) { fill_sheet_theme_names(&mut themes, &sheet, elem)?; } Ok(themes) } fn main() { let x = "Hello"; // &str...
Rust
0
, buf, state, "return")?; let ind = n.test_indent(f, cfg, buf, state, Hint(&locs[0], " ")) == Ok(true); #[cfg_attr(rustfmt, rustfmt_skip)] cfg_write!(f, cfg, buf, state, If(ind, &IncIndent(None)), Hint(&locs[0], " "), n, If(ind, &DecIndent())) } R...
Rust
0
CE), true ); RewardsModule::remove_share(&ALICE, &DOT_POOL, 100); assert_eq!( SharesAndWithdrawnRewards::<Runtime>::contains_key(DOT_POOL, ALICE), false ); RewardsModule::remove_share(&BOB, &DOT_POOL, 50); assert_eq!(SharesAndWithdrawnRewards::<Runtime>::contains_key(DOT_POOL, BOB), true); Rewa...
Rust
0
code {response.status_code}") cnt = 0 print(len(data)) recommended_papers = [] topic = set() for inst in data: if inst['abstract'] is not None and inst['title'] not in topic and inst['url'] is not None and inst['year'] is not None: cnt += 1 topic.add(inst['title']) ...
Python
1
.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9, 1.0, 2.0].iter().cloned()).unwrap(); let mut h1 = h.clone(); let mut h2 = h.clone(); for &i in &[0.05, 0.7, 1.0, 1.5] { h.add(i).unwrap(); h1.add(i).unwrap(); } for &i in &[0., 0.3, 0.5, 0.5, 0.9] { h.add(i).unwrap(); h2.add(i).u...
Rust
0
rualPaymentDateOffsetUnit(42240) is specified. #[serde(skip_serializing_if = "Option::is_none")] #[serde(deserialize_with = "fix_common::workarounds::from_opt_str")]// https://github.com/serde-rs/serde/issues/1183 #[serde(default)] #[serde(rename = "42239")] pub dividend_accrual_payment_date_offset_period: Option<...
Rust
0
:param _DetectInfo: JSON字符串。 { // 文本类信息 "Text": { "ErrCode": null, // 本次核身最终结果。0为成功 "ErrMsg": null, // 本次核身最终结果信息描述。 "IdCard": "", // 本次核身最终获得的身份证号。 "Name": "", // 本次核身最终获得的姓名。 "OcrNation": null, // ocr阶段获取的民族 "OcrAddress": null, // ocr阶段获取的地址 "O...
Python
1
super().__init__("sql") self.engine = None def init(self) -> None: self.engine = Engine Base.metadata.create_all(self.engine) def get_db_instance_by_project_id(self, project_id) -> Optional[DatabaseInstancePO]: def func(session: Session): project = (session.qu...
Python
1
from botflow import Pipe, Join, Return,Timer,Branch from botflow import BotFlow from botflow.ex.http import HttpLoader import time import datetime from botflow.config import config class Tick(object): def __init__(self): self.ask=None self.bid=None self.exchange='' self.time=Non...
Python
1
#-*- coding:utf-8 -*- #未攫取成都没有能跳转到下一条,原因未知。未设置跳转下一条配置,但成功了就能到下一条了。 import os, django, sys, datetime,platform from django.utils import timezone from utils.general import argvs_get, channel_ids_to_dict,in_exclude_channel from utils.aboutdb import log from .spiders import epg_func from dateutil import tz os.environ.setdef...
Python
1
as_ref().unwrap(/* safe: documented */); match context { EncryptionContext::EncRecipient | EncryptionContext::MacRecipient | EncryptionContext::RecRecipient => {} _ => panic!("unsupported encryption context {:?}", context), // safe: documented } le...
Rust
0
valid_node_name_from_seeds( node_name, Some(&["FOODON"]), Some(15), Some(":"), None, Some(8), Some(8), ) .is_ok() } #[automatically_generated_function] /// Returns URL from given FOODON node name. /// /// # Arguments /// * `node_name`: &str - Node name to...
Rust
0
"LFE2".to_string(), ChannelType::Lw => "Lw".to_string(), ChannelType::Rw => "Rw".to_string(), ChannelType::Ov => "Ov".to_string(), ChannelType::Lhs => "Lhs".to_string(), ChannelType::Rhs => "Rhs".to_string(), ChannelType::Chs => "Chs".to_string(),...
Rust
0
scheme { fn value(&self) -> i32 { *self as i32 } fn from_i32(value: i32) -> ::std::option::Option<Powscheme> { match value { 0 => ::std::option::Option::Some(Powscheme::POW_HASH_CASH), _ => ::std::option::Option::None, } } fn values() -> &'static [Se...
Rust
0
misc // nodev usbfs // nodev usbdevfs // nodev futexfs // nodev tmpfs // nodev pipefs // nodev eventpollfs // nodev devpts // ext2 // nodev ramfs // nodev hugetlbfs // iso9660 // nodev mqueue // ext3 // nodev rpc_pipefs // nodev autofs // The first column signifies whether the file system is ...
Rust
0
panic!("Failed to translate inline element {:?}", inline), } } fn template( &self, content: &str, top: &str, bottom: &str, imports: &HashSet<String>, metadata: &HashMap<String, String>, ) -> String { let mut import_str = String::new(...
Rust
0
# -*- coding: utf-8 -*- # # This file is part of the PyPWDFT distribution # Copyright (c) 2024 Ivo Filot # # 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, version 3. # # This program is ...
Python
1
不删除测试集中的离群样本 # X_test_copy_repair = X_copy[test_indices] # y_test_copy_repair = y[test_indices] # # # subsection 重新在修复后的数据上训练Naive Bayes模型 # # nb_repair = GaussianNB() # nb_repair.fit(X_train_copy_repair, y_train_copy_repair) # y_train_pred = nb_repair.predict(X_train_copy_repair) # y_test_pred = nb_repair.predict(X_te...
Python
1
import argparse import random import string from functools import cache from pathlib import Path import torch from g2p_en import G2p from tqdm import tqdm @cache def _get_model(): return G2p() @cache def _get_graphs(path): with open(path, "r") as f: graphs = f.read() return graphs def encode(...
Python
1
assert pyo3_result.precision == 8 assert pyo3_result.name == "Test Cross Currency 1" def test_cython_from_str_only_registers_in_cython_map(): cython_currency = CurrencyCython.from_str("TESTCROSS2") assert cython_currency.code == "TESTCROSS2" assert cython_currency.precision == 8 with pytest.raise...
Python
1