text
string
label_name
string
labels
int64
from yacs.config import CfgNode as CN _C = CN(new_allowed=True) _C.env = CN(new_allowed=True) _C.env.gpus = [0] _C.env.meta_arch = False _C.env.nprocs = 0 _C.dataset = CN(new_allowed=True) _C.dataset.type = 'train' _C.dataset.name = 'celeba_a' _C.dataset.tasks_name = [] # task name # common _C.dataset.args = CN(new_...
Python
1
.stop(&app, &version, time::Duration::from_secs(5)) .await .context("Failed to stop container")?; } // Check if we need to umount if mode != Mode::StartStop { client ...
Rust
0
me @LastUpdateTime.setter def LastUpdateTime(self, LastUpdateTime): self._LastUpdateTime = LastUpdateTime @property def MaxRetryTimes(self): """最大重试次数 注意:此字段可能返回 null,表示取不到有效值。 :rtype: int """ return self._MaxRetryTimes @MaxRetryTimes.setter def MaxRetr...
Python
1
rt = {:?}",GetId(id2)); } //匹配中的default. rust 中匹配必须穷尽所有.(支持default) //思路就是, 写明白你在做什么. #[test] fn cb0x_match03() { let v = 5; let rt = match v { 7 =>17, _ =>27, }; println!("rt = {:?}",rt); let rt = match v { 7 =>17, other =>other, }; println!("rt = {:?}",r...
Rust
0
status. // broadcast block. } } /// current height. pub(crate) async fn sync_req(group: &mut Group) -> Result<u64> { todo!() } /// current height. blocks, pool events. pub(crate) async fn sync_res(group: &mut Group) -> Result<(u64, Vec<BlockId>, Vec<EventId>)> { todo!() } /// after connect & syn...
Rust
0
import numpy as np from scipy import stats from sklearn import metrics import torch def d_prime(auc): standard_normal = stats.norm() d_prime = standard_normal.ppf(auc) * np.sqrt(2.0) return d_prime @torch.no_grad() def concat_all_gather(tensor): """ Performs all_gather operation on the provided ...
Python
1
iants() { let dict = Dictionary::fix44(); let field_36 = dict.field_by_tag(36).unwrap(); assert_eq!(field_36.name(), "NewSeqNo"); assert!(field_36.enums().is_none()); } #[test] fn fix44_field_167_has_eucorp_variant() { let dict = Dictionary::fix44(); let fiel...
Rust
0
} Ok(()) } fn rx_bytes_available(&mut self) -> Result<u8, Error<SpiE, GpioE>> { let mut last = 0; loop { let rxbytes = RXBYTES(self.0.read_register(Status::RXBYTES)?); if rxbytes.rxfifo_overflow() == 1 { return Err(Error::RxOverflow); ...
Rust
0
eserialize)] pub struct Block { #[serde(rename = "type")] block_type: BlockType, #[serde(rename = "recMath")] rec_math: bool, #[serde(rename = "recSteps")] rec_steps: bool, #[serde(rename = "minSummonerLevel")] min_summoner_level: i64, #[serde(rename = "maxSummonerLevel")] max_su...
Rust
0
4, payload: Payload::Literal(3) } ] }), packet.payload ); assert_eq!(None, decoder.next()); } fn version_sum(decoder: Decoder) -> u32 { let mut sum = 0; for packet in decoder { sum += version_sum_packet(packet); } sum } f...
Rust
0
) CloseMessageWindow() ChrTalk( 0x0101, ( '#0010150205V#005F好!', TxtCtl.Enter, TxtCtl.Clear, '#0010150206V#005F奸商,\n', '给我等着瞧~~', TxtCtl.Enter, ), ) CloseMessageWindow() def _loc_122D(): pass ...
Python
1
import copy import torch import numpy as np from torch_geometric.data import Data, Batch from torch_geometric.loader import DataLoader FOLLOW_BATCH = ['protein_element', 'ligand_context_element', 'pos_real', 'pos_fake'] class ProteinLigandData(Data): def __init__(self, *args, **kwargs): super().__init_...
Python
1
property::testing::serialization_bijection(b) } } impl Arbitrary for HeaderRaw { fn arbitrary<G: Gen>(g: &mut G) -> Self { let len = u16::arbitrary(g); let mut v = Vec::new(); for _ in 0..len { v.push(u8::arbitrary(g)) ...
Rust
0
assumes that the array contents are stored inline and not on the heap // I think this will always be true but we should check instead // the reason I am not checking is that I don't know how to check yet let path_addr: usize = unsafe { rarray.as_.ary[0] as usize }; // 1 means get th...
Rust
0
atrix of weight constants for this set of weighted densities pub fn weight_constants(&self, k: T, dimensions: usize) -> Array2<T> { let segments = self.component_index.len(); let n_wd = self.n_weighted_densities(dimensions); let mut weight_constants = Array::zeros([n_wd, segments]); ...
Rust
0
import logging from galaxy.model.item_attrs import UsesItemRatings log = logging.getLogger(__name__) class ItemRatings(UsesItemRatings): """Overrides rate_item method since we also allow for comments""" def rate_item(self, trans, user, item, rating, comment=""): """Rate an item. Return type is <ite...
Python
1
ra to jump here unsafe fn fork_ret() -> ! { static mut FIRST: bool = true; // Still holding p->lock from scheduler CPU_MANAGER.my_proc().excl.unlock(); if FIRST { // File system initialization FIRST = false; fs::init(ROOTDEV); } user_trap_ret(); } #[inline] f...
Rust
0
ef create_evaluator( rank: int, env: dict[str, Any], comm: ICommunicator, runtime: RuntimeContext, kind: str | None = "iterative", ) -> IEvaluator: """Factory to create an evaluator engine. Args: rank: Party rank. env: Initial variable environment. comm: Communicator...
Python
1
import numpy as np import matplotlib.pyplot as plt def exercise1(): """ Solution to Exercise 1: Sampling and Frequency Analysis """ # Given parameters T = 0.1 # sampling period in seconds fs = 1 / T # sampling frequency in Hz f_signal = 15 # highest frequency component in Hz N = 100...
Python
1
Vec::with_capacity(capacity as usize); let p = buffer.as_mut_ptr(); mem::forget(buffer); let len = neon_sys::string::data(p, capacity, self.to_raw()); String::from_raw_parts(p, len as usize, capacity as usize) } } pub fn new<'a, T: Scope<'a>>(scope: &mut...
Rust
0
# -*- coding: utf-8 -*- """Tests for `saxo_openapi` package.""" import requests_mock from .unittestsetup import test_generic, ReqMockTest import saxo_openapi.endpoints.portfolio as pf from parameterized import parameterized class TestSaxo_Portfolio_Exposure(ReqMockTest): """Tests for `portfolio-exposure` endpoi...
Python
1
// error // })?; let addr = SocketAddr::from(([0, 0, 0, 0], 4000)); tracing::debug!("Listening on {}", addr); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .map_err(|error| { tracing::error!("[ERROR: {error:?}]"); error ...
Rust
0
} }; Ok(size) } /// Mark a PTE invalid for user access. /// Used by exec for the user stack guard page. pub fn clear(&mut self, va: UVAddr) { self.page_table .get_mut(va, None) .expect("clear") .clear_user(); } /// Copy f...
Rust
0
ed database queries if subnet_division app is enabled. Tests in "openwisp_controller.config" are written assuming subnet_division is disabled. Therefore, it is required to increase the number of expected queries in those tests. """ if exc_type is not None: ret...
Python
1
from .sampler import UniPCSampler # noqa: F401
Python
1
."] #[doc = ""] #[doc = " An invalidate operation is issued that marks the state of each instruction cache block as invalid without writing back modified cache blocks to memory.<br>"] #[doc = " Cache access is blocked during this time. Bus accesses to the cache are signaled as a miss during in...
Rust
0
value.clone(), 2); assert_eq!(x % value.clone(), 0); assert!(value.clone() < <$res>::from(x + 2)); assert!(<$res>::from(x + 2) > value.clone()); assert!(x < <$res>::from(x + 2)); assert!(<$res>::from(x + 2) > x); )*) } test_type!( Nat, usize...
Rust
0
>; pub struct LanaEnv<'a> { pub data: EnvData, pub outer: Option<&'a LanaEnv<'a>>, } impl<'a> LanaEnv<'a> { pub fn default() -> Self { LanaEnv { data: prelude::prelude(), outer: None, } } pub fn get(&self, symbol: &str) -> Option<LanaExpr> { match s...
Rust
0
ed_length(input: &[u8]) -> std::result::Result<Option<i32>, &'static str> { if let Ok((rest, _)) = take_chunked_ctl_chars(input) { if let Ok((trailing_data, chunked_length)) = hex_digits()(rest) { if trailing_data.is_empty() && chunked_length.is_empty() { return Ok(None); ...
Rust
0
Constrain X to be positive semidefinite. fairPCA.add_constraint(X>>0) fairPCA.add_constraint(X<<I) #the following depends on the type of the problems. Here we coded 3 of them: #1) max min variance 2) min max loss 3) Nash social welfare of variance ...
Python
1
MinusEqual, Star, StarEqual, Slash, SlashEqual, // literals Str(String), Char(char), Int(String), Float(String), // identifiers Ident(String), // Keywords // `True` and `False` are considered boolean literals, but will be lexed as // as keywords for simplicit...
Rust
0
class(); if let Some(attr) = objtype::class_get_attr(&cls, attr_name.as_str()) { if let Some(descriptor) = objtype::class_get_attr(&attr.class(), "__delete__") { return vm.invoke(&descriptor, vec![attr, obj.clone()]).map(|_| ()); } } if let Some(ref dict) = obj.dict { d...
Rust
0
import streamlit as st st.title("Fire Protection") st.write("## Question Bank") with st.expander("What allows air to enter and ventilate the nacelle?"): st.write(""" * 2 NACA Ductos, one in the front-top and the other in the front-bottom of the cowlings, therefore they are an important part of the preflight ins...
Python
1
ovement(): global current_room old_room = current_room if keyboard.left: current_room -= 1 if keyboard.right: current_room += 1 if keyboard.up: current_room -= MAP_WIDTH if keyboard.down: current_room += MAP_WIDTH if current_room > 50: current_ro...
Python
1
<GridItem cols=[3]> { Self::render_cards("Integrations", integration_cards) } </GridItem> <GridItem cols=[3]> { if !demo_cards.is_empty() { Self::render_cards("Demos", demo_cards) } else { ...
Rust
0
lf.pool_to_same_tokens(student_logits, teacher_softmax_logits) assert student_logits.size() == teacher_softmax_logits.size(), f'{student_logits.size()} != {teacher_softmax_logits.size()}' # Soften probabilities and compute distillation loss loss_logits = 0 if not (studen...
Python
1
gGroup::Mandarin => { let lang = detect_lang_base_on_mandarin_script(&query, &script_info).lang(); RawLangInfo::Mandarin(lang) } }); RawInfo { script_info, lang_info, } } // Copyright (c) 2021 Quark Container Authors // // Licensed under the A...
Rust
0
_api::markup::Markup, registry: &mut plygui_api::markup::MarkupRegistry) { use plygui_api::markup::MEMBER_TYPE_BUTTON; fill_from_markup_base!(self, member, markup, registry, Button, [MEMBER_TYPE_BUTTON]); fill_from_markup_label!(self, member, markup); fill_from_markup_callbacks!(self...
Rust
0
allow( clippy::wrong_self_convention, clippy::redundant_closure, clippy::redundant_field_names, clippy::match_single_binding )] pub mod secrets_store_capnp; use std::mem::zeroed; use std::ops::{Range, RangeTo, RangeFrom, RangeFull}; use std::os::unix::io::RawFd; use nix::errno::errno; use libc::getrlimit; use ...
Rust
0
# Copyright (c) ASAPP Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import fire import os import sys import time from tqdm.auto import tqdm import re import json from colorama import Fore import numpy as np def get_train_epoch_time...
Python
1
from math import pi import torch from torch import nn from einops import rearrange, repeat from pcdet.utils.spconv_utils import replace_feature def broadcat(tensors, dim=-1): num_tensors = len(tensors) shape_lens = set(list(map(lambda t: len(t.shape), tensors))) assert len(shape_lens) == 1, 'tensors mu...
Python
1
# Creates a channel /// * Gets a valid connection /// * Returns a channel pub async fn create_channel<'a>( addr: &'a str, total_retries: u64, ) -> Result<Channel, GenericError<lapin::Error>> { let conn = get_connection(&addr, 0, total_retries).await?; return match conn.create_channel().await { ...
Rust
0
).await = Some(r); } else { log::warn!("Failed to acquire root resource (already taken)") } } Err(e) => log::warn!("Bad incoming request: {:?}", e), ...
Rust
0
; use iron::prelude::*; use iron::Handler; use iron::status; use serde_json; use api; use core::consensus::reward; use core::core::{build, Block, Output, Transaction, TxKernel}; use core::ser; use keychain::{BlindingFactor, Identifier, Keychain}; use types::*; use util; use util::LOGGER; /// Dummy wrapper for the hex...
Rust
0
import random import requests class Rooms: EXIT = "🍭" GHOST = "👻" START = "🚪" ROOM = "🔳" class Directions: NORTE = "norte" SUR = "sur" ESTE = "este" OESTE = "oeste" PISOS_MANSION = 4 X_INICIO, Y_INICIO = [ random.randint(0, PISOS_MANSION - 1), random.randint(0, PISOS_MA...
Python
1
esponse['version'] == 5 # XXX: is there any feasible way of testing IPv6 source addresses? # Same would go for non-proxy source_address test... def test_ipv4_client_source_address(self, handler, ctx): with ctx.socks_server(Socks5ProxyHandler) as server_address: source_address = f'127.0....
Python
1
performance logits, labels = model.predict(target_data) preds = logits.argmax(dim=1) mi_f1 = eval_micro_f1(labels, preds) ma_f1 = eval_macro_f1(labels, preds) if args.source in {'DE', 'EN', 'ES', 'FR', 'PT', 'RU'}: auc = eval_roc_auc(labels, logits[:, 1]) else: auc = 0.0 results = 'sagda,source,' + args.so...
Python
1
from typing import Any, Dict from .Options import Architect, GoldGainMultiplier, Vendors rl_options_presets: Dict[str, Dict[str, Any]] = { # Example preset using only literal values. "Unknown Fate": { "progression_balancing": "random", "accessibility": "random", "starting...
Python
1
ideoX-5B# # Or Just dont cat and pass it through the norm_final # Then remove the img_feature_cond contribution #hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1) hidden_states = self.norm_final(hidden_states) hidden_states = hidden_stat...
Python
1
BidAsk, TickAttribLast, TickByTickType, TickMsgType, TickType, UNSET_DOUBLE, UNSET_INTEGER, }; use crate::core::contract::{Contract, ContractDescription, ContractPreamble, ContractDetails, DeltaNeutralContract}; use crate::core::errors::IBKRApiLibError; use crate::core::execution::{Execution,ExecutionFilter}; use c...
Rust
0
========= async def apply(chat: 'ch.Chat', llm: 'llm.LLM'): strat = MCTS_STRAT.value strat_params = MCTS_STRAT_PARAMS.value exploration_constant = MCTS_EXPLORATION_CONSTANT.value max_simulations = MCTS_MAX_SIMULATIONS.value max_iterations = MCTS_MAX_ITERATIONS.value thoughts = MCTS_THOUGHTS.value debug_i...
Python
1
import funcao_pytest def test_soma(): assert funcao_pytest.soma(2, 3) == 5 assert funcao_pytest.soma(-1, 1) == 0
Python
1
, [None, 2, 'nearest']], #45 [ -1, ELAN, [128, 32, 64, 4, 2, [-1, -2, -3, -4, -5, -6]]], # 46 [ -1, Conv, [64, 32, 3, 1]], #47 [ -1, Upsample, [None, 2, 'nearest']], #48 [ -1, Conv, [32, 16, 3, 1]], #49 [ -1, ELAN, [16, 4, 8, 4, 2, [-1, -2, -3, -4, -5, -6]]], # 50 [ -1, Upsample, [None, 2, 'nearest']], #51 [...
Python
1
ignal worker"); macro_rules! listen { ($sig:ident) => {{ trace!(kind=%stringify!($sig), "listening for windows process notification"); $sig().map_err(|err| CriticalError::IoError { about: concat!("setting ", stringify!($sig), " signal listener"), err })? }} } let mut sigint = listen!(ctrl_c); let...
Rust
0
") for table in tables: table_currencies = self._parse_html_table(table) if table_currencies: currencies.extend(table_currencies) if currencies: return currencies divs = soup.find_all( "div", class_=lambda x: x and ("rate" in x or...
Python
1
# 这个脚本的作用是把预测结果重新映射回原始 mesh import os from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier import numpy as np import vedo from utils import color2label, label2color_lower lower_palette = np.array( [[125, 125, 125]] + [[label2color_lower[label][2][0], label2color_lower[label][2]...
Python
1
way, I think, so don't bother reflowing. //Add the extra bit to `y` because the current graphics looks better that way. framebuffer.print( spec.text.as_bytes(), spec.x.saturating_add(SPRITE_SIZE), spec.y + (FONT_SIZE / 4), WHITE_INDEX, ); result } //We can r...
Rust
0
orm( grasp_points.expand(num_envs, num_points, 3) - position_local.unsqueeze(1), dim=-1, ) min_dist, min_idx = torch.min(grasp_points_dist, dim=-1) lf_dist = torch.norm(grasp_points[min_idx] - lf_local, dim=-1) rf_dist = torch.norm(grasp_points[min_idx] - rf_local, dim=-1) return m...
Python
1
import asyncio import re from collections.abc import AsyncGenerator, Generator from dataclasses import dataclass from typing import Protocol, TypeVar import logging import numpy as np import torch from numpy.typing import NDArray from fastrtc.utils import async_aggregate_bytes_to_16bit logging.basicConfig(level=logg...
Python
1
" { #[link_name = "cMl::memalignB(i32, u32)"] fn game_memalign(align: isize, size: usize) -> *mut u8; #[link_name = "cMl::free(void*)"] fn game_free(ptr: *mut u8); #[link_name = "strlen"] fn game_strlen(string: *const u8) -> usize; } #[no_mangle] pub extern "C" fn malloc(size: usize) -> *mut u8...
Rust
0
ite(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } } impl AsRawHandle for ChildStdin { fn as_raw_handle(&self) -> RawHandle { self.0.as_raw_handle() } } impl IntoRawHandle for ChildStdin { fn i...
Rust
0
//! See the License for the specific language governing permissions and //! limitations under the License. use std::convert::TryInto; use ir_common::generated::algebra as algebra_pb; use ir_common::KeyId; use pegasus::api::function::{FnResult, MapFunction}; use crate::error::{FnExecError, FnGenResult}; use crate::g...
Rust
0
n_dm = dm.shape[0] ngrids = grids.shape[0] if n_dm == 1: return get_int3c1e_density_contracted(mol, grids, charge_exponents, dm[0], intopt).reshape(1, ngrids) int3c_density_contracted = cp.empty((n_dm, ngrids)) for i_dm in range(n_dm): ...
Python
1
melody = [ # Take on me, by A-ha # Score available at https://musescore.com/user/27103612/scores/4834399 # Arranged by Edward Truong 740, 8, # NOTE_FS5 740, 8, # NOTE_FS5 587, 8, # NOTE_D5 494, 8, # NOTE_B4 0, 8, # REST 494, 8, # NOTE_B4 0, 8, # REST 659, 8...
Python
1
from pydantic import BaseModel, Field, validator from typing import Optional, Dict, Any, List, Union from datetime import datetime import uuid class PrintGenerateRequest(BaseModel): asset_id: uuid.UUID template_id: Union[str, int] # Può essere ID (int) o key (str) del template options: Optional[Dict[str,...
Python
1
import requests import json from concurrent.futures import ThreadPoolExecutor print("共142个接口") print("SethAion制作") print("--------------------------------") phone = input("请输入手机号:") def request_url1(): url1 = "https://miniapps.nj12345.net/wechatsmallprogram/rest/checkcode/getCheckCode" headers1 = { "Ho...
Python
1
if args.display_help { print!("{}", help); std::process::exit(0); } if args.display_version { println!("helix {}", env!("VERSION_AND_GIT_HASH")); std::process::exit(0); } if args.health { if let Err(err) = helix_term::health::print_health(args.health_arg) {...
Rust
0
for line_list in &self.line_lists { let vertex_buffer_first_element = vertex_list.len() as u32; for vertex_pos in &line_list.points { vertex_list.push(Debug3DVertex { pos: (*vertex_pos).into(), color: line_list.color.into(), ...
Rust
0
of `FromIterator`), but /// specialized to tuples of expected length. pub fn into_tuple<B>(self) -> Result<Option<B>> where B: ConstrainedEntsConstraintTuple { let expected = self.spec.expected_CausetIndex_count(); self.results.into_tuple().and_then(|vec| B::from_ConstrainedEnts_vec(expected, v...
Rust
0
en=max_seq_len // 2) train_sampler = DistributedSampler(train_ds) if ddp else None train_loader = DataLoader( train_ds, batch_size=args.batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=args.num_workers, sampler=train_sampler ) ...
Python
1
UINT32, pub algorithm: TPM_KEY_PARMS, pub credential: *mut BYTE, } #[test] fn bindgen_test_layout_tdTPM_SYM_CA_ATTESTATION() { assert_eq!(::std::mem::size_of::<tdTPM_SYM_CA_ATTESTATION>() , 40usize , concat ! ( "Size of: " , stringify ! ( tdTPM_SYM_CA_ATTESTATION ) )); ass...
Rust
0
builder(); path_builder.move_to(point(50., 50.)); path_builder.line_to(point(100., 150.)); path_builder.line_to(point(150., 50.)); path_builder.close(); let path = path_builder.build(); builder .stroke(&path, &StrokeOptions::default()) .expect("Err...
Rust
0
<Expr>) -> Expr { if exprs.iter().any(|expr| matches!(**expr, ExprX::Const(Constant::Bool(false)))) { return mk_false(); } let exprs: Vec<Expr> = exprs .iter() .filter(|expr| !matches!(***expr, ExprX::Const(Constant::Bool(true)))) .cloned() .collect(); if exprs.le...
Rust
0
shop_msg1 = f"道友上架的{shop_goods_name}已被购买,获得灵石{give_stone}枚,坊市收取手续费:{service_charge}枚灵石!" shop_msg2 = Message(f"[CQ:at,qq={shop_user_id}]") sql_message.update_ls(shop_user_id, give_stone, 1) del shop_data[group_id][str(arg)] try: if X...
Python
1
&format!("{}-{}", opek.get_name(), opek.get_revision()), &opek.get_body(), ], ).map_err(SrvError::OriginPublicEncryptionKeyCreate)?; match rows.iter().nth(0) { Some(row) => Ok(self.row_to_origin_public_encryption_key(row)), None => Err(SrvEr...
Rust
0
ns::{HashMap, HashSet}; use std::fmt; use std::fmt::{Display, Formatter}; // Boxed types used for storing information from the parsing will be used especially for the // location of the AST item #[doc(hidden)] pub type AstExpr = Box<Spanned<Expr>>; #[doc(hidden)] pub type AstArgument = Spanned<Argument>; #[doc(hidden)...
Rust
0
name for the error that is going to be returned in case we are in the grace /// period. const RECENTLY_SENT: () = (); // Start off by creating a reference to Local Storage value. // Since the local storage is common for all offchain workers, it's a good practice // to prepend your entry with the module ...
Rust
0
""" Generated by Eclipse Cyclone DDS idlc Python Backend Cyclone DDS IDL version: v0.11.0 Module: nav_msgs.msg.dds_ IDL file: MapMetaData_.idl """ from enum import auto from typing import TYPE_CHECKING, Optional from dataclasses import dataclass import cyclonedds.idl as idl import cyclonedds.idl.annotations ...
Python
1
2); //! }); //! ``` //! //! #### Encrypting //! //! ``` //! use bip38::{Encrypt, EncryptWif}; //! //! let informed_wif_key = "<KEY>"; //! let internal_prv_key = [0xd0; 32]; //! let user_pass = String::from("<PASSWORD>"); //! //! let eprvk_from_raw = internal_prv_key.encrypt(&user_pass, true).unwrap_or_else(|err| { //! ...
Rust
0
e a public key associated with the given auth token let public_key_option = get_public_key_for_auth_token(auth_token, pool)?; let public_key = public_key_option.ok_or_else(|| warp::reject::custom(Error::NoAuthToken))?; // Check that the given public key isn't banned if is_banned(&public_key, pool)? { ...
Rust
0
# ----------------------------------------------------------------------------- # Problem: Assign Cookies # ----------------------------------------------------------------------------- # # @question: # You are given two integer arrays: # - `greed[i]`: the minimum size of a cookie each child needs. # - `cookies[j]`: th...
Python
1
ult<(String, BTreeSet<String>), ESIError> { if let Some(record) = sqlx::query!( "SELECT * FROM access_token WHERE character_id=?", character_id ) .fetch_optional(self.db.as_ref()) .await? { if record.expires >= chrono::Utc::now().timestamp() { ...
Rust
0
import time import RPi.GPIO as GPIO import spidev GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) spi = spidev.SpiDev() spi.open(0,0) spi.max_speed_hz=5000 def ReadChannel(channel): adc = spi.xfer2([1,(8+channel)<<4,0]) data = ((adc[1]&3) << 8) + adc[2] return data # Function to convert data to voltage level,...
Python
1
error is raised if sky_area has no units sky_area = 1 with pytest.raises(TypeError): redshifts_from_comoving_density(redshift, density, sky_area, cosmo, noise=False) @pytest.mark.flaky def test_smail(): from skypy.galaxies.redshift import smail # sample a single redshift rvs = smail(1.3, ...
Python
1
} | distance {round(self.robot_info.robot_p, 5)}") # respond response = TriggerResponse() response.success = True response.message = f"{self.robot_name} want to enter conflict zone" return response def kinematic_info_cb(self, kinematic_data_msg: KinematicDataArray): ...
Python
1
(); let namespace_cache = writer.as_reader(); let namespace_reflector = try_flatten_applied(reflector(writer, namespace_watcher)).try_for_each(ok); // ObjectSync controller let configuration = Configuration::new(client); let controller = ObjectSyncController::new(configuration, namespace_cac...
Rust
0
ons and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Novartis Institutes for BioMedical Research Inc. # nor the names of its contributors may be used to endorse or promote # products derived from this softwar...
Python
1
itive}; use crate::{ bytesrepr::{Error, FromBytes, ToBytes}, CLType, CLTyped, }; /// The number of bytes in a serialized [`Phase`]. pub const PHASE_SERIALIZED_LENGTH: usize = 1; /// The phase in which a given contract is executing. #[derive(Debug, PartialEq, Eq, Clone, Copy, FromPrimitive, ToPrimitive)] #[re...
Rust
0
import torch class ClipGrad: def __init__(self, clip_type="None", clip_value=0.1, max_norm=35, norm_type=2): self.clip_type = clip_type self.clip_value = clip_value self.max_norm = max_norm self.norm_type = norm_type def __call__(self, model): if self.clip_type == 'val...
Python
1
Type::SequentialAccess, 2 => PeripheralDeviceType::Printer, 3 => PeripheralDeviceType::Processor, 4 => PeripheralDeviceType::WriteOnce, 5 => PeripheralDeviceType::CdDvd, 6 => PeripheralDeviceType::Obsolete, 7 => PeripheralDeviceType::OpticalMemory, 8 => Peripheral...
Rust
0
config() -> WindowConfig { WindowConfig { has_canvas: true, canvas_width: CANVAS_WIDTH as u32, canvas_height: CANVAS_HEIGHT as u32, canvas_color_letterbox: Color::black(), windowed_mode_allow: true, windowed_mode_allow_resizing: true, ...
Rust
0
Users\DoubleZeroWater\.cache\huggingface\datasets\glue\sst2") model_name = "distilbert-base-uncased-finetuned-sst-2-english" tokenizer = AutoTokenizer.from_pretrained(model_name) train_dataset = Dataset_java_huggingface(dataset, "train", tokenizer, 256) test_dataset = Dataset_java_huggingface(dataset, "...
Python
1
assignment_error(): df["a"].fillna(100, inplace=True) tm.assert_frame_equal(df, df_orig) with tm.raises_chained_assignment_error(): df[["a"]].fillna(100, inplace=True) tm.assert_frame_equal(df, df_orig) else: with tm.assert_produces_warning(None): ...
Python
1
e unless the timer got above this number #[cfg(feature = "timing")] impl Timer { pub fn new(name: &'static str) -> Timer { Timer { name, start: Instant::now(), } } pub fn stop(self) { let end = Instant::now(); let dur = end - self.start; let...
Rust
0
from . import loadDefaultParams as dp from . import timeIntegration as ti from ..model import Model class WWModel(Model): """ Wong-Wang model. Original version and reduced version. Main reference: [original] Wong, K. F., & Wang, X. J. (2006). A recurrent network mechanism of time integrat...
Python
1
# -*- coding: utf-8 -*- # Copyright 2025 Google LLC # # 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 applicable law or...
Python
1
t_search_total_count, PostgresWallet::fetch_search_next_record, PostgresWallet::free_search, ) } #[no_mangle] pub extern fn init_storagetype(config: *const c_char, credentials: *const c_char) -> libindy::ErrorCode { return PostgresWallet::init(config, credentials); } struct PostgresStorageCont...
Rust
0
# The MIT License (MIT) # # Copyright (c) 2020 Huimao Chen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modif...
Python
1
#!/usr/bin/env python3 """ Script de teste para verificar o sistema de upload OneDrive """ import sys import os from pathlib import Path # Adiciona o diretorio raiz ao path sys.path.insert(0, str(Path(__file__).parent)) from src.upload_onedrive import sincronizar_historico_uploads, validar_configuracao_onedrive def...
Python
1
= [self._adb, 'shell', 'dumpsys', 'input_method'] check_str = 'mInteractive=true' if self._is_art else 'mScreenOn=true' output, err, code = cexec(commands, callback=None) return re.search(check_str, output) def _turn_on_screen(self): commands = [self._adb, 'shell', 'input', 'keyeve...
Python
1