text
string
label_name
string
labels
int64
mut Option<M>>) -> OptionLoaned<&'a mut T> { match result { Some(inner) => { match inner.as_mut() { Some(inner) => OptionLoaned::Some(inner.borrow_mut()), None => OptionLoaned::Loaned, } } None => Option...
Rust
0
command=( "from maya_zen_tools import loft;" "loft.show_loft_distribute_uvs_between_edges_or_uvs_options()" ), parent=MENU, ) cmds.menuItem(label="Help", parent=MENU, divider=True) cmds.menuItem( label="About ZenTools", command=( "impo...
Python
1
for i, batch in enumerate(tqdm(dataloader)): view_id = f"{i:03d}" camCv2world = batch["camCv2world"] K = batch["K"] real_img = batch["img"] obj_mask_1d = batch["obj_mask_1d"] distortion_params = batch.get("distortion_params") distort...
Python
1
g: &impl IsA<Message>) -> Vec<Cookie> { skip_assert_initialized!(); unsafe { FromGlibPtrContainer::from_glib_full(ffi::soup_cookies_from_response(msg.as_ref().to_glib_none().0)) } } //#[doc(alias = "soup_form_decode")] //pub fn form_decode(encoded_form: &str) -> /*Unknown conversion*//*Unimplemente...
Rust
0
default = None desc = """\ CA certificates file """ class SuppressRaggedEOFs(Setting): name = "suppress_ragged_eofs" section = "SSL" cli = ["--suppress-ragged-eofs"] action = "store_true" default = True validator = validate_bool desc = """\ Suppress ragged EOFs (see std...
Python
1
_valid_balance_ratio(balance_ratio: Rate) -> bool { Rate::zero() <= balance_ratio && balance_ratio <= Rate::one() } } impl<T: Config> PoolsManager<T::AccountId> for Pallet<T> { /// Gets module account id. fn pools_account_id() -> T::AccountId { T::LiquidationPoolsPalletId::get().into_account() } /// Gets curr...
Rust
0
d(); // Not-default let (fg, bg, modifiers) = use_or_default_styles(&props, &span); assert_eq!(fg, Color::Yellow); assert_eq!(bg, Color::Cyan); assert!(modifiers.intersects(Modifier::UNDERLINED)); // Default let span: TextSpan = TextSpan::from("test"); let...
Rust
0
: Option<unsafe extern "C" fn()>, // } // impl ::std::fmt::Debug for ClutterScriptClass { // fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { // f.debug_struct(&format!("ClutterScriptClass @ {:?}", self as *const _)) // .field("get_type_from_name", &self.get_type_from_name) ...
Rust
0
Result<PathBuf> { use std::convert::TryInto; use std::mem::size_of; use std::ffi::OsString; use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStringExt; use winapi::um::winreg::RegGetValueW; use winapi::um::winreg::HKEY_CURRENT_USER; use winapi::um::winreg::RRF_RT_REG_SZ...
Rust
0
def pre_act_resnet101(pretrained=False): return _pre_act_resnet('pre_act_resnet101', PreActBottleneck, [3, 4, 23, 3], pretrained=pretrained)
Python
1
))] #[transactional] pub fn transfer_multiasset_with_fee( origin: OriginFor<T>, asset: Box<VersionedMultiAsset>, fee: Box<VersionedMultiAsset>, dest: Box<VersionedMultiLocation>, dest_weight: Weight, ) -> DispatchResult { let who = ensure_signed(origin)?; let asset: MultiAsset = (*asset).try_...
Rust
0
se + "e") # e.g., "coding" -> "code" if keyword.endswith("ed"): # Remove -ed base = keyword[:-2] if len(base) > 2: search_terms.append(base) search_terms.append(base + "e") # e.g., "created" -> "create" # Ded...
Python
1
data: (0..len).map(|_| T::default()).collect(), } } /// Returns the number of dimensions in the array. pub fn num_dims(&self) -> usize { self.dims.len() } /// Converts a ND index into a 1D index. fn nd_to_1d(&self, indexes: &[usize]) -> usize { assert_eq!(self.dims.l...
Rust
0
#!/opt/manager/env/bin/python import os import re import sys import socket import logging import argparse from manager_rest import config from manager_rest.flask_utils import setup_flask_app from manager_rest.storage import db, models logger = logging.getLogger(__name__) def update_managers_version(version): l...
Python
1
class MEPSize(object,IDisposable): """ Stores the basic size information for an MEP duct,pipe,cable tray,or conduit. MEPSize(nominalDiameter: float,innerDiameter: float,outerDiameter: float,usedInSizeLists: bool,usedInSizing: bool) """ def Dispose(self): """ Dispose(self: MEPSize) """ pass def ReleaseUnma...
Python
1
# Copyright (c) OpenMMLab. All rights reserved. import torch def split_batch(img, img_metas, kwargs): """Split data_batch by tags. Code is modified from <https://github.com/microsoft/SoftTeacher/blob/main/ssod/utils/structure_utils.py> # noqa: E501 Args: img (Tensor): of shape (N, C, H, W) e...
Python
1
[prost(enumeration="ProposalDecisionStatus", repeated, tag="5")] pub include_status: ::prost::alloc::vec::Vec<i32>, } /// A response to the ListProposals command. #[derive(candid::CandidType, candid::Deserialize)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListProposalsResponse { /// The returned ...
Rust
0
fn gmonth_parse_test() { // No timezone. assert_eq!( GMonth::from_str("--12"), Ok(GMonth { value: 12, timezone: None }) ); // Timezone "Z". assert_eq!( GMonth::from_str("--12Z"), Ok(G...
Rust
0
import pybamm class VoltageModel(pybamm.BaseSubModel): """ Voltage model for use with equivalent circuits. This model is used to calculate the voltage and total overpotentials from the other elements in the circuit. Parameters ---------- param : parameter class The parameters ...
Python
1
.field("clone", &self.clone) .field("init_from_rc", &self.init_from_rc) .field("set_background", &self.set_background) .field("render_icon", &self.render_icon) .field("draw_hline", &self.draw_hline) .field("draw_vline", &self.draw_vline) .field("draw_shadow", &self....
Rust
0
from typing import Tuple import torch from torch import nn, Tensor import torch.nn.functional as F __all__ = ["TrajGRUCell"] def _warp(input: Tensor, flow: Tensor) -> Tensor: """ 这个操作和可变形卷积类似 """ device = input.device B, C, H, W = input.size() # mesh grid # 这两行代码很像 broadcasting # sh...
Python
1
:Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("android/renderscript/Sampler$Builder\0", "create\0", "()Landroid/renderscript/Sampler;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } ...
Rust
0
w0 = np.random.uniform(0, 1, size=N) # w0 /= np.sum(w0) # # # setting contraints # constraints = [ # weight_constraint, # {'type': 'eq', 'fun': lambda w, target=target: np.dot(w, drift) - target} # actual portfolio return must equal fixed portf...
Python
1
return -4 always; } assert_eq!(12, mock.foo(5)); assert_eq!(-4, mock.boo()); } fn return_call_with_args() { let mock = new_mock!(A); given! { <mock as A>::foo(|_| true) then_return_from |&(x)| x + 1 always; } assert_eq!(6, mock.foo(5)); } ...
Rust
0
import numpy from thinc.backends._param_server import ParamServer def test_param_server_init(): array = numpy.zeros((5,), dtype="f") params = {("a", 1): array, ("b", 2): array} grads = {("a", 1): array, ("c", 3): array} ps = ParamServer(params, grads) assert ps.param_keys == (("a", 1), ("b", 2)) ...
Python
1
# Just return having found a repo already in the dest path before = hg.get_revision() elif hg.at_revision: # no update needed, don't pull before = hg.get_revision() # but force and purge if desired cleaned = hg.cleanup(force, purge) else: # get the curre...
Python
1
raw(&self) -> CH2_ERR_INT_RAW_R { CH2_ERR_INT_RAW_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - The interrupt raw bit for channel 3 turns to high level when the transmit process is done."] #[inline(always)] pub fn ch3_tx_end_int_raw(&self) -> CH3_TX_END_INT_RAW_R { CH3_TX_END...
Rust
0
sys::ctypes::c_char = ptr::null_mut(); let graphics = Graphics::get(); pd_func_caller!( (*graphics.0).loadIntoBitmap, c_path.as_ptr(), self.raw_bitmap, &mut out_err )?; if out_err != ptr::null_mut() { let err_msg = unsafe { CStr...
Rust
0
from_slice(&[term]).unwrap(); prop_assert_eq!(native(&arc_process, list), Err(badarg!().into())); Ok(()) }, ) .unwrap(); } #[test] fn with_two_element_tuple_list_returns_value() { TestRunner::new(Config::with_source_file(file!())) .run( ...
Rust
0
pub fn print(&mut self, string: String, x: i32, y: i32, col: i32) { let mut x = x; let y = y; for k in 0..string.len() { let value = string.as_bytes()[k] as usize; let data; if value >= 32 && value <= 126 { data = GLYPH[value - 32]; ...
Rust
0
= ptr::null_mut(); let mut source_object = ptr::null_mut(); let res = ffi::g_socket_listener_accept_socket_finish(_source_object as *mut _, res, &mut source_object, &mut error); let result = if error.is_null() { Ok((from_glib_full(res), from_glib_none(source_object))) } else { Err(fr...
Rust
0
AdvancedStateCreateInfoEXT.html) /// /// Struct Extends: [`VkPipelineColorBlendStateCreateInfo`] VkPipelineColorBlendAdvancedStateCreateInfoEXT { /// * **Values:** [`VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_ADVANCED_STATE_CREATE_INFO_EXT`] sType: VkStructureType, /// * **Optional:** true pNext: *con...
Rust
0
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Fa...
Python
1
= U64; type GenesisEpoch = U0; fn default_spec() -> ChainSpec { ChainSpec::mainnet() } } pub type FoundationBeaconState = BeaconState<MainnetEthSpec>; /// Ethereum Foundation minimal spec, as defined here: /// /// https://github.com/ethereum/eth2.0-specs/blob/v0.6.3/configs/constant_presets/mini...
Rust
0
, x, mask) mask = gene_mask(y) y = self.decoder_layer4(y, y, y, x, x, mask) return y # Calculate the Mask through the cosine similarity between patches def gene_mask(x): x = x.reshape([-1, 28 * 28, 512]) x = F.normalize(x, dim=-1) mask = torch.matmul(x, x.transpose(-1, -2).contig...
Python
1
import streamlit as st import time # Title 작성 st.title("Color Picker 구현") # 코드 표시 st.subheader("코드") code = ''' import streamlit as st import time text = """ #### 1절 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세 무궁화 삼천리 화려 강산 대한 사람 대한으로 길이 보전하세 #### 2절 남산 위에 저 소나무 철갑을 두른 듯 바람 서리 불변함은 우리 기상일세 무궁화 삼천리 화려 강산 대한 사람 대한으로...
Python
1
-(?P<plat>.+) )? )? )? cB@seZdZd d ddZdZdZedZdZ dddZ e j dZ eddZed Zedd Zedd ZRS(s3Object representing an advertised importable objectcC@...
Python
1
import re with open('abc.java', 'r') as file: java_code = file.read() pattern = r'public\s+static\s+void\s+main\s*\(\s*String\s*\[\s*\]\s*[a-zA-Z0-9]*\s*\)\s*{' matches = re.findall(pattern, java_code) class_name = None if matches: main_method_match = matches[0] class_name_pattern = r'class\s+([a-zA-Z][a-zA...
Python
1
__all__ = ['AnyCallable', 'MISSING', 'Possibly', 'Decorator', 'F'] from enum import Enum from typing import Any, Callable, TypeVar, Union # PEP-blessed solution for defining a Singleton type: # https://peps.python.org/pep-0614/#motivation class _Missing(Enum): flag = 'Missing' MISSING = _Missing.flag """Singl...
Python
1
bleFlags, PhysFrame, Size4KiB}, PhysAddr, VirtAddr, }; mod config { include!(concat!(env!("XTASK_OUT_DIR"), "/cfg_uefi_stub.rs")); } const KERNEL_SIZE: usize = include_bytes!(env!("KERNEL_PATH")).len(); const KERNEL_BYTES: [u8; KERNEL_SIZE] = *include_bytes!(env!("KERNEL_PATH")); /// Put kernel ELF in memory...
Rust
0
// Formula for line function when working with // homogeneous projective coordinates, as described in https://eprint.iacr.org/2013/722.pdf. let a = r.x * &r.y; let b = r.y.square(); let b4 = b.double().double(); let c = r.z.square(); let e = B::G2Parameters::COEFF_B * &(c.double() + &c); ...
Rust
0
erialize_struct("SpaceUsage", SPACE_USAGE_FIELDS, StructVisitor) } } impl ::serde::ser::Serialize for SpaceUsage { fn serialize<S: ::serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // struct serializer use serde::ser::SerializeStruct; let mut s = serializer.se...
Rust
0
s.iter() { node_labels.entry(s1.as_ref()).or_insert_with(|| { counter += 1; counter }); node_labels.entry(s2.as_ref()).or_insert_with(|| { counter += 1; counter }); } let mut tgf = String::new(); let mut node_label_pairs: Vec<...
Rust
0
ttr(dim, "size"): init_code += f"{{ {dim.size} }}" else: raise ValueError("Error: Missing size value") # Close initialization code init_code += ";" # Append to changes made list self.changes_made.append...
Python
1
|| c.y == self.y_min() || c.x == self.x_max() || c.y == self.y_max() } fn nei_coord_iter(&self, coord: Coord) -> NeiCoordIter { NeiCoordIter::new(coord) } fn nei_iter<'a>(&'a self, coord: Coord) -> NeiIter<'a, Self> where Self: Sized { NeiIter::new(self, coord) } f...
Rust
0
ssage_setter(self): err = ContractLogicError(revert_message="test message 1") err.revert_message = "test message 2" assert str(err) == "test message 2" assert err.message == "test message 2" assert err.revert_message == "test message 2" class TestUnknownSnapshotError: def t...
Python
1
am: print(chunk.content, end="", flush=True) last_response = response assert last_response is not None chat.append(last_response) print() async def main(argv: Sequence[str]) -> None: if len(argv) > 1: raise app.UsageError("Unexpected comman...
Python
1
efault, true); assert_eq!( tokens, vec![ Token { word: "我们", start: 0, end: 2 }, Token { word: "中出", start: 2, end: 4 }, Token { word: "了", start: 4, end: 5 }, Token { word: "一个", start: 5, end: 7 }, Token { ...
Rust
0
.type == aiohttp.WSMsgType.TEXT: asyncio.create_task(client.on_client_message(msg)) elif msg.type == aiohttp.WSMsgType.ERROR: print( f"WebSocket connection closed with exception {ws.exception()}" ) elif m...
Python
1
input::RangeId = input::RangeId(0); const MOUSE_WHEEL_DELTA_Y: input::RangeId = input::RangeId(1); const MOUSE_BUTTON_SEPARATOR: u32 = 1 << 16; fn is_mouse_button(state_id: input::StateId) -> bool { state_id.0 >= MOUSE_BUTTON_SEPARATOR && (state_id.0 < (MOUSE_BUTTON_SEPARATOR + 5)) } const fn is_keyboard_button(...
Rust
0
SUCCESS_REG_TEXT = 'Thank you for registering with Main Website Store.' REQUIRED_FIELD_TEXT = 'This is a required field.' PSWRD_CONFIRMATION_ERROR_TEXT = 'Please enter the same value again.' MAIN_SALE_WOMAN_INFO = "Women’s Deals" MAIN_SALE_WOMAN_TITLE = "Pristine prices on pants, tanks and bras." MAIN_SALE_WOMAN_BUT...
Python
1
# -*- test-case-name: twisted.python.test.test_constants -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Symbolic constant support, including collections and constants with text, numeric, and bit flag values. """ # Import and re-export Constantly from constantly import FlagConstant, F...
Python
1
xt = torch.multinomial(probs, num_samples=1) idx = torch.cat((idx, idx_next),dim=1) return idx model= BigramLanguageModel() m = model.to(device) optimizer = torch.optim.AdamW(model.parameters(),lr=lr) for steps in range(max_iters): if steps % eval_interval == 0: losses = estimate_loss() print(f"s...
Python
1
128(&self) -> bool { *self == DIV_A::DIV128 } } #[doc = "Write proxy for field `DIV`"] pub struct DIV_W<'a> { w: &'a mut W, } impl<'a> DIV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DIV_A) -> &'a mut W { unsafe { self.bits(varian...
Rust
0
pass-hooks', '--cc=""', '--bypass-watchlist'] if commit_queue_mode >= 2: logging.info('Sending the CL to the CQ...') cmd.extend(['--use-commit-queue']) elif commit_queue_mode >= 1: logging.info('Starting CQ dry run...') cmd.extend(['--cq-dry-run']) subprocess.check...
Python
1
# cook your dish here # Input number of test cases T = int(input()) # Loop through each test case for _ in range(T): # Input the values of X and Y X, Y = map(int, input().split()) # Calculate the total working hours in one week total_hours = 4 * X + Y # Output the result print(total_h...
Python
1
= data_train[3] with torch.cuda.amp.autocast(): restored = model_restoration(input_, mask) restored = torch.clamp(restored,0,1) psnr_train_rgb.append(utils.batch_PSNR(restored, target, False).item()) psnr_train_rgb = sum...
Python
1
"Taillard-like: RL - PPO (Makespan: {rl_taillard_makespan:.2f})") except Exception as e: print(f"\nError processing Taillard-like data: {e}") print("Skipping Taillard-like problem due to parsing or processing issue.") return { 'original': { 'exact': (exact_schedule, exact_...
Python
1
#[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct HOST_IF__STATUS(u8); impl Debug; u8; pub get, set: 0; } bitfield! { #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct PAD_I2C_HV__CONFIG(u8); impl Debug; u8; pub vmodeint_hv, set_vmodeint_hv: 0, 7; pub test_hv, set_...
Rust
0
{ println!("id: {}, area: {}", id, contained_area_count[&id]); } } println!("{:?}", on_edge_ids); } fn day6b(mut matrix: Vec<Vec<Option<usize>>>, coordinates: &[(usize, (usize, usize))], distance_threshold: isize) { for row in 0..matrix.len() { for col in 0..matrix[0].len() { ...
Rust
0
# # # Copyright (C) 2010 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and ...
Python
1
ption::is_none")] pub name: Option<String>, #[serde(rename = "nameChangeFlag", skip_serializing_if = "Option::is_none")] pub name_change_flag: Option<bool>, #[serde(rename = "partnerId", skip_serializing_if = "Option::is_none")] pub partner_id: Option<String>, #[serde(rename = "profileIconId", s...
Rust
0
# encoding: utf-8 import pytest from tests import utils from app import create_app @pytest.yield_fixture(scope='session') def flask_app(): app = create_app(flask_config_name='testing') from app.extensions import db with app.app_context(): db.create_all() yield app db.drop_all() ...
Python
1
def check_model_list(): """Check the model list inside the transformers library.""" models_dir = os.path.join(PATH_TO_DIFFUSERS, 'models') _models = [] for model in os.listdir(models_dir): model_dir = os.path.join(models_dir, model) if os.path.isdir(model_dir) and '__init__.py' in os.lis...
Python
1
nic_itm; // logs messages over ITM; requires ITM support // extern crate panic_semihosting; // logs messages to the host stderr; requires a debugger // use cortex_m::asm; use cortex_m_rt::entry; use cortex_m_semihosting::hprint; use stm::{interrupt, Interrupt, NVIC}; use stm::{usart1, GPIOB, U...
Rust
0
# Generated by Django 4.2.1 on 2024-08-22 19:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('panel', '0008_alter_advertisingbannermodel_url'), ] operations = [ migrations.RemoveField( model_name='advertisingbannermodel', ...
Python
1
feature = "zh_Hant_HK")] crate::Annotation { lang: "zh_Hant_HK", tts: Some("↑↑↑"), keywords: &["↑↑↑"], }, #[cfg(feature = "zu")] crate::Annotation { lang: "zu", tts: Some("isandla esiphakanyisiwe esivuliwe"), keyword...
Rust
0
match input to conversion.")) }; } //todo: add tests for exitcodes... external tests? use std::io::Read; use std::fmt; use std::path::{PathBuf, Path}; use std::fs::File; use errors::{ReadError, ReadEnum}; use nginx_config; use nginx_config::visitors::DirectiveIter; use nginx_config::ast::{Directive, Main}; pub ...
Rust
0
str(uuid.uuid4())) res_file = res_file + str(startIdx) + 'to' + str(endIdx) res_file += '.txt' print res_file self._write_ilsvrc_results_file(all_boxes, res_file) # Optionally cleanup results txt file if self.config['cleanup'] and 0: os.remove(res_file) ...
Python
1
import copy users = { 1: {'name': 'Ivan', 'age': 32, 'pets': [{'type': 'dog', 'name': 'Charly'}, {'type': 'cat', 'name': 'Murzic'}, {'type': 'fish', 'name': 'GoldBurzhui'}]}, 2: {'name': 'Milana', 'age': 17, 'pets': [{'type': 'hamster', 'name':'...
Python
1
narwhals.typing import FrameT >>> @nw.narwhalify ... def agnostic_func(df: FrameT) -> FrameT: ... return df.with_columns(c=nw.col("a") + 1) """ DataFrameT = TypeVar("DataFrameT", bound="DataFrame[Any]") """TypeVar bound to Narwhals DataFrame. Use this if your function can accept a Narwhals DataFrame a...
Python
1
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _...
Python
1
omicRmw16CmpxchgU, I64AtomicRmw8CmpxchgU, I64AtomicRmw16CmpxchgU, I64AtomicRmw32CmpxchgU, // 0xFD operators // SIMD https://webassembly.github.io/simd/core/binary/instructions.html V128Load, V128Load8x8S, V128Load8x8U, V128Load16x4S, V128Load16x4U, V128Load32x2S, V128Loa...
Rust
0
headers(&self) -> &hyper::Headers { &self.headers } /// Returns a reference to the request HTTP method. #[inline] pub fn method(&self) -> &Method { &self.method } /// Returns a reference to the request URI. #[inline] pub fn uri(&self) -> &hyper::Uri { &self.uri ...
Rust
0
"""A problem report message.""" import logging from enum import Enum from marshmallow import EXCLUDE, ValidationError, validates_schema from ....problem_report.v1_0.message import ProblemReport, ProblemReportSchema from ..message_types import CREDENTIAL_PROBLEM_REPORT, PROTOCOL_PACKAGE HANDLER_CLASS = ( f"{PROT...
Python
1
n = int(input("Введите количество слов: ")) i = 0 word="" while i < n: word += str(input("Введите слово: ")) word += " " i += 1 else: print(word)
Python
1
e=self.samples).mean(axis=0) for a in all_arms] ) weights = np.exp(self.eta * (rewards - rewards.max(axis=0))) # TODO: This is not actually correct if top_k is used, but top_k is currently # stateless, so we have no idea what it was at the time of selection. # However, ix_gamma ...
Python
1
import torch import torch.nn as nn class Features(nn.Module): def __init__(self, num_layers=3, hidden_dim=256, device='cpu'): super(Features, self).__init__() self.device = device # 文本信息 self.hidden_dim = hidden_dim self....
Python
1
ypes)): type = config.cardTypes[i] #if type == 'StraightFlush': continue for rank1 in actionList[type]: color = None rank = rank1 #to distinguish StraightFlush from others if (type == 'StraightFlush'): rank = rank1[...
Python
1
pd.to_numeric(temp_df["askvol1"], errors="coerce") temp_df["volume"] = pd.to_numeric(temp_df["volume"], errors="coerce") temp_df["position"] = pd.to_numeric(temp_df["position"], errors="coerce") temp_df["preclose"] = pd.to_numeric(temp_df["preclose"], errors="coerce") temp_df["changepercent"] = pd.to_nu...
Python
1
rtiaTensor}; pub use volumetric::volumetric_ball::{ball_volume, ball_surface, ball_center_of_mass, ball_unit_angular_inertia}; pub use volumetric::volumetric_cylinder::{cylinder_volume, cylinder_surface, cylinder_center_of_mass, cylinder_u...
Rust
0
<Self::SerializeMap, Self::Error> { Err(key_must_be_a_string()) } #[inline] fn serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error> { Err(key_must_be_a_string()) } #[inline] fn serialize_struct_var...
Rust
0
} #[repr(C)] #[derive(Copy, Clone)] pub struct PluginSetTheTruthI { pub inst: *mut PluginO, pub set_the_truth: ::std::option::Option<unsafe extern "C" fn(inst: *mut PluginO, tt: *mut TheTruthO)>, } impl Default for PluginSetTheTruthI { fn default() -> Self { let mut s = ::std::mem::MaybeUnin...
Rust
0
details = {} try: t = await TicketCRUD.get_ticket_by_id(db, ticket_id, load_user=True) if t and t.user: details.update({ "target_telegram_id": t.user.telegram_id, "target_username": t.user.username, ...
Python
1
he total number of seasons available for the series. """ if not self.seasons_manager.seasons: self.collect_info_title() return len(self.seasons_manager.seasons) def getEpisodeSeasons(self, season_number: int) -> list: """ Get all episodes for a s...
Python
1
= validate(uri.as_ref())?; Ok(MxcUri { media_id: media_id.into(), server_name: <ServerNameBox>::try_from(server_name)? }) } impl FromStr for MxcUri { type Err = crate::Error; fn from_str(uri: &str) -> Result<Self, Self::Err> { try_from(uri) } } impl TryFrom<&str> for MxcUri { type Error ...
Rust
0
paramset2 = { "parama": 1, "paramb": "foo", "paramc": 42, "experiment": AnotherExperiment("another_experiment_params"), } return [paramset1, paramset2] # this method can, if required, use: # class properties (e.g., inherited); par...
Python
1
ig_site["site"]["solar"] = True hopp_config_site["site"].update({"solar_resource":solar_resource}) else: hopp_config_site["site"]["solar"] = False if "solar_resource" in hopp_config_site["site"]: hopp_config_site["site"].pop("solar_resource") if wind_capacity_mw>0: ho...
Python
1
interrupt" ] Dcmi, # [ doc = "FPU interrupt" ] Fpu, } unsafe impl Nr for Interrupt { fn nr(&self) -> u8 { match *self { Interrupt::Wwdg => 0, Interrupt::Pvd => 1, Interrupt::TampStamp => 2, Interrupt::RtcWkup => 3, Interrupt::Rcc => 5,...
Rust
0
address will be zerod out. For 3B mode, the value in the upper byte /// does not matter, as the controller will automatically pick the /// correct bits (0x0560 => virtual_addr_filter: ReadWrite<u32>), /// Debug register that tracks how many rising edges of CSB has been /// seen...
Rust
0
) highlight_size = mouse_settings.value("highlight_size", 50, type=int) # 鼠标轨迹历史 trail_points = [] last_mouse_pos = None click_effects = [] # 存储点击效果的位置和时间 with mss.mss() as sct: # 如果没有指定区域,使用主显示器 if region is None: ...
Python
1
ount, recipient_id)) sent_at = datetime.utcnow().isoformat() await db._conn.execute( """ INSERT INTO transfers (from_user_id, to_user_id, amount, fee, sent_at) VALUES (?, ?, ?, ?, ?) """, (sender_id, recipient_id, net_amount, commission, sent_at) ) await db._con...
Python
1
it according to the update document. pub fn find_one_and_update( &self, filter: Document, mut update: Document, upsert_data: Option<MinimalFacilityData>, ) -> mongodb::Result<Option<Document>> { let upsert = upsert_data.is_some(); if let Some(facility_info) = up...
Rust
0
!table.display_frees; }, Event::KeyDown { keycode: Some(Keycode::H), ..} => { table.hint(); }, Event::KeyDown { keycode: Some(Keycode::Z), ..} => { table.undo(); }, ...
Rust
0
# Set up axes. ax.grid(which = 'major', axis = 'both', linestyle = '-', color = 'k', linewidth = 2, zorder = 1) ax.set_xticks(np.arange(-0.5, self.track.shape[1] , 1)); ax.set_xticklabels([]) ax.set_yticks(np.arange(-0.5, self.track.shape[0], 1)); ax.set_yticklabels([]) ...
Python
1
lone, Hash, Eq, PartialEq, Deserialize, Serialize)] pub enum SuzunaAdType { ShopNobori, TownNobori, Chindon, NewsPaper, BunBunMaruPaper, AdPaper, } impl SuzunaAdType { pub fn from_str(s: &str) -> Self { match s { "ShopNobori" => Self::ShopNobori, "TownNobori"...
Rust
0
x2 = x2.unsqueeze(0) return x2 else: raise ValueError(f'Unknown modalities: {modalities}') def build_vision_projector(config, delay_load=False, **kwargs): projector_type = getattr(config, 'mm_projector_type', 'linear') if projector_type == 'linear': return nn.L...
Python
1
import argparse import glob import os.path from lada.deepmosaics.models import loadmodel from lada.deepmosaics.inference import restore_video_frames from lada.lib.video_utils import read_video_frames, get_video_meta_data, write_frames_to_video_file def validate(in_dir, out_dir, gpu_id, model_path): model = loadmod...
Python
1
`child` unless the /// `show_mask` flag is set. In this case the mask widget is /// displayed and the input to the `child` is supressed. /// /// The default mask widget is a simple [Spinner] displayed in the /// center. pub fn new(child: impl Widget<T> + 'static) -> Self { let mask = Al...
Rust
0
ASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } JAZZMIN_SETTINGS = { 'site_title': 'Admin Panel', 'site_header': 'A...
Python
1