text
string
label_name
string
labels
int64
return Err(ParseError::Month("Invalid month number", 2, 4)); } let year = date % 100 + from_separator(&separator)?; let days_in_month = days_in_month(month, year); let day = date / 10_000; if day < 1 || day > days_in_month { return Err(ParseError::Day("I...
Rust
0
v2 的输入梯度或者 conv2 层输出梯度) # 这里我们利用 model.feature_map 已保存 conv2 层输出 # 注意:由于我们没有注册 hook 获取梯度,这里简单地对 image 求梯度也可作为示例 grad_norm = image.grad.data.norm(2).item() return grad_norm def detect_poisoned_sample(model: nn.Module, image: torch.Tensor, device: torch.device, threshold: float) -> bool: """ 对输入图...
Python
1
''' Created on ١١‏/٠٥‏/٢٠١٠ @Created by: Muhammad Altabba ''' from ...Models.Lexicon.RootsAndPatternsRepository import *; from ...Models.Lexicon.LettersConstants import *; from ...Models.Lexicon.LettersConstants import *; from ...Models.Tagging.POSTags.CliticlessPOS import *; from ...Models.Tagging.POSTags.NominalPOS ...
Python
1
om, &self.heap) { Ordering::Less => continue, Ordering::Equal | Ordering::Greater => { index = i; break; } } } indices.push(index); if node.level == 0 { ...
Rust
0
evaluate_end(&self) { let n_selected = self.selected_set.lock_ref().len(); let n_target = { match self.game.base.settings.next { Next::SelectAll => Some(self.traces.len()), Next::SelectSome(n) => Some(n), Next::Continue => None } ...
Rust
0
class Solution: def kthCharacter(self, k: int) -> str: word = "a" while len(word) < k: tmp = "" for ch in word: tmp += chr(ord(ch) + 1) word += tmp return word[k - 1]
Python
1
ive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ethtool_gstrings { pub cmd: u32, pub string_set: u32, pub len: u32, pub data: [u8; 0], } impl Default for ethtool_gstrings { fn default() -> Self { unsafe { zeroed() } } } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialO...
Rust
0
pm.addContextHelp("Logical NOT") return pm.getBlock() #---------------------------------------------------------------------- def not_b(self): pm = Block.OutputBool("Math") pm.addDecorator("NOT") pm.addSyntax("!") pm.addSpaceBool() pm.addContextHelp("L...
Python
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # #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 l...
Python
1
e, viewport, ox + rr, oy + rr, f); } } } #[cfg(test)] pub fn debug_root(&self) -> Vec<u128> { self.debug(self.root) } #[cfg(test)] pub(crate) fn debug(&self, node: NodeId) -> Vec<u128> { use itertools::Itertools; match node_ref(node) { Node::Leaf(LeafNode { key, .. }) => { ...
Rust
0
, pub results: Vec<EvictStaleItem>, } impl From<Result<Vec<EvictStaleItem>, ServiceError>> for EvictStaleResult { fn from(result: Result<Vec<EvictStaleItem>, ServiceError>) -> Self { match result { Ok(results) => Self { success: true, error: "".to_string(), ...
Rust
0
hreadpool // doesn't allow creating dynamically), with very shallow stacks // (say 1MB) // c) keep adding work while the P95? P80? of completion stays the same // when pNN starts to increase either (i) we've saturated the system // or (ii) other work coming in has saturated the system or (iii) this // so...
Rust
0
from models import db class Character(db.Model): __tablename__ = 'characters' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30),nullable=False,unique = True) age = db.Column(db.Integer) race_id = db.Column(db.Integer,db.ForeignKey('races.id')) city_id = db.Column(db.In...
Python
1
tempt', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ocr_result', models.JSONField(blank=True, default=dict)), ('forgery_result', models.JSONField(blank=True, default=dict)), (...
Python
1
\x89\ \xfah\x85\xfa\x97l\x89IVDD:5\x87b{\ 1%\xc0\xccOY\xab\x15;R\xda\x1a\xfb\x0a\xf68\ \x9e\x19\x8f^\xb4c\xf3}]s&]I\x93\xccp\ \xed\x96y\xae\xa9\x96\x7f{\xf7\xeeKF\xcb}\xc0O\ q\xe2\xb0\xb7`\x06\xea\xcb\xf1\xd3V\xf2\x99\x07*g\ 5JTb\x9br\xbe/\x96nuk`\x84\xdb\x08\ ;Iz\xbc_\xaa\xd20J:\xaf=\xe7\x89\x8aY\ $\x00\xe6r\xd5 \x82\...
Python
1
is list. reduced_exprs : list of sympy expressions The reduced expressions with all of the replacements above. """ from sympy.matrices import Matrix # Handle the case if just one expression was passed. if isinstance(exprs, Basic): exprs = [exprs] if optimizations is Non...
Python
1
from django.db import models import urllib # Create your models here. class Photo(models.Model): photoId = models.AutoField(primary_key=True) # 照片id userName = models.CharField(max_length=255) # 用户名 takenDate = models.CharField(max_length=255, null=True) # 拍摄日期 ...
Python
1
success() && response.status().as_u16() != 200 { crate::operation_deser::parse_untag_resource_error(response) } else { crate::operation_deser::parse_untag_resource_response(response) } } } <gh_stars>1-10 use crate::vec2d::Vec2D; use std::collections::VecDeque; use fastrand::R...
Rust
0
a.dashboard.v1.GlobalDashboardConfigService/GetAllBatched": grpclib.const.Handler( self.__rpc_get_all_batched, grpclib.const.Cardinality.UNARY_STREAM, GlobalDashboardConfigBatchedStreamRequest, GlobalDashboardConfigBatchedStreamResponse, ), ...
Python
1
# -*- coding: utf-8 -*- # # conncomp.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 # ...
Python
1
docker_command(&["stop", "mimirsbrunn_fafnir_tests"]); docker_command(&["rm", "mimirsbrunn_fafnir_tests"]); } } //! Day 5: //! This solution process highlighted two things. First, branching logic can //! be expensive. My original solution to part 1 was 3x slower than the //! solution to part 2, but the on...
Rust
0
(x, y, alternative='greater') print('RF6 p-value: ', p_value) for i in range(6): x = plot_data_TMB[i*2] y = plot_data_TMB[i*2+1] statistic, p_value = mannwhitneyu(x, y, alternative='greater') print('TMB p-value: ', p_value) ################ violin & box plot for scores d...
Python
1
| { barrier2.wait(); awakener2.wake().expect("unable to wake"); }); // Receive the event from thread 1. expect_events(&mut os_queue, &mut events, vec![ Event::new(event_id, Ready::READABLE), ]); // Unblock thread 2. barrier.wait(); // Now we need to receive another...
Rust
0
s(rotation=45) plt.tight_layout() plt.show() def save_model(model, vectorizer, filename='spam_detector.joblib'): """Save the trained model and vectorizer""" joblib.dump({'model': model, 'vectorizer': vectorizer}, filename) print(f"\nModel saved as {filename}") def interactive_predict(model, vec...
Python
1
from fastapi import FastAPI, HTTPException from fastapi.encoders import jsonable_encoder from models import Item from data import items app = FastAPI() @app.get("/") def index () -> dict[str, dict[int, Item]]: return {"items": items} @app.get("/items/{item_id}") def get_item_by_id(item_id: int) -> Item: if ...
Python
1
# -*- coding: utf-8 -*- # This code is part of Amoco # Copyright (C) 2017 Axel Tillequin (bdcht3@gmail.com) # published under GPLv2 license # import expressions: from amoco.cas.expressions import reg, cst, is_reg_pc, is_reg_stack from amoco.cas.expressions import * # noqa: F403 # reference documentations: # The RIS...
Python
1
class Car: model = "alto" color = "white" car = Car() print(car.model) print(car.color)
Python
1
e3_adv = parameter_dict['scale3_adv'] print('scale3_benign: {}'.format(scale3_benign)) print('scale3_adv: {}'.format(scale3_adv)) perturbFM = parameter_dict['perturbFM'] # print('perturbFM: {}'.format(perturbFM)) dt = datetime.now().strftime("%y%m%d%H%M%S") # change this path checkpoint_path = '/ck...
Python
1
ate IDs must be in the format <id_type>:<id>", alternate_id )), )); } let split: Vec<&str> = alternate_id.split(':').collect(); let id_type = split[0]; let id = split[1]; let mut query = purchase_order_alternate_id::table.into_boxe...
Rust
0
pub copper_tier: CopperTier, // else tin pub iron_tier: IronTier, // else lead pub silver_tier: SilverTier, // else tungsten pub gold_tier: GoldTier, // else platinum pub cobalt_tier: CobaltTier, // else pub mythril_tier: MythrilTier, // else orichalcum pub adamantite_tier: AdamantiteTier, // else titanium } im...
Rust
0
1 = 0 if x1 is None else x1 x2 = 0 if x2 is None else x2 x3 = 0 if x3 is None else x3 y1 = 0 if y1 is None else y1 y2 = 0 if y2 is None else y2 y3 = 0 if y3 is None else y3 try: draw = ImageDraw.Draw(img) draw.line(((int(tdx), int(tdy)), (int(x1),int(y1))), fill=(0, 0, 255), widt...
Python
1
import numpy as np import ctypes import os import cv2 # so_path = os.path.join(os.path.dirname(__file__), 'libtest.so') # lib = ctypes.cdll.LoadLibrary(so_path) # c_float_p = ctypes.POINTER(ctypes.c_float) def extract_points(image): image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) data_p = image.astype(np.fl...
Python
1
you like to open the Fabric wiki to find out how to fix this?\n\nURL: https://fabricmc.net/wiki/player:tutorials:java:windows"; const REG_HIVE: HKEY = HKEY_CURRENT_USER; const REG_PATH: &str = r"SOFTWARE\Mojang\InstalledProducts\Minecraft Launcher"; const REG_KEY: &str = "InstallLocation"; // This appears to be the ...
Rust
0
, 0.07428705012229142, 0.06163502514254733, 0.04804839908118027, 0.033732303685955825, 0.018896858024263503, 0.003076923076923039, ]; let points = vec![ [-1.0], [-0.9887274123114755], [-0.9623778747677165], [-0.921435546817557], ...
Rust
0
for W { #[inline(always)] fn from(writer: crate::W<SC1_SPEC>) -> Self { W(writer) } } #[doc = "Input channel select\n\nValue on reset: 31"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum ADCH_A { #[doc = "0: External channel 0 is selected as input."] ADCH_0 = 0, #[doc = "1...
Rust
0
import sys import os import casadi.casadi as cs import opengen as og optimizers_dir = "my_optimizers" optimizer_name = "rosenbrock" def get_open_local_absolute_path(): cwd = os.getcwd() return cwd.split('open-codegen')[0] nu, np = 5, 2 u = cs.SX.sym("u", nu) # decision variable (nu = 5) p = cs.SX.sym("p"...
Python
1
# -*- coding: utf-8 -*- # # Copyright 2020 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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 y...
Python
1
types and functions. pub mod bitopts; pub mod registers; pub mod static_ref; /// Descriptive name for each register. pub trait RegisterLongName {} impl RegisterLongName for () {} /// Conversion of raw register value into enumerated values member. /// Implemented inside register_bitfields! macro for each bit fiel...
Rust
0
), // ssh_key: None, // }, // config.bcrypt_cost, // &conn, // ) { // eprintln!("Error creating user {:?}", e); // break; // } // } // // Ok(rocket) // } // // async fn seed_clients( // rocket: Rocket<Ignite>, // amount: usize, // ) -> std::result::Result<Rocket<Ignite>, Rocket<Ignite>> { // let conn = DbConn::get_on...
Rust
0
/// The reasons (in terms of [`UserInput`]) that the button was pressed /// /// If the button is currently released, the `Vec<UserInput`> returned will be empty /// /// # Example /// /// ```rust /// use leafwing_input_manager::prelude::*; /// use leafwing_input_manager::buttonlike::...
Rust
0
super::AtomicLock; use crate::platform::{types::*, Pal, Sys}; use core::sync::atomic::Ordering; pub struct Semaphore { lock: AtomicLock, } impl Semaphore { pub const fn new(value: c_int) -> Self { Self { lock: AtomicLock::new(value), } } pub fn post(&self) { self.l...
Rust
0
h).map_err(Error::FileStorage)?; storage.remove(identifier).map_err(Error::Remove) } /// Retrieves the data from the specified location denoted by (scope, domain, identifier). pub fn retrieve(scope: Scope, domain: &str, identifier: &str) -> Result<Vec<u8>> { let path = get_storage_path(scope, domain)?; if ...
Rust
0
U: Borrow<Vec3>, { let vector = vector.borrow(); let normal = normal.borrow(); let vector = normalize(vector); let dt = dot(&vector, normal); let discriminant = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt); if discriminant > 0.0 { let refracted = (vector - normal * dt) * ni_over_...
Rust
0
import time import functools def timing_decorator(operation_name): """ Decorator to measure execution time and maintain running averages. """ def decorator(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): start_time = time.time() res...
Python
1
'w') as f: f.write(yaml.dump(results, Dumper=LutfDumper, indent=2, sort_keys=False)) else: print(yaml.dump(results, Dumper=LutfDumper, indent=2, sort_keys=False)) def setup_paths(): global lutf_tmp_dir base_lustre = '' for p in LUTF_SCRIPT_PATHS: path = os.path.join(clutf_global.get_lutf_path(),p) ...
Python
1
import torch import torch.nn as nn import torch.utils.data import torch.nn.functional as F class Net(nn.Module): # 新建一个网络类,就是需要搭建的网络,必须继承PyTorch的nn.Module父类 def __init__(self): # 构造函数,用于设定网络层 super(Net, self).__init__() ...
Python
1
.sun_path[..provided_len] }; Ok(SocketAddrAny::Unix( SocketAddrUnix::new(path_bytes.iter().map(|c| *c as u8).collect::<Vec<u8>>()) .unwrap(), )) } } _ => Err(io::Error::INVAL), } } pub(crate) un...
Rust
0
elf.point_lits.len() { let names = &self.point_lits[point_index]; let mut pos = view_matrix * lit.transform.position.extend(1.0); pos /= pos.w; let attenuation = Vector3::new( ...
Rust
0
else: # AI决定模式:不给出具体页数限制,让AI自行判断 page_count_instruction = "- 页数要求:请根据主题内容的复杂度、深度和逻辑结构,自主决定最合适的页数,确保内容充实且逻辑清晰" expected_page_count = {"mode": "ai_decide"} logger.info("AI decide mode set for page count") # 使用字符串拼接避免f-string中的花括号冲突 ...
Python
1
ib types, the input /// arguments converted *from* Glib types, and so on. pub struct FnSig<'ast> { pub name: Ident, pub inputs: Vec<FnArg<'ast>>, pub output: Ty<'ast>, } pub enum FnArg<'ast> { SelfRef(Token!(&), Token!(self)), Arg { mutbl: Option<Token![mut]>, name: Ident, t...
Rust
0
_SET_B, #[doc = "dout_oem1 (1-bit mode)"] DOUT_OEM1_1_BIT_MOD, #[doc = "dout_oem2 (2-bit mode)"] DOUT_OEM2_2_BIT_MOD, #[doc = "dout_oem4 (4-bit mode)"] DOUT_OEM4_4_BIT_MOD, #[doc = "dout_oem8 (8-bit mode)"] DOUT_OEM8_8_BIT_MOD, #[doc = r" Reserved"] _Reserved(u8), } impl P_OE_CFG...
Rust
0
t_num[index]) print("") index = index + 1 exit_menu() def exit(): print("") print(" Thanks for visiting") print(" Goodbye") def exit_menu(): print("") print("Do you want to exit the program or return to...
Python
1
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-present Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the F...
Python
1
uation); (i, Token::OperatorIdentifier(self.slice(i, e)), e) } /// consume a string literal fn dquote( &mut self, i: ByteIndex, ) -> Result<(ByteIndex, Token<'text>, ByteIndex), SyntaxError> { let e = self.consume_delimited(|c| c != '"')?; self.bump(); Ok...
Rust
0
er) # Generate evolved character image print("Generating evolved character image...") images_evolved2, output_evolved2 = image_generator.generate_images( attributes=evolved_character2, num_samples=1 ) # Save images image_paths_evolved2 = image_generator.save_images( ...
Python
1
allowed. pub fn enter(&mut self) { unsafe { v8__Isolate__Enter(self) } } /// Exits this isolate by restoring the previously entered one in the /// current thread. The isolate may still stay the same, if it was /// entered more than once. /// /// Requires: self == Isolate::GetCurrent(). pub fn exit...
Rust
0
tts: Some("scenske umetnosti"), keywords: &[ "gledališče", "maska", "nastopanje", "scenske umetnosti", "umetnost", ], }, #[cfg(feature = "so")] crate::Annotation { lang: "so", ...
Rust
0
erate_examples(self, filepath): with open(filepath, encoding="utf-8") as f: data = json.load(f) count=0 for id_, conversation in enumerate(data): name, messages = conversation['name'], conversation["messages"] contents=[] for c...
Python
1
return False jsonl_files_with_seed = [ f"task_1_{seed_value}_vanilla.jsonl", f"task_1_{seed_value}_crafted.jsonl", f"task_2_{seed_value}_vanilla.jsonl", f"task_2_{seed_value}_crafted.jsonl", ] for file in jsonl_files_with_seed: file_path = os.path.join(mp2_dir, fi...
Python
1
t fe = match ctx.get_fd_entry(fd, rights.into(), 0) { Ok(fe) => fe, Err(e) => return enc_errno(e), }; let mut iovs: Vec<IoVec<&mut [u8]>> = iovs .iter_mut() .map(|iov| unsafe { host::iovec_to_nix_mut(iov) }) .collect(); let host_nread = match readv(fe.fd_object.rawf...
Rust
0
f = open('17_5.txt') a = [int(i) for i in f] s = 0 mx = 0 for i in range(len(a) - 1): for j in range(i + 1, len(a)): if (a[j] + a[i]) % 2 == 1 and (a[j] * a[i]) % 5 == 0: s += 1 mx = max(mx, a[i] + a[j]) print(s, mx)
Python
1
; inner.extra = Some(Uuid::new_v4().to_string()); RTDChatActionRecordingVideoNoteBuilder { inner } } } #[doc(hidden)] pub struct RTDChatActionRecordingVideoNoteBuilder { inner: ChatActionRecordingVideoNote } impl RTDChatActionRecordingVideoNoteBuilder { pub fn build(&self) -> ChatActionRecordingVideoNo...
Rust
0
{ if *all { Value::String { val: re.replace_all(val, replacement).to_string(), span: head, } } else { Value::String { val: ...
Rust
0
import os,sys import platform if 'Windows' in platform.platform(): PATH = "\\".join( os.path.abspath(__file__).split('\\')[:-1]) else: PATH = "/".join( os.path.abspath(__file__).split('/')[:-1]) sys.path.append(PATH) sys.path.append(PATH) #-------------------------- set gpu using tf ---------------------------...
Python
1
# This file is not meant for public use and will be removed in SciPy v2.0.0. # Use the `scipy.sparse` namespace for importing the functions # included below. import warnings from . import _base __all__ = [ # noqa: F822 'MAXPRINT', 'SparseEfficiencyWarning', 'SparseFormatWarning', 'SparseWarning', ...
Python
1
let mut acked_indexes = HashMap::new(); acked_indexes.insert("a".to_owned(), 100); advance_and_receive_sealed(&mut rep, acked_indexes); assert!(matches!(rep.learning_state, LearningState::Learning { .. })); let (_, learns) = rep.broadcast(); assert!(!learns.is_empty()); ...
Rust
0
""" Вариант 5 Дан файл в формате csv. (Фамилия, Имя, Учреждение (организация), Отдел, Адрес электронной почты, Состояние, Тест начат, Завершено, Затраченное время, Оценка/100,00, В.1 /10,00, В.2 /10,00, В.3 /10,00, В.4 /10,00, В.5 /10,00, В.6 /10,00, В.7 /10,00, В.8 /10,00, В.9 /10,00, В.10 /10,00). Примечание: Тест сч...
Python
1
frutas = ('laranja', 'banana', 'maça', 'uva', 'goiaba') indice_laranja = frutas.index('laranja') indice_banana = frutas.index('banana') print('Indice da laranja', indice_laranja) print('Indice da banaa', indice_banana) # qtd_banana = frutas.count('banana') # print('Quantidade de bananas', qtd_banana) # laranja, banana...
Python
1
f self.split == DatasetSplit.TRAIN else 1000 def _validate_data(self) -> bool: if not self.csv_asset.path().exists(): return False videos_folder = self.videos_asset.path().parent if not videos_folder.exists(): return False self.mp4_files, self.label_indices...
Python
1
import sys # This program prints Hello, world! And the version of Python we have. The print function automatically adds a newline character at the end print('Hello, world!') print(sys.version) # If an if statement or anything that involves you to indent doesn't have an indentation on the next line, # python will n...
Python
1
ormer(replace_infinite)), ( "column_transformer", make_column_transformer( ( KNNImputer(n_neighbors=3), make_column_selector(dtype_include=[np.number]), ), ( SimpleImputer(strateg...
Python
1
Clone, PartialEq)] pub enum ButtonType { WaterGun, AcidTower, SodaMaker, Upgrade, Delete, Other, } <filename>src/widget.rs<gh_stars>0 use button; use drop_down_list; use envelope_editor; use number_dialer; use slider; use text_box; use toggle; use xy_pad; /// Represents the placement of the w...
Rust
0
# # This file originates from # https://github.com/princeton-vl/Coupled-Iterative-Refinement/tree/c50df7816714007c7f2f5188995807b3b396ad3d, licensed # under the MIT license (see CIR-LICENSE in the root folder of this repository). # import torch import torch.nn.functional as F def _bilinear_sampler(img, coords, mask=F...
Python
1
>8} ${:02X} = {:02X}", address, mnemonic, address, operand) } fn format_zero_page_x(data: &Data, mnemonic: &str) -> String { let address = data.opcode_data[0]; let effective_address = data.opcode_data[1]; let operand = data.opcode_data[2]; format!("{:02X}{:>8} ${:02X},X @ {:02X} = {:02X}", address, mnemonic, addre...
Rust
0
print('=== Fails on locale-sensitive match', t) # Try the match with the search area limited to the extent # of the match and see if it still succeeds. \B will # break (because it won't match at the end or start of a # string)...
Python
1
= stack .pop() .ok_or_else(|| VMError::StackUnderflow("Failed to get entity".to_owned()))?; let ent = match ent { Entity::Str(str_entity) => str_entity, _ => { return Err(VMError::TypeMismatch { expected: RuntimeTypeInfo::Str, actual: ent...
Rust
0
import _plotly_utils.basevalidators class TickformatstopsValidator(_plotly_utils.basevalidators.CompoundArrayValidator): def __init__( self, plotly_name="tickformatstops", parent_name="scatter3d.marker.colorbar", **kwargs, ): super(TickformatstopsValidator, self).__init...
Python
1
(|x| x.into_iter()) { result.push(element); } assert_eq!(result, vector); } } <filename>src/cursor.rs use std::{marker::PhantomData, ops}; use crate::{Index, PendingRef, Pointer, PointerData, StorageId, StorageInner}; /// A slice of a storage. Useful for cursor iteration. #[derive(Deb...
Rust
0
reserved_obj_sz = &self.reserved_obj_sz; let alloc_obj_sz; let stack_impl; unsafe { let cell = & *self.cell.get(); stack_impl = &cell.0; alloc_obj_sz = &cell.1; } write!(f, "{{stack = {:#?}, alloc_obj_sz = {:#?}, reserved_obj_sz = {:#?}}}",...
Rust
0
ts, 16), ), |c| char::from_u32(c).map(String::from).map(Cow::Owned), ), )), ); let string_char = alt((normal, escape_sequence)); delimited(char('"'), many0(string_char), char('"')) .map(|strs| Ast::String(strs.concat())) .parse(input) } f...
Rust
0
tables_rf_parameters_upstream` - An ElementRef that holds the table. /// /// # Returns /// * `Vec<UpstreamParameter>` pub fn parse_tables_rf_parameters_upstream_table( tables_rf_parameters_upstream: scraper::ElementRef, ) -> Vec<UpstreamParameter> { let tr_selector = scraper::Selector::parse("tr").unwrap(); ...
Rust
0
if use_warnmsg is None: self._orig_show(message, category, filename, lineno, *args, **kwargs) else: self._orig_showmsg(use_warnmsg) def __call__(self, func): """ Function decorator to apply certain suppressions to a whole function...
Python
1
against the patterns defined by the macro. for (pattern, body) in &self.rules { // todo we need to cross the template too. //let body_pat = Pattern::new(&self.ellipsis, &self.literals, datum); match pattern.cross(&self.ellipsis, datum) { Some(x) => { ...
Rust
0
(40) DEFAULT 'Luso Films', did int DEFAULT nextval('distributors_serial'), stamp timestamp DEFAULT now() NOT NULL, stamptz timestamp with time zone, time time NOT NULL, timetz time with time zone, CONSTRAINT name_len PRIMARY KEY (name, len))", "CREATE TABLE types (a real, b double precision, c numeric(2, 3), d ...
Rust
0
""" Python bindings for the ggml library. Usage example: from ggml import lib, ffi from ggml.utils import init, copy, numpy import numpy as np ctx = init(mem_size=10*1024*1024) n = 1024 n_threads = 4 a = lib.ggml_new_tensor_1d(ctx, lib.GGML_TYPE_Q5_K, n) b = lib.g...
Python
1
legend_ids.dropdown_dim_1, 5.0f64) .w(BUTTON_WIDTH) .h(BUTTON_HEIGHT - 2f64) .set(legend_ids.back_button, &mut ui) { event_queue.push(UIEvents::SetExplanationMode(ExplanationMode::DaSilva( DaSilvaType::Euclidean, ...
Rust
0
'Position': df['Position'].to_list() } df_mapped = pd.DataFrame(mapped_data) # to exculde any tracked pbject outside the pitch df_mapped = df_mapped[(df_mapped['X'] >= 0) & (df_mapped['X'] <= 1050)] df_mapped = df_mapped[(df_mapped['Y'] >= 0) & (df_mapped['Y'] <= 680)] ...
Python
1
:TreeId; } impl<T: Config<I>, I: 'static> VAnchorInterface<VAnchorConfigration<T, I>> for Pallet<T, I> { fn create( creator: Option<T::AccountId>, depth: u8, max_edges: u32, asset: CurrencyIdOf<T, I>, ) -> Result<T::TreeId, DispatchError> { let id = T::LinkableTree::create(creator.clone(), max_edges, depth...
Rust
0
observation_spec = BoundedTensorSpec((1, ), torch.int32, -10, 10) env = RandomAlfEnvironment(observation_spec, action_spec, render_size=(4, 4, 3)) env.reset() img = env.render() self.assertTrue(np.all(img < 256...
Python
1
ressure_ratio; let inner_radius = min( max(last_pressure_radius as u16, ground_radius as u16 + 1), surround_radius as u16 + HEARTBEAT_INNER_MAX_OVERFLOW, ) as f64; let inner_color = if last_pressure_radius >= surround_radius { INNER_CIRCLE_COLOR_OVERFLOW } else { INNER_...
Rust
0
#!/usr/bin/env python3 import queue import sys size = 70 + 1 n = 1024 # size = 6 + 1 # n = 12 start = 0, 0 end = size - 1, size - 1 walls = [] lines = sys.stdin.read().splitlines() for l in lines: x, y = [int(x) for x in l.split(",")] walls.append((y, x)) def bfs(walls): walls_set = set(walls) q = q...
Python
1
false, false, false, false], TileType::Tile02 => [true, false, true, false, false, false], TileType::Tile03 => [true, false, false, true, false, false], TileType::Tile012 => [true, true, true, false, false, false], TileType::Tile024 => [true, false, true, false, true, fal...
Rust
0
CHECK: store // CHECK: ret i32 2 #[no_mangle] pub unsafe fn not_nomem() -> i32 { VAR = 1; asm!("", out("ax") DUMMY_OUTPUT, options(pure), options(readonly)); VAR = 2; VAR } // Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can...
Rust
0
Pode também levantar um erro se preferir (como no seu exemplo). """ fabrica = self._fabricas_registradas.get(tipo_midia.lower()) if not fabrica: # Opção 1: Retornar None e deixar o cliente tratar # print(f"Aviso: Fábrica para o tipo de...
Python
1
> 255 { return false; } let mut prev_c = '.'; let mut has_dot = false; for c in s.chars() { if c == '.' { if prev_c == '.' || prev_c == '-' { return false; } has_dot = true; } else if c == '-' { if prev_c == '.' { ...
Rust
0
interpret_eq("(x: y: x) y", "y: _y"); interpret_eq("(x: y: x) y", "y: _y"); // possible tricky case. Variable appears first without shadow binding // and later with shadow interpret_eq("y ((x: y: x) y)", "_y (y: _y)"); interpret_eq("z ((x: y: x) z)", "z (y: z)"); } ...
Rust
0
::Error::new( io::ErrorKind::Other, "Can't parse /proc/stat", )) } } } impl Process { pub fn new(pid: i32) -> Self { Process { pid: pid, proc_path: Path::new("/proc").join(pid.to_string()), } } pub fn find<P>(p...
Rust
0
pt: str @app.post("/ask") async def ask_question(request: QuestionRequest): """Answer questions based on the uploaded PDF documents.""" if not state["chain"]: raise HTTPException(status_code=400, detail="No PDF documents uploaded yet. Please upload PDFs first.") try: response = state["...
Python
1
e_id WHERE a.race_type = $race_type GROUP BY 1,2,3,4,5,6,7 ORDER BY a.race_date, a.race_distance", race_type = race_type ); let conn = pool.get().await?; query.fetch(&conn).await.map_err(Into::into) } pub async fn get_result_by_id(id: i32,...
Rust
0