text
string
label_name
string
labels
int64
aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam ...
Rust
0
{ JsBox::new(self, v) } #[cfg(all(feature = "napi-4", feature = "event-queue-api"))] /// Creates an unbounded queue of events to be executed on a JavaScript thread fn queue(&mut self) -> EventQueue { EventQueue::new(self) } } /// A view of the JS engine in the context of top-level...
Rust
0
def getNfsCallStruct(procedure): if procedure == "lookup": callStruct = NfsDiropArgs elif procedure == "getattr": callStruct = NfsFhandle elif procedure == "read": callStruct = NfsFileopArgs else: raise RuntimeError("NFS call procedure {} not implemented".format(procedure)) return callStruct ...
Python
1
).format( data_json.get("user", {}).get("id"), data_json.get("user", {}).get("nickname"), ) ) return data_json @classmethod async def WebcastChatMessage(cls, data: bytes) -> dict: """ 处理直播间聊天消息 Args: data (bytes)...
Python
1
*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] pub const VERTEX: u32 = 1u64 as u32; #[cfg(web_sys_unstable_apis)] #[doc = "The `GPUShaderSt...
Rust
0
ror::CircularTypes( alpha.extract(), left.clone(), right.clone(), )) } } // <: instantiate R // α^ /∈ FV(A) Γ[^α] ⊢ A =<: ^α ⊣ ∆ // Γ[^α] ⊢ A <: ^α ⊣ ∆ ...
Rust
0
cond component of the vector. pub y: N, /// Third component of the vector. pub z: N, /// Fourth component of the vector. pub w: N, /// Fifth of the vector. pub a: N } double_dispatch_binop_decl_trait!(Vec5, Vec5MulRhs) double_dispatch_binop_decl_trait!(Vec5, Vec5DivRhs) double_dispatch_bino...
Rust
0
mples) = self.samples { unsafe { (*samples[index_of(x, y, self.width, self.height)].get()).push(sample); } } else { panic!("Using uninitialized SampleAcumulator!") } } pub fn flush(&self, sink: &mut Box<RayTraceSink>, frame: usize) -> Result<(), IOError> { if let Some(ref samples) = self.samples {...
Rust
0
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: ''' using divisors string concatenation ''' n = len(s) for i in range(1, n // 2 + 1): if n % i == 0: pattern = s[:i] * (n // i) if s == pattern: ...
Python
1
u32, (), _>(&mut store, "__rustretro_plugin_free_emulator") .unwrap(); Self { emulator_pointer, timeout_ms, epoch_handle, epoch_stop_sender, store, memory, metadata, wasm_controller_input, ...
Rust
0
view.api.OpenReviewClient( baseurl='https://api2.openreview.net', username=os.environ.get('openreview_id'), password=os.environ.get('openreview_pw'), ) # for skp, fav, aggr res_notes = [[], [], []] #XXX kmkim: return pdfs with notes pdfs = [[], [], []] notes = client.sea...
Python
1
275, 546.1933, 1.0000], [273.3727, 545.5930, 1.0000]]] ) res = draw_keypoints(person_int, prediction, connectivity=connect_skeleton, colors="blue", radius=4, width=3) show(res) # %% # What happened there? # The model, which predicted the new keypoints, # can't detect the three points that are hidden on the uppe...
Python
1
tch_index = int(callback_data.split("_")[1]) user_data["current_batch"] = batch_index batches = user_data["batches"] if 1 <= batch_index <= len(batches): selected_batch = batches[batch_index - 1] query.edit_message_text( f"📁 دسته {ba...
Python
1
import os import torch import imghdr from glob import glob import numpy as np from PIL import Image from transformers import AutoModelForCausalLM import folder_paths from nodes import node_helpers, ImageSequence, ImageOps from .janus.models import VLChatProcessor from .utils import mie_log MY_CATEGORY = "🐑 JanusProC...
Python
1
'files_with_faces': len([f for f in file_metadata.values() if f['faces_detected'] > 0]), 'cache_last_updated': cache_last_updated, 'face_encodings_count': len(face_encodings) }) if __name__ == '__main__': print("�� Starting Optimized DeepFace Photo Finder App...") # Load existing c...
Python
1
from flask import url_for, request from ..models import db, Class from ..decorators import json, paginate, etag from . import api @api.route('/classes/', methods=['GET']) @etag @paginate() def get_classes(): return Class.query @api.route('/classes/<int:id>', methods=['GET']) @etag @json def get_class(id): r...
Python
1
ements the `TypeCheckerFamilyDependentExt` methods along with substitution. crate mod type_checker; /// Type family for "base inference" -- inferring just the base types. #[derive(Copy, Clone, Debug, DebugWith, PartialEq, Eq, Hash)] crate struct FullInference; impl TypeFamily for FullInference { type InternTables...
Rust
0
ed PNG byte buffer. pub async fn load_png( file: File, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, JsValue> { let array_buffer = JsFuture::from(file.array_buffer()).await?; let uint8_array = Uint8Array::new(&array_buffer); let png = decode_png(&uint8_array.to_vec()[..], demultiply)...
Rust
0
casts::usize::usize; <reponame>tasogare3710/filesystem_provider //! 具象ファイルシステムを新たに作るためのファクトリに関するモジュール。 pub mod make; <filename>crypto/multisig/src/lib.rs // Copyright (c) 2018-2022 The MobileCoin Foundation //! Multi-signature implementation: A multi-signature is a protocol that allows //! a group of signers, each po...
Rust
0
from plots_constants import * from scipy.stats import spearmanr with plt.rc_context(bundles.neurips2023()): fig, (ax, ax2) = plt.subplots(ncols=2) fig.set_figheight(2.4) for x, y, color, marker, size in zip(res["best_eval_auroc_correct"].to_list(), res["best_test_av...
Python
1
def load_knowledge(): vecs = [] vecs.append([0] * 100) with open('../../kg_embed/entity2vec.del', 'r') as fin: for line in fin: vec = line.strip().split('\t') vec = [float(x) for x in vec] vecs.append(vec) embed_ent = torch.FloatTensor(vecs) del vecs v...
Python
1
Id(state).into()), } } } /// Section of the replSetGetStatus member that we care about. #[derive(Debug, Deserialize)] pub struct ReplSetStatusMember { #[serde(rename = "self", default = "ReplSetStatusMember::default_self")] pub is_self: bool, pub name: String, pub optime: TimeStamp, pub...
Rust
0
from typing import Any, Dict, List, Optional import requests from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, SecretStr, root_validator from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env JINA_API_URL: str = "https://api.jina.ai/v1/embeddings"...
Python
1
::opstats::gen_opstat_unguarded_register(ctx.builder, instruction); for i in 0..8 { ctx.builder .const_i32(global_pointers::get_reg32_offset(i as u32) as i32); ctx.builder.get_local(&ctx.register_locals[i]); ctx.builder.store_aligned_i32(0); } } pub fn gen_move_registers_fro...
Rust
0
n!( "{term:width$}", term = Term::Ann( Ignore::default(), Rc::new(Term::Var(Ignore::default(), Var::Free(Name::user(&*name)))), Rc::new(Term::from(&*inferred)), ).to_concrete(), width = term_width...
Rust
0
duration: start.elapsed(), }), Err(e) => Err(RequestFailure::General(format!("{:?}", e))), } } } use molecule_codegen::ast::{self, HasName}; use case::CaseExt; pub(in super::super) trait GenBuilder { fn gen_builder(&self) -> String; } impl GenBuilder for ast::Option_...
Rust
0
globalstar_gateway: 5, last_contact_time: 6, last_attempt_time: 7, call_attempts_since_reset: 8, successful_connects_since_reset: 9, average_connection_duration: 10, connection_duration_...
Rust
0
(state, hbox, |builder| builder.set_flex_grow(1.0)); // let row3 = HBox::new().build(state, panel, |builder| { // builder.class("item") // }); // Label::new("Checkbox").build(state, row3, |builder| builder.class("label")); // Checkbox::new().build(state, row3, |builder| builder.set_align_self(A...
Rust
0
).is_ok()); //! ``` //! **Note**: The above example generates a private key using a private function intended only for //! testing purposes. Production code should find an alternate means for secure key generation. use crate::{traits::*, HashValue}; use anyhow::{anyhow, Result}; use core::convert::TryFrom; use libra_c...
Rust
0
retval VX_ERROR_NOT_SUPPORTED If the \\a attribute is not a value supported on this implementation."] #[doc = " \\retval VX_ERROR_INVALID_PARAMETERS If any of the other parameters are incorrect."] #[doc = ""] #[doc = " \\ingroup group_array"] pub fn vxQueryArray( arr: vx_array, at...
Rust
0
max_len = max(max_len, self._lens[index]) if max_len * (len(batch_indices) + 1) > self._max_tok: if not batch_indices: raise ValueError( "max_tokens too small / max_seq_len too long") batches.append(batch_in...
Python
1
is_value1(&self) -> bool { **self == PDIS12_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PDIS12_A::VALUE2 } } impl core::ops::Deref for PDIS12_R { type Target = crate::FieldReader<bool, PDIS12_A...
Rust
0
f32 = 1.5; pub const SCREEN_SIZE: f32 = 24.0; pub const PLAYER_LIMIT: f32 = SCREEN_SIZE - PLAYER_SIZE; pub const PLAYER_VLIMIT: f32 = SCREEN_SIZE * 2.0 - PLAYER_SIZE; use std::f32::consts::{PI}; pub use self::point::{Point3D}; pub use self::vector::{Vector3D, AsVector}; pub use self::direction::{Direction3D}; pub use...
Rust
0
ame, "babylon-request-id"); let attr = plugin_attributes!("TcpLog", api.plugins.remove(0), ApiPlugin::TcpLog); assert_eq!(attr.enabled, true); assert_plugin_removed!("Oauth2", api.plugins.remove(0), ApiPlugin::Oauth2); assert_plugin_removed!("Oauth2Extension", api.plugins.remove(0), ApiPlugin::Oauth2E...
Rust
0
_MODE_DESC> for ModeDesc<u32, u32, Rational, Format> { fn from(src: DXGI_MODE_DESC) -> ModeDesc<u32, u32, Rational, Format> { ModeDesc { width: src.Width, height: src.Height, refresh_rate: src.RefreshRate.into(), format: unsafe { std::mem::transmute(src.Format...
Rust
0
::symlink; use std::path::{Path, PathBuf}; use anyhow::{bail, Result}; use nix::errno::Errno; use nix::fcntl::{open, OFlag}; use nix::mount::mount as nix_mount; use nix::mount::MsFlags; use nix::sys::stat::Mode; use nix::sys::stat::{mknod, umask}; use nix::unistd::{chdir, chown, close, getcwd}; use nix::unistd::{Gid, ...
Rust
0
0x21, 0xD1, 0xB9, 0xC9, 0xEA, 0x05, 0x12, 0x11, 0x10, 0x11, 0x21, 0x0C, 0x0C, 0x0A, 0x04, 0x15, 0xFC, 0x03, 0x00, 0xCC, 0xA1, 0x30, 0xA0, 0x21, 0xD1, 0x10, 0x11, 0x21, 0x0C, 0x18, 0xB9, 0xC9, 0xEA, 0x05, 0x12, 0x11, 0x0A, 0x04, 0x15, 0xFC, 0x03, 0x00, 0x08, 0x11, 0x22, 0x04, 0x00, 0x08, 0x60, 0x00, 0x3D...
Rust
0
assert_eq!(lookup.to_string(), input); } #[test] fn unquoted() { let input = "start.after"; let lookup = Lookup::from_str(input).unwrap(); assert_eq!(lookup[0], Segment::from("start")); assert_eq!(lookup[1], Segment::from("after")); assert_eq!(lookup.to_string(), input); } #[test] fn quoted() {...
Rust
0
(2)]]; }; struct FragData { float4 pos [[position]]; float2 uv; float4 color; }; vertex FragData vert( Vertex v [[stage_in]], constant uint2 *viewport_size [[buffer(1)]] ) { FragData out; out.pos = float4((v.pos / float2(*viewport_size)) * 2.0, 0.0, 1.0); out.pos.x -= 1.0; out.pos.y = 1.0 - o...
Rust
0
Queuer0queuesr|r4)r(maxsizer|s rr|BaseContext.Queued!W"2"2"455rc6SSKJn U"XR5S9$)rzr JoinableQueuer0r~rr4)r(rrs rrBaseContext.JoinableQueuei)W*:*:*<...
Python
1
(torch.int64) batch, cat, height, width = scores.size() # topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K) # 前100个点 topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() K = topk_inds.numel() to...
Python
1
= dest.metadata()?; let mut perm = meta.permissions(); perm.set_mode(0o750); set_permissions(dest, perm).await } <reponame>invarianee/inve-crypt<filename>inve-elliptic-curve/src/scalar/nonzero.rs use crate::{ bigint::Encoding as _, ops::{Invert, Reduce, ReduceNonZero}, rand_core::{CryptoRng, Rn...
Rust
0
ub cosmos_quorum_acked_llsn: u64, pub session_token: String, pub charge: f64, pub service_version: String, pub activity_id: uuid::Uuid, pub gateway_version: String, pub date: DateTime<Utc>, } impl CreateOrReplaceTriggerResponse { pub async fn try_from(response: HttpResponse) -> azure_core::...
Rust
0
ian 4-byte integer from some position. #[inline] #[cfg(not(feature = "safe-encode"))] pub(super) fn get_batch(input: &[u8], n: usize) -> u32 { unsafe { read_u32_ptr(input.as_ptr().add(n)) } } #[inline] #[cfg(feature = "safe-encode")] pub(super) fn get_batch(input: &[u8], n: usize) -> u32 { let arr: &[u8; 4] = ...
Rust
0
def test_app_human_longint_filter_non_numeric_str(mock_app): """Test template filter human_longint when the provided string is 'inf'.""" assert "human_longint" in mock_app.jinja_env.filters.keys() assert mock_app.jinja_env.filters["human_longint"]("inf") == "inf" def test_app_human_longint_filter_str(mock...
Python
1
import os, yaml DEFAULT = { "settings": { "router": { "strategy": "smart", "weights": {"cost": 0.60, "latency": 0.25, "quality": 0.15}, "profiles": { "openai:gpt-4o-mini": {"cost": 0.15, "latency": 0.8, "quality": 0.75}, "openai:gpt-4o": {"cost": 5.00, "latency": 1.0, "quality":...
Python
1
get_alfred_version")] pub alfred_version: Version, /// Number of bookmarks to show in Alfred pub pins_to_show: u8, /// Number of tags to show in Alfred pub tags_to_show: u8, /// Flag to perform search only on `tag` fields of bookmarks pub tag_only_search: bool, /// Flag to perform a fuzz...
Rust
0
(coef) > threshold].tolist() # Save the list of selected features to a text file, one feature per line. with open(selected_features_file, 'w') as f: for feature in selected_features: f.write(f"{feature}\n") print(f"Selected {len(selected_features)} features (demographic features exclude...
Python
1
upper_bound]) np.save('sample_shap{}.npy'.format(FLAGS.index), sample_shap) print('Getting primal effects...') try: primal_effects = np.load('primal_effects{}.npy'.format(FLAGS.index)) except FileNotFoundError: primal_explainer = MarginalExplainer(model, X_tr...
Python
1
#apply knn algorithm for regression import pandas as pd from sklearn import linear_model from sklearn.neighbors import KNeighborsRegressor #training patterns df=pd.read_csv("Example2.csv") x=df[['length','width']] y=df['cost'] #applying linear regression on training pattern r=linear_model.LinearRegression() r.fit(x....
Python
1
eip, third, breakpoint, memory): ''' TBD can we manage breakpoints/haps with runAlone vice stopping execution? ''' if self.breakout_hap is None: return cpu, comm, tid = self.task_utils.curThread() bp = int(str(breakpoint)) self.lgr.debug('exitMaze breakout tid:%s bre...
Python
1
t key).await?; Ok((key, None)) } ValueKind::Unknown => Err(IoError::new( ErrorKind::InvalidData, format!("invalid value kind {}", kind), )), } } <filename>src/matrix/sparse_crs.rs use matrix::BasicReadableMatrix; use matrix::BasicWriteableMatrix; use matri...
Rust
0
_and_tcpstream() { fn _foo(sess: ClientSession, sock: TcpStream) -> StreamOwned<ClientSession, TcpStream> { StreamOwned { sess, sock } } } #[test] fn streamowned_can_be_created_for_server_and_tcpstream() { fn _foo(sess: ServerSession, sock: TcpStream) -> StreamOwned<Serv...
Rust
0
# You can assign values to more than one variable using just a single line. x,y,z=1,2,3 print(x,y,z)
Python
1
!(fc2SetFormat7Configuration(self.context.handle, &mut fmt7_settings, 100.0)); self.roi_offset = (0, 0); checked_call!(fc2StartCapture(self.context.handle)); } Ok(()) } fn set_boolean_control(&mut self, _id: CameraControlId, _state: bool) -> Result<(), CameraError> { ...
Rust
0
ed_game is None: raise RuntimeError("Game not initialized. Call init_game() first.") original_debug = self.enhanced_game.debug if hasattr(log_file, 'write'): self.enhanced_game.debug = False try: results = self.enhanced_game.run_game() ...
Python
1
} else { self.write_all(&tmp[0..64+56-m]).unwrap(); } // Length in bits (=lengh in bytes*8=shift 3 bits to the right). len = len << 3; for i in (0..8) { tmp[i] = (len >> (56 - 8*i)) as u8; } self.write_all(&tmp[0..8]).unwrap(); a...
Rust
0
sults directory exists eval_results_dir = model_training_dir / "evaluation_results" eval_results_dir.mkdir(exist_ok=True) analysis_file = eval_results_dir / "dataset_analysis.json" with open(analysis_file, 'w', encoding='utf-8') as f: json.dump(analysis_results, f, indent=2, ensure_ascii=Fa...
Python
1
.com', '36氪': 'https://36kr.com', '36kr': 'https://36kr.com', '虎嗅': 'https://www.huxiu.com', '虎嗅网': 'https://www.huxiu.com', '雷锋网': 'https://www.leiphone.com', '钛媒体': 'https://www.tmtpost.com', '创业邦': 'https://www.cyzone.cn', ...
Python
1
del_dir pipeline_dir = args.pipeline_dir repo_id = args.repo_id wallet_name = args.wallet_name hotkey_name = args.hotkey_name hf_token = args.hf_token if not hf_token: hf_token = HuggingFaceModel.get_hf_token() upload_model = args.upload_model upload_pipeline = arg...
Python
1
OLLERAXISMOTION, ControllerButtonDown = ll::SDL_CONTROLLERBUTTONDOWN, ControllerButtonUp = ll::SDL_CONTROLLERBUTTONUP, ControllerDeviceAdded = ll::SDL_CONTROLLERDEVICEADDED, ControllerDeviceRemoved = ll::SDL_CONTROLLERDEVICEREMOVED, ControllerDeviceRemapped = ll::SDL_CONTROLLERDEVICEREMAPPED, F...
Rust
0
tsdf_vol[mask] = tsdf_vol_bilin[mask] # padding_mode='ones' does not exist for grid_sample so replace # elements that were on the boarder with 1. # voxels beyond full volume (prior to croping) should be marked as empty mask = (coords.abs()>=1).squeeze(0).any(3) tsdf_vol[mask...
Python
1
; ((self.bits >> OFFSET) & MASK as u32) != 0 }; AMRDOYR { bits } } #[doc = "Bit 6 - When 1, the Month value is not compared for the alarm."] #[inline] pub fn amrmon(&self) -> AMRMONR { let bits = { const MASK: bool = true; const OFFSET: u8 = 6;...
Rust
0
const BINTIME_SCALE: f64 = 5.421010862427522e-20; let old: bintime = if let Some(prev) = $prev { $bintime(unsafe {prev.devstat.as_ref() }) } else { bintime{sec: 0, frac: 0} }; let new: bintime = $bintime(unsafe {$cur.devstat.as...
Rust
0
from config import ALLOWED_FILE_TYPES def is_file_type_allowed(file_type: str) -> bool: return file_type in ALLOWED_FILE_TYPES
Python
1
show_element(&input_id1); find_element_by_id(&input_id1) .dyn_into::<web_sys::HtmlInputElement>() .unwrap() .set_value(&name); // prefill the text input with the old name focus_element(&input_id1); Msg::...
Rust
0
def test_safe_join(): assert safe_join("foo", "bar/baz") == posixpath.join("foo", "bar/baz") assert safe_join("foo", "../bar/baz") is None if os.name == "nt": assert safe_join("foo", "foo\\bar") is None def test_safe_join_os_sep(): import werkzeug.security as sec prev_value = sec._os_alt_s...
Python
1
router = router_with_routes(&$routes); let routed_to = matches(&router, Get, $to); let expected = &[$($want),+]; assert!(routed_to.len() == expected.len()); for (got, expected) in routed_to.iter().zip(expected.iter()) { assert_eq!(got.uri.to_string(), exp...
Rust
0
""" 此脚本用于测试yolov5中一些操作运算 单独测试,方便自己理解 """ import os import random from tqdm import tqdm from pathlib import Path import numpy as np import torch import math def make_grid(nx=10, ny=10): """生成特征图网格坐标""" # 输出的shape:(1,1,ny,nx,2) # [[(0,0),(0,1),(0,2)], # [(1,0),(1,1),(1,2)]] yv, xv = torch.meshgrid...
Python
1
]) { if cfg.minify_css { let result = Minifier::default().minify(unsafe { from_utf8_unchecked(code) }, Level::Three); // TODO Collect error as warning. if let Ok(min) = result { if min.len() < code.len() { out.extend_from_slice(min.as_bytes()); ret...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' name: zookeeper 未授权漏洞 referer: https://www.secpulse.com/archives/61101.html author: Lucifer description: Zookeeper的默认开放端口是2181。Zookeeper安装部署之后默认情况下不需要任何身份验证, 造成攻击者可以远程利用Zookeeper,通过服务器收集敏感信息或者在Zookeeper集群内进行破坏(比如:kill命令)。 攻击者能够执行所有只允许由管理员运行的命令。。 ...
Python
1
sheet, also known as the length. pub fn len(&self) -> usize { self.sprites.len() } /// If the sprite sheet contains sprites or not. pub fn is_empty(&self) -> bool { self.sprites.is_empty() } /// Retrieves the sprite's index from a given texture and point. /// /// # Err...
Rust
0
mod primitive; use self::data::parse_type_data; use self::header::*; use self::primitive::type_data_for_primitive; pub use self::data::*; pub use self::primitive::{Indirection, PrimitiveKind, PrimitiveType}; /// `TypeInformation` provides zero-copy access to a PDB type data stream. /// /// PDB type information is s...
Rust
0
e connection ID for the scalar message to route to. Created by the caller before hooking. } ////////////////////////////////////////////////////////////////////////////////////// pub const ZERO_PCM: u16 = 0x0; // assumes 2's compliment. 0x8000 otherwise. pub const FIFO_DEPTH: usize = 256; /* The format of samples app...
Rust
0
tent or "*无法识别图片内容*" except FileNotFoundError: # 重新抛出文件不存在错误 raise except Exception as e: logger.error(f"图片处理失败: {e}") raise Exception(f"图片处理失败: {str(e)}") async def get_ocr_text(image_path: str) -> str: """ 使用PaddleOCR提取图片中的文字 Args: image_path:...
Python
1
''' 题目:输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。例如,输入如下的链表1和链表2,则合并之后的升序链表如链表3所示。 链表1:1-->3-->5-->7 链表2:2-->4-->6-->8 链表3:1-->2-->3-->4-->5-->6-->7-->8 ''' """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """...
Python
1
cur_node = &mut cur_node.as_mut().unwrap().next; } } // 最后可以还有进位没有加入到链表 if carry > 0 { cur_node.as_mut().unwrap().next = Some(Box::new(ListNode::new(1))); } head } #[cfg(test)] mod test { use crate::add_two_numbers::{add_two_numbers, ListNode}; // 传入的 v 是正序的,...
Rust
0
用; • 16k_en:英语; • 16k_yue:粤语; • 16k_id:印度尼西亚语; • 16k_fil:菲律宾语; • 16k_th:泰语; • 16k_pt:葡萄牙语; • 16k_tr:土耳其语; • 16k_ar:阿拉伯语; • 16k_es:西班牙语; • 16k_hi:印地语; • 16k_fr:法语; • 16k_de:德语; :rtype: str """ return self._EngineType @EngineType.setter def EngineType(self, EngineType): self._Engi...
Python
1
ponse_json] except KeyError: iterable = [] for obj in iterable: for field in fields: datetime_obj = str_to_datetime(obj[field], original_format) obj[field] = datetime_to_str(datetime_obj, expected_format) respo...
Python
1
@property def minor(self): return self._minor
Python
1
f x != -1) # append to savelist layers.append(m_) ch.append(c2) return nn.Sequential(*layers), sorted(save) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') parser.add_argument('--device', d...
Python
1
nstance(state2, Matrix): raise ValueError("state1 and state2 must be of type Density or Matrix " "received type=%s for state1 and type=%s for state2" % (type(state1), type(state2))) if state1.shape != state2.shape and state1.is_square: raise ValueEr...
Python
1
_layer = Layer::new().with_writer(stdout_writer); guards.push(stdout_guard); let app_name = concat!(env!("CARGO_PKG_NAME"), "-", env!("CARGO_PKG_VERSION")).to_string(); let file_appender = RollingFileAppender::new(Rotation::DAILY, "/docker2mqtt/logs", "d2m"); let (file_writer, file_guard) = tracing_ap...
Rust
0
Result}; use crate::ui::{Contents, LikedSongs, RecentPlayed}; use self::rspotify::model::context::CurrentlyPlaybackContext; use self::rspotify::model::track::SavedTrack; use crate::spoterm::SaveState::UNKNOWN; use rspotify::model::device::Device; use rspotify::model::playing::PlayHistory; use rspotify::senum::RepeatS...
Rust
0
= GroupProfileAuthorization().read_list([], mock_bundle) self.assertEqual(GroupProfile.objects.all().count(), groups.count()) @patch("geonode.api.authorization.ApiLockdownAuthorization.read_list", return_value=GroupProfile.objects.all()) @patch("geonode.people.models.Profile.group_list_all", return_val...
Python
1
} } pub fn read_expression_bytes<T: Read>(reader: &mut T) -> anyhow::Result<Vec<u8>> { let mut acc = ReaderInstructionAccumulator::new(reader); while acc.move_to_next()? { // Nothing in here - we're just accumulating the instructions } Ok(acc.instr_bytes()) } <filename>src/enums.rs use se...
Rust
0
/// /// The sub-resources are deleted asynchronously and order of their deletion is not guaranteed, as /// each sub-resource deletion is handled by its own controller. Therefore, naturally, once this method /// returns, it is not a guarantee of the sub-resources being deleted. This is correct approach, as /// resource...
Rust
0
8((((len & 0x07) as u8) << 5) | 0x1F)?; //5 self.bytes_writer.write_u8(0xFC)?; //6 self.bytes_writer .write(&self.bytes_reader.extract_remaining_bytes()[..])?; Ok(()) } } <gh_stars>0 #[macro_use] extern crate clap; use gnuplot::{Figure, Color}; use clap::{Arg, App}; use dsp::s...
Rust
0
s should be less or equal than the {}.", Self::MAX_NODES_COUNT ); ensure!( self.anchoring_interval > 0, "Anchoring interval should be greater than zero." ); ensure!( self.transaction_fee >= Self::MIN_TX_FEE, "Transaction fee sho...
Rust
0
mg, self.level_map[op_name]) return img class RandAugment(RawRandAugment): """RandAugment wrapper to auto fit different img types""" def __init__(self, prob=0.5, *args, **kwargs): self.prob = prob if six.PY2: super(RandAugment, self).__init__(*args, **kwargs) else:...
Python
1
{ Debug }; use std::cmp::{ PartialEq }; use cql_model::{ CqlWritable, CqlReadable }; use crate::tests::single_point_read_writes::_4d_database::with_overwrite::test_functions; const POINT: [u64; 4] = [2, 3, 4, 5]; pub fn unchecked<TStore: CqlWritable + CqlReadable>(db_location: &str, value1: TStore::ValueType, value2:...
Rust
0
"); } if cfg!(target_family = "windows") { entry_excluded_items.set_text("*\\.git\\*,*\\node_modules\\*,*\\lost+found\\*,*:\\windows\\*"); } } // Resetting allowed extensions { let entry_allowed_extensions = upper_notebook.entry_allowed_extensions.clone(); ...
Rust
0
footnote["referenced_items"] = [ {**item, "item_uid": mock.ANY, "visible_in_protocol_soa": mock.ANY} for item in footnote["referenced_items"] if item["item_type"] not in {"StudyActivityGroup"} ] normalized_footnotes.append(footnote) # Assign filtered list back...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """Config file that contains all config varibles.""" __author__ = 'Chong Guo <armourcy@email.com>' __copyright__ = 'Copyright 2018, Chong Guo' __license__ = 'GPL' import numpy as np import tensorflow as tf # Debug flag, if true, will check model shape using assert in e...
Python
1
_populates="context_templates") class ContextBackup(Base): """Backup of a context.""" __tablename__ = "dashboard_context_backups" id = Column(Integer, primary_key=True) context_id = Column(Integer, ForeignKey("dashboard_gpt_contexts.id"), nullable=False) backup_data = Column(JSON, nullable=False) ...
Python
1
_Normal; smooth out vec4 v_Color; uniform mat4 u_Projection; uniform mat4 u_View; uniform mat4 u_Model; uniform vec4 u_Color; uniform vec3 u_LightDirection; void main() { vec3 normal = normalize(vec3(u_Model * vec4(a_Normal, 0.0))); float dot = max(dot(normal, u_LightDirec...
Rust
0
+ Scalar { } impl<T> Identity<Addition> for Polynomial<T> where T: Identity<Addition> { fn id() -> Self { Polynomial::from_coef(vec![T::id()]) } } impl<T> Monoid<Addition> for Polynomial<T> where T: MagmaAdd + Scalar + Identity<Addition> { } impl<T> MonoidAdd for Polynomial<T> where ...
Rust
0
mm_mul_ps(a_wzwy, c_wwyz)); *f = _mm_mul_ps(a_xxxx, d); *f = _mm_add_ps(*f, _mm_mul_ps(b, _mm_shuffle_ps(c, c, 0 /* 0, 0, 0, 0 */))); *f = _mm_add_ps( *f, _mm_mul_ps(a_ywyz, _mm_shuffle_ps(d, d, 121 /* 1, 3, 2, 1 */)), ); *f = _mm_add_ps( *f, ...
Rust
0
# Tag: String # Time: O(N) # Space: O(1) # Ref: - # Note: - # You are given a string num consisting of only digits. A string of digits is called balanced if the sum of the digits at even indices is equal to the sum of digits at odd indices. # Return true if num is balanced, otherwise return false. #   # Examp...
Python
1
ault: _D, convert: Callable[[str], _T], ) -> _T | _D: ... def get( # type: ignore self, section: str, name: str, default: _D | None = None, convert: Callable[[str], _T] | None = None, ) -> _D | _T | str | None: try: value: str = s...
Python
1