text
string
label_name
string
labels
int64
import datetime from sqlalchemy import ( CheckConstraint, DateTime, Double, ForeignKeyConstraint, Integer, PrimaryKeyConstraint, String, text, ) from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship class Base(DeclarativeBase): pass class Users(Base): ...
Python
1
# Copyright 2021 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
1
(OrderedFloat(f)) => { RefOrOwned::Owned(Integer::from_f64(f.floor()).unwrap_or_else(|| Integer::from(0))) } &Number::Rational(ref r) => { let r_ref = r.fract_floor_ref(); let (mut fract, mut floor) = (Rational::new(), Integer::new()); (&mut fract, &mut f...
Rust
0
; let body = resp_insert.take_body().as_str().to_string(); let response: InsertEntityResponse = ron::de::from_str(&body).unwrap(); let uuid = response.uuid; let payload = format!( "MATCH ANY(a > 100, b <= 10.0) UPDATE test_match_all SET {{a: 43, c: Nil,}} INTO {}", uuid ); let r...
Rust
0
ad), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [misc_por_3](index.html) modu...
Rust
0
*deposit_amount_1, false, ), _ => Err(Error::<T>::DisabledTradingPair.into()), }; assert!(result.is_ok(), "genesis add liquidity pool failed."); }); }); } } #[pallet::pallet] pub struct Pallet<T>(PhantomData<T>); #[pallet::hooks] impl<T: Config> Hooks<...
Rust
0
t = match media_type.params().next() { Some(("q", value)) if value.len() <= 5 => match value.parse::<f32>().ok() { Some(q) if q > 1. => return Err(pear_error!("q value must be <= 1")), Some(q) if q < 0. => return Err(pear_error!("q value must be > 0")), Some(q) => Some(q), ...
Rust
0
fer, timeinfo, flags), None => PaStreamCallbackResult::Abort, }; mem::forget(stream_data); result as i32 } extern "C" fn stream_finished_callback<I, O>(user_data: *mut c_void) { // TODO: use Box::from_raw once it is stable let mut stream_data: Box<StreamUserData<I, O>> = unsafe { mem::transmute(user_da...
Rust
0
(self.zoom_pan, ZoomPan::default(), cx.last_event_time)); } else { self.target_zoom_pan = Some((self.zoom_pan, new_zoom_pan, cx.last_event_time)); } cx.request_draw(); } } match event { Event::Construct => { ...
Rust
0
from os import environ LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { '': { # root logger 'handlers': ['console'], 'level': 'DEBUG' if environ.g...
Python
1
use crate::buffer::immutable::ImmutableBuffer; use crate::buffer::view::BufferViewCreationError; use crate::buffer::BufferUsage; use crate::buffer::BufferView; use crate::format::Format; #[test] fn create_uniform() { // `VK_FORMAT_R8G8B8A8_UNORM` guaranteed to be a supported format ...
Rust
0
for source_object_id in labels[t].keys(): # check not marked as misdetection, if there is an annotation at all in the next frame if (misdetectionLabel in labels[t][source_object_id]) or (t + 1 not in labels.keys()): continue # check objec...
Python
1
ex<ProcessStateData>, /// Tracks used and free allocated Thread Local Storage regions of this process. pub tls_manager: Mutex<TLSManager>, } /// Next available PID. /// /// PIDs are just allocated sequentially in ascending order, and reaching usize::max_value() causes a panic. static NEXT_PROCESS_ID: AtomicUs...
Rust
0
[derive(Debug)] pub enum Error { Custom, AlreadyExists, IO(std::io::Error), FSExtra(fs_extra::error::Error), Zip(zip::result::ZipError), Serde(serde_json::Error) } impl From<std::io::Error> for Error { fn from(e: std::io::Error) -> Self { Error::IO(e) } } impl From<fs_extra::er...
Rust
0
_rounds = 2; let mut arena = ArenaBuilder::new().with_rounds(total_rounds).build(); assert_eq!(arena.current_round, 1); assert_eq!(arena.total_rounds, total_rounds); assert!(!arena.is_last_round()); arena.next_round(); assert_eq!(arena.current_round, 2); assert_e...
Rust
0
riEvalContext<'mir, 'tcx>, rwlock_op: OpTy<'tcx, Tag>, id: impl Into<ScalarMaybeUninit<Tag>>, ) -> InterpResult<'tcx, ()> { ecx.write_scalar_at_offset_atomic( rwlock_op, 4, id, ecx.machine.layouts.u32, AtomicWriteOp::Relaxed ) } fn rwlock_get_or_create_id<'mir, 'tcx: 'mir>( ecx: &mu...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipaySocialBaseBcClusterQueryModel(object): def __init__(self): self._operate_business_id = None self._tenant_id = None @property def operate_business_id(self): ...
Python
1
import pytest import torch import colossalai from colossalai.logging import disable_existing_loggers from colossalai.shardformer.layer import dist_log_prob_1d from colossalai.testing import rerun_if_address_is_in_use, spawn CONFIG = dict( parallel=dict(data=1, pipeline=1, tensor=dict(size=2, mode="1d")), ) def ...
Python
1
import heapq class Node: def __init__(self, state, parent, cost, heuristic): self.state = state self.parent = parent self.cost = cost self.heuristic = heuristic def __lt__(self, other): return self.heuristic < other.heuristic def best_first_search(start, goal, heuristi...
Python
1
allocPtr, CUDA_DEVICE_MEMORY_POOL}; use cuda_stream_pool::CUDA_STREAM_POOL; use pinned_memory_pool::{PinnedMemoryPtr, PINNED_MEMORY_POOL}; use persia_libs::{anyhow::Result, tracing}; use persia_speedy::{Readable, Writable}; use crate::tensor::{CPUStorage, DType}; pub fn set_device(card_index: i32) { let result =...
Rust
0
from sqlalchemy import ForeignKey, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column from databases.database import Base class OrganizationSpecializations(Base): """ Модель м2м связи организации и специализации ## Attrs - organization_id: int - идентификатор организации FK Or...
Python
1
5).reshape(1, -1, 3, S*H8, W8) sw.summ_rgbs('1_model/2_kp_s', vis_all.unbind(1)) if trajs_g is not None: seq_loss = sequence_loss(coord_predictions, trajs_g, vis_g, valids, 0.8) vis_loss, _ = balanced_ce_loss(vis_e, vis_g, valids) ce_loss = score_map_loss(fcps, t...
Python
1
aise ValueError(f"Expect inputs of 3 or 4 dim, got {len(segmentation.shape)}") return unpadded_segmentation def plot_bar(): id2label = { 0: "Caption", 1: "Footnote", 2: "Formula", 3: "List-item", 4: "Page-footer", 5...
Python
1
borrow_mut().assign(name, value) } else { Err(Error::Runtime { token: name.clone(), message: format!("Undefined variable '{}'", key), }) } } } } impl fmt::Display for Environment { fn fmt(&self, f: &mut fmt:...
Rust
0
class TrieNode: def __init__(self): self.children = {} # Dictionary to store child nodes self.isWord = False # Flag to indicate if this node marks the end of a valid word def addWord(self, word): cur = self for c in word: if c not in cur.children: # If ch...
Python
1
b struct TcpipErr { pub msg: &'static str, pub ignoreStats: bool, pub sysErr: i32, } impl TcpipErr { pub fn New(msg: &'static str, ignoreStats: bool, sysErr: i32) -> Self { return Self { msg, ignoreStats, sysErr, }; } pub const ERR_UNKNOWN_PR...
Rust
0
from pwn import * import sys context.log_level='DEBUG' if len(sys.argv) == 2: r = remote('printf.chal.ctf.westerns.tokyo', 10001) is_remote = True else: r = process(['./ld-linux-x86-64.so.2', './printf'], env={'LD_LIBRARY_PATH':'.'}) is_remote = False # Leak r.recvuntil('name?\n') r.sendline(' '.join...
Python
1
=> &self.10, 11 => &self.11, 12 => &self.12, 13 => &self.13, 14 => &self.14, 15 => &self.15, _ => panic!("invalid TextRenderCommands index"), } } } impl IndexMut<u8> for TextRenderCommands { fn index_mut<'a>(&'a mut self, index: u...
Rust
0
nfo("Update", "Record updated successfully", parent=self.root) def mark_attendance(self, face_id, roll_no, name, department): time_now = datetime.datetime.now().strftime("%H:%M:%S") date_now = datetime.datetime.now().strftime("%d/%m/%Y") attendance_status = "Present" with o...
Python
1
import unittest import torch from src.pytorch_ood.loss import CrossEntropyLoss from tests.helpers import ClassificationModel, SegmentationModel class TestCrossEntropyLoss(unittest.TestCase): """ Test code for the cross-entropy loss """ def test_example_1(self): """ Mix of IN and OOD...
Python
1
TASKS = [ 'abstract_algebra', 'anatomy', 'astronomy', 'business_ethics', 'clinical_knowledge', 'college_biology', 'college_chemistry', 'college_computer_science', 'college_mathematics', 'college_medicine', 'college_physics', ...
Python
1
mary) pub fn open_event(class: u32, spec: u16, mode: u16, func: *const u32) -> u32; /// Calls BIOS function [B(09h)](http://problemkaputt.de/psx-spx.htm#biosfunctionsummary) pub fn close_event(event: u32); /// Calls BIOS function [B(0Ah)](http://problemkaputt.de/psx-spx.htm#biosfunctionsummary) pub ...
Rust
0
anon.search(""); assert_eq!(json.crates.len(), 0); assert_eq!(json.meta.total, 0); let krate = app.db(|conn| { let u = new_user("foo").create_or_update(None, conn).unwrap(); CrateBuilder::new("fooindex", u.id).expect_build(conn) }); let json = anon.search(""); assert_eq!(json.c...
Rust
0
import controller import keyboard from time import sleep import pyautogui # keyboard=controller() def volumeup(query): for i in range(10): pyautogui.press("volumeup") def volumedown( query): for i in range(10): pyautogui.press("volumedown")
Python
1
l: r!(()), symbol: sym!("xyz").try_into()?, pairlist: pairlist!(x=1), function: R!("function() 1")?.try_into()?, // environment: Environment::new_with_parent(global_env()), // promise: Promise::from_parts(r!(1), global_env())?, ...
Rust
0
#!/usr/bin/env python3 """ Profile GPU maximum memory usage. """ from typing import Optional import torch if torch.cuda.is_available(): if torch.cuda.device_count() > 1: print("WARNING: gpu_max_mem measures the *first* GPU, but you have several.") from pynvml import ( NVMLError, nvml...
Python
1
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import unittest from pytext.data import utils class TargetTest(unittest.TestCase): def test_align_target_label(self): target = [[0.1, 0.2, 0.3], [0.1, 0.2, 0.3]] batch_label_list = [["l3", "l2", "l1"], ...
Python
1
from .model_helpers.deplot.deplot import llm_prompts, TemplateKey from transformers import Pix2StructForConditionalGeneration from .api.azure_gpt4 import gpt4 import requests import torch # device = "cuda:4" # torch.cuda.set_device(device) def deplot(image, prompt, temperature, top_p): quantization_config = BitsAn...
Python
1
"] pub mod f25r1; #[doc = "Filter bank 25 register 2"] pub struct F25r2 { register: VolatileCell<u32>, } #[doc = "Filter bank 25 register 2"] pub mod f25r2; #[doc = "Filter bank 26 register 1"] pub struct F26r1 { register: VolatileCell<u32>, } #[doc = "Filter bank 26 register 1"] pub mod f26r1; #[doc = "Filter ...
Rust
0
''' @ No: 5464 @ Title: 주차장 @ key Point: 큐 자료구조 사용 @ 입력값 : - n : 주차 공간 개수 - m : 차량 대수 - price_list : 주차 공간 별 단위 무게 당 요금 - weight_list : 차량 s번의 무게 - order_list : 주차장 출입 순서 (양수면 들어 오는 것, 음수면 나가는 차량) @ 출력값 : - 총 요금 @ 조건 : - 빈 공간이 없으면 대기한다. - 빈 공간이 여러 대 이면 가장 번호가 작은 주차 공간에 주차한다. - 여러 ...
Python
1
} }; let mut y = from.1 as f64; for x in from.0..=to.0 { put_pixel((x, y as i32), 1.0 + y.floor() - y).unwrap(); put_pixel((x, y as i32 + 1), y - y.floor()).unwrap(); y += grad; } } } fn main() { let time_span = 10.0; let time_interval ...
Rust
0
} ptr_extern_ctor! { crate::rgbd::Kinfu_VolumeParams, cv_PtrOfKinfu_VolumeParams_new } impl PtrOfKinfu_VolumeParams { #[inline] pub fn as_raw_PtrOfKinfu_VolumeParams(&self) -> *const c_void { self.as_raw() } #[inline] pub fn as_raw_mut_PtrOfKinfu_VolumeParams(&mut self) -> *mut c_void { self.as_raw_mut() } }...
Rust
0
while True: C, R = map(int, input().split()) if R + C == -2: break wall = '0' Graph = [[wall for j in range(C+2)] for k in range(R+2)] for r in range(1, R+1): line = list(input().strip()) Graph[r] = [wall] + line + [wall] direction = [(-1, 0), (1, 0), (0, 1), (0, -1)]...
Python
1
from enum import Enum from pydantic import BaseModel from fastapi import FastAPI, HTTPException, Path, Query app = FastAPI() class Category(Enum): TOOLS = "tools" CONSUMABLES = "consumables" class Item(BaseModel): name: str price: float count: int id: int category: Category items = ...
Python
1
# Copyright Allo authors. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from typing import Any from ..customize import Schedule from ..ir.utils import MockBuffer KINDS = ["reorder", "pipeline", "to", "split", "unroll"] class SchedulePrimitive: def __init__( self, kind: str, args: list[Any] =...
Python
1
import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QStandardItem, QStandardItemModel, QIcon from PyQt5.QtWidgets import QApplication, QAbstractItemView, QDialog, QGroupBox, QHBoxLayout, QLabel, QListView, QFrame from PyQt5.QtWidgets import QPushButton, QSpacerItem, QSizePolicy, QVBoxLayout, QComboBox from ...
Python
1
import io from fastapi import FastAPI, File, UploadFile, Form from fastapi.responses import StreamingResponse from video_processing import * app = FastAPI() @app.post("/lip-sync") async def lip_sync_video( video: UploadFile = File(...), speech_text: str = Form(...), language: str = Form(...) ...
Python
1
#[test] fn test_is_ipm() { unsafe { let is_ipm = tibrv_IsIPM(); assert_eq!(is_ipm, tibrv_bool::TIBRV_FALSE); } } #[test] fn get_version() { use std::ffi::CStr; unsafe { let version = CStr::from_ptr(tibrv_Version()); assert!...
Rust
0
ty = 1i32; #[doc = "*Required features: `\"Win32_UI_TabletPC\"`*"] pub const DISPID_IEPData: DISPID_InkExtendedProperty = 2i32; #[doc = "*Required features: `\"Win32_UI_TabletPC\"`*"] pub type DISPID_InkGesture = i32; #[doc = "*Required features: `\"Win32_UI_TabletPC\"`*"] pub const DISPID_IGId: DISPID_InkGesture = 0i3...
Rust
0
x = open('p1.txt').readlines()[0] from collections import Counter c = Counter(x) ans = c['B'] + 3*c['C'] print(ans) x = open('p2.txt').readlines()[0] x = [x[i:i+2] for i in range(0, len(x), 2)] S = { 'x': 0, 'A': 0, 'B': 1, 'C': 3, 'D': 5 } ans = 0 for e in x: for f in e: ans += S...
Python
1
raw = DataRep::F32(value); } pub fn boolean(&mut self, value: bool) { self.data_raw = DataRep::Bool(value); } pub fn string(&mut self, value: Box<String>) { self.data_raw = DataRep::Str(value); } pub fn array(&mut self, value: Box<Vec<Var<'a>>>) { self.data_raw = DataR...
Rust
0
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
Python
1
ker for handling edited channel `Post` events. - :code:`inline_query`: Event marker for handling `InlineQuery` events. - :code:`chosen_inline_result`: Event marker for handling chosen `InlineResult` events. - :code:`callback_query`: Event marker for handling `CallbackQuery` events. - :code:`shipping_que...
Python
1
ed_num) all_node = [i for i in range(node_num)] for i in range(edge_num): pos_ID = true_sample[i] pos_sample.append(list(map(int, pos_ID))) # half_num = math.ceil(len(pos_ID)/2) half_num = 1 for j in range(ratio): neg = random.sample((set(all_node) - set(pos_I...
Python
1
if inside_ignore_both { ignore_both(&mut entry); if marker == Some(EndIgnoreBoth) { inside_ignore_both = false; } continue; } match marker { Some(IgnoreLine) => ignore_line(&mut ent...
Rust
0
ile. /// /// **Endpoint** `GET /api/v1/users/me` /// /// **Default model** [`UserInfo`] /// /// # Examples /// ``` /// # use traduora::{TestClient as Traduora, TraduoraError}; /// use traduora::{api::users::Me, Login, Query}; /// /// let login = Login::password("<EMAIL>", "<PASSWORD>"); /// let client = Traduora::with_...
Rust
0
e) else: conv3x3s = [] for k in range(i-j): if k == i - j - 1: num_outchannels_conv3x3 = num_inchannels[i] conv3x3s.append(nn.Sequential( nn.Conv2d(num_...
Python
1
chat_id: chat_id.into(), } } } impl Method for UnpinChatMessage { type Response = bool; fn into_request(self) -> Request { Request::json("unpinChatMessage", self) } } #[cfg(test)] mod tests { use super::*; use crate::request::{RequestBody, RequestMethod}; use serde_json::V...
Rust
0
import sys, os, time, json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from ai import tokenizer, get_model, generate, next from utils.logging import exec # def main1(): # model = exec('Load model', get_model) # sentence = 'tôi đang làm công' # output_list = exec('G...
Python
1
ssert_eq!(expected, actual); } #[derive(Debug)] pub enum Opcode { SYS, CLS, RET, JP(u16), CALL(u16), SE(u8, u8), SNE(u8, u8), SER(u8, u8), LD(u8, u8), ADD(u8, u8), LDR(u8, u8), OR(u8, u8), AND(u8, u8), XOR(u8, u8), ADDR(u8, u8), SUBR(u8, u8), SHR(u8), ...
Rust
0
_PKCS11_FUNCTION_INFO($func:ident, $ftype:ident)( $( $arg:ident: $argty:ty ),* ); )* } => { // Function type. $( pub type $ftype = unsafe extern "C" fn ( $( $arg: $argty ),* ) -> CK_RV; )* ...
Rust
0
# file: app/chain/cli.py from __future__ import annotations import argparse import logging from pythonjsonlogger import jsonlogger from app.core.chain_config import _DEFAULT_INDEX from app.chain.api import _engine_for # ─── Logging setup ──────────────────────────────────────────────────────────── _LOG_HANDLER = ...
Python
1
""" ===== Words ===== Words/Ladder Graph ------------------ Generate an undirected graph over the 5757 5-letter words in the datafile `words_dat.txt.gz`. Two words are connected by an edge if they differ in one letter, resulting in 14,135 edges. This example is described in Section 1.1 in Knuth's book (see [1]_ and ...
Python
1
MoveToAction <filename>codealong/src/analyzed_diff.rs use crate::work_stats::WorkStats; use std::collections::HashMap; use std::ops::{Add, AddAssign}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AnalyzedDiff { pub stats: WorkStats, pub tag_stats: HashMap<String, WorkStats>, } impl An...
Rust
0
: &mut Criterion) { let tmp = tempfile::tempdir().unwrap(); let cache = tmp.path().to_owned(); let data = vec![1; 1024 * 1024 * 5]; let sri = cacache::put::data(&cache, "hello", data).unwrap(); c.bench_function("read_hash_big_data", move |b| { b.iter(|| cacache::get::read_hash(black_box(&cac...
Rust
0
g_key", payload) .unwrap(); let (keys, keyrings) = new_keyring.read().unwrap(); assert_eq!(keys.len(), 1); assert_eq!(keys[0], key); assert!(keyrings.is_empty()); keyring.link_key(&key).unwrap(); let (keys, keyrings) = keyring.read().unwrap(); assert_eq!(keys.len(), 1); assert...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates import torch from torch.fx.node import Argument def friendly_debug_info(v: object) -> Argument: """ Helper function to print out debug info in a friendly way. """ if isinstance(v, torch.Tensor): return f"Tensor({v.shape}, grad={v.requires_gr...
Python
1
fered: WithAttributes { /// Return a clone with the specified buffering set. fn buffered(&self, buffering: Buffering) -> Self { self.with_attributes(|new_attr| new_attr.buffering = buffering) } /// Return the current buffering strategy. fn get_buffering(&self) -> Buffering { self.ge...
Rust
0
// `__CPROVER_bitvector[bits] $pad<n>` pub fn datatype_padding(name: &str, bits: u64) -> DatatypeComponent { Padding { name: name.to_string(), bits } } pub fn double() -> Self { Double } /// The void type pub fn empty() -> Self { Empty } /// Empty struct....
Rust
0
_zeros() as u32; let trailing = if a_trailing <= b_trailing { a_trailing } else { b_trailing }; if trailing > 0 { ll::shr(ap, ap.as_const(), an, trailing); ll::shr(bp, bp.as_const(), bn, trailing); } while !ll::is_zero(ap.as_const(), an) { while *ap == 0...
Rust
0
ren: expr_list = node.children[0] for expr in expr_list.children: self.visit(expr) # Chama a função if func_name in self.procedure_starts: func_label = self.procedure_starts[func_name] self.emit(f"PUSHA {func_label}") s...
Python
1
'{}\': \n{}", input.to_str().unwrap(), err); continue; } }; println!( "\'{}\' -> \'{}\'", input.to_str().unwrap(), output.to_str().unwrap(), ) }, }...
Rust
0
ice=a_q.device ) gateup_output = gateup_output.permute(1, 2, 0) # requirement of kernel sf_vec_size = 16 assert a_q_sf.dtype == torch.float8_e4m3fn assert a_q.dtype == torch.uint8 ab_dtype = "float4_e2m1fn" sf_dtype = "float8_e4m3fn" c_dtype = "bfloat16" # Gemm1 grouped_gemm_nt...
Python
1
"123", timer_for_harvest::parse_account_details("GET /?expires_in=123&scope=harvest%3A456").2 ); assert_eq!( "123", timer_for_harvest::parse_account_details("GET /?scope=harvest%3A456&expires_in=123").2 ); } #[test] fn should_format_timeentry_not...
Rust
0
&[0xf2, 0x4f, 0x0f, 0x5e, 0x01], "divsd xmm8, [r9]"); test_instr(&[0x66, 0x4f, 0x0f, 0x5f, 0x01], "maxpd xmm8, [r9]"); test_instr(&[0xf2, 0x4f, 0x0f, 0x5f, 0x01], "maxsd xmm8, [r9]"); test_instr( &[0x66, 0x4f, 0x0f, 0x60, 0x9c, 0x9c, 0x34, 0xaa, 0xbb, 0xcc], "punpcklbw xmm11, [r12 + r11 * 4 ...
Rust
0
c::AT_FDCWD, path, 0).is_ok()); /// ``` pub fn fsync(fd: i32) -> Result<(), Errno> { let fd = fd as usize; syscall1(SYS_FSYNC, fd).map(drop) } /// Truncate an opened file to a specified length. /// /// ``` /// let path = "/tmp/nc-ftruncate"; /// let ret = nc::openat(nc::AT_FDCWD, path, nc::O_WRONLY | nc::O_CRE...
Rust
0
.5 { arr.swap(0, 2); // break point _s = show_arr(&arr); } dbg!(arr); // break point println!("Hello, world!"); }use crate::math::{Vec2, Vec3}; use crate::graphics::Material; use crate::graphics::ray::{Ray, Tracable, Bounded, Hit}; use crate::graphics::AABB; /// An infinite plane in 3d...
Rust
0
# -*- coding: UTF-8 -*- # # Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com> # # This file is part of Wammu <https://wammu.eu/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ve...
Python
1
# coding=utf-8 import sys from appium import webdriver import time # 获取尺寸 def get_size(driver): x = driver.get_window_size()['width'] y = driver.get_window_size()['height'] return (x, y) # 通过参数,来判断调用那个端口 def handle_run(scence): if scence == 1: cap = { 'platformName': 'Android', ...
Python
1
CARD) | (1 << VIRTIO_BLK_F_WRITE_ZEROES), ) .unwrap(); let out_req = Request::new( RequestType::Out, vec![(GuestAddress(0x100), 0x400), (GuestAddress(0x800), 0x200)], 1, GuestAddress(0x200), ); mem.write_slice(&[NON_ZERO_VALUE; 0x...
Rust
0
is critical and happens before stream generator can be called or its finally block # So, we log it here immediately if api_key_for_logging is available if api_key_for_logging: log_api_usage(api_key_for_logging, "chat_stream_error", model_name_for_log, prompt_tokens_for_log, 0, prompt_tokens...
Python
1
>, >; 15] = [ r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, rsp, ]; //fn parse(input: &[u8]) -> IResult<&[u8], IComplie> { //let (input, symbol): (&[u8], Option<&[u8]>) = match symbol(input) { //Ok((input, symbol)) => (input, Some(symbol)), //Err(nom::Err::Error((input, _))) => (input, None), //}; /...
Rust
0
import os os.system("clear") contador = 0 par = 0 impar = 0 soma_par = 0 soma= 0 while True: numero = int(input(f"Digite o {contador+1}º número: ")) if numero == 0: break elif numero % 2 == 0: par += 1 soma_par = numero else: impar += 1 contador += 1 soma += n...
Python
1
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: dir = [(0, 1), (1, 0), (-1, 0), (0, -1)] visited = set() queue = deque() ans = [[0 for _ in range(len(isWater[0]))] for _ in range(len(isWater))] print(ans) for i in range(len(isWate...
Python
1
command_tx .send(ClientCommand::Next( should_append, range.clone(), code.clone(), )) .map_err(|err| io::Error::new(io::ErrorKind::BrokenPipe, err))?; should_append = true; } Ok((None,...
Rust
0
expand_scenarios=False, remove_invalid_goals=False, shuffle=False, timestamp_threshold_s=None, ego_displacement_minimum_m=None, ego_start_speed_threshold=None, ego_stop_speed_threshold=None, spee...
Python
1
orModel)) else: graph.add(gtsam.PriorFactorPose3(0, first_odom_node_prior, self.priorModel)) # graph.keys() are the nodes' ids # size of the graph is the number of edges # initial are the initial values for the nodes return graph, initial def plot_input_object_p...
Python
1
xists (should not for non-persistent) actual_path = prop.replace('propConfig.', '') actual_value = flattened.get(actual_path, "NOT FOUND") has_binding = any(f"{actual_path}.binding" in p for p in flattened.keys()) print(f" {prop} → {actual_path}: {actual_value} (binding: {has_binding})") # Analyze regular cu...
Python
1
"""IK with Collision Basic Inverse Kinematics with Collision Avoidance using PyRoKi. """ import time import numpy as np import pyroki as pk import viser from pyroki.collision import HalfSpace, RobotCollision, Sphere from robot_descriptions.loaders.yourdfpy import load_robot_description from viser.extras import Viser...
Python
1
文件写入完毕,请查收!') if __name__ == '__main__': title() parser = argparse.ArgumentParser(description="Raster Terminator V1.1", epilog='自动读取图片并尝试爆破光栅,诸如:python3 Raster-Terminator.py -x demo.png') parser.add_argument('-x', action='store', dest='xcoordinate', help='自动读取图片并尝试爆破横向光栅图') parser.add_argument('-y', a...
Python
1
cell(body: &str, id: StreamId, msg: RelayMsg) { let body = decode(body); let mut bad_rng = BadRng; let expected = RelayCell::new(id, msg); let decoded = RelayCell::decode(body).unwrap(); assert_eq!(format!("{:?}", expected), format!("{:?}", decoded)); let encoded1 = decoded.encode(&mut bad_rng).unwrap(); le...
Rust
0
class Solution: def minOperations(self, s: str) -> int: furthest_char = 0 for char in s: if char == 'a': co...
Python
1
assert!(frame.is_set(4, 0)); assert!(frame.is_set(4, 1)); assert!(frame.is_set(4, 2)); assert!(frame.is_set(4, 3)); assert!(!frame.is_set(4, 4)); } } } <filename>src/models/media.rs use crate::models::{ manga, relation, }; use crate::schema::media...
Rust
0
usage=globals()['__doc__'], version='$Id: FSM.py 533 2012-10-20 02:19:33Z noah $') parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output') (options, args) = parser.parse_args() if options.verbose: print time.asctime() main() if options.ver...
Python
1
0.into_owned()) } } impl Deref for InterfaceName<'_> { type Target = str; fn deref(&self) -> &Self::Target { self.as_str() } } impl Display for InterfaceName<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.as_str(), f) } } impl PartialEq<str> fo...
Rust
0
, 34038, 49489, 96595, 75366, 50721, 61362, 69035, 12224, 61742, 55712, 36233, 55324, 22898, 72897, 74814, 74285, 89085, 91738, 40750, 39373, 8325, 77713, 72707, 5472, 15854, 35277, 78633, 98355, 97707, 496, 1622, 90274, 16387, 3208, 89508, 32109, 13999, 10123, 89422, 134...
Rust
0
#[nrf_softdevice::gatt_server] struct Server { my_service: MyService, } #[embassy::task] pub async fn bluetooth_task( sd: &'static Softdevice, button1: InputChannel<'static, AnyChannel, AnyPin>, mut led5: gpio::Output<'static, AnyPin>, ) { let server: Server = unwrap!(gatt_server::register(sd)); ...
Rust
0
""" public toolkit API """ from pandas.api import ( extensions, indexers, interchange, types, typing, ) __all__ = [ "interchange", "extensions", "indexers", "types", "typing", ]
Python
1
_something || p.pass(&mut model)?; if cfg!(debug_assertions) { model.check_edges()?; } } if !done_something { break; } model = compact::compact(&model)?; } Ok(model) } /// Attempt...
Rust
0
""" Python 'utf-16-le' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs encode = codecs.utf_16_le_encode def decode(input, errors='strict'): return codecs.utf_16_le_decode(input, errors, True) class IncrementalEncod...
Python
1