text
string
label_name
string
labels
int64
ne(always)] pub fn divide_1(self) -> &'a mut W { self.variant(SPDIF0_CLK_PODF_A::DIVIDE_1) } #[doc = "Divide by 2"] #[inline(always)] pub fn divide_2(self) -> &'a mut W { self.variant(SPDIF0_CLK_PODF_A::DIVIDE_2) } #[doc = "Divide by 3"] #[inline(always)] pub fn divid...
Rust
0
e(Bytes::new(Vec::from(flags))); } pub(crate) fn set_yylval_str(&mut self, value: &TokenBuf) { println_if_debug_lexer!("set_yylval_str {:#?}", value); self.lval = Some(value.bytes.clone()); } pub(crate) fn set_yylval_name(&mut self) { println_if_debug_lexer!("set_yyval_name({:#...
Rust
0
import numpy as np from numpy import cos, sin, arctan2, pi import trackers.Struck import objects class objects: def __init__(self): self.x = None self.y = None self.v = None self.a = None self.yaw = None self.yawrate = None self.w = None self.l = No...
Python
1
} pub fn set_property_internal( org: &mut orgize::Org, key: &str, value: &str, ) -> Result<(), crate::errors::HeadlineError> { let t = &mut get_title_mut_internal(org)?; let pairs = &mut t.properties.pairs; match pairs.binary_search_by(|(k, _)| k.as_ref().cmp(key)) { Ok(id_index) => { ...
Rust
0
"""Manage git auto configuration""" manager = GitAutoManager() config_file = manager.repo_root / ".git_auto_config.json" if show: console.print("⚙️ Git Auto Configuration:") for key, val in manager.config.items(): console.print(f" {key}: {val}") return ...
Python
1
"""Solving Poisson equation using a mixed (two-field) formulation.""" # https://fenicsproject.org/docs/dolfin/2018.1.0/python/demos/mixed-poisson from dolfin import * # Create mesh mesh = UnitSquareMesh(30, 30) # Define finite elements spaces and build mixed space BDM = FiniteElement("BDM", mesh.ufl_cell(), 1) DG = ...
Python
1
import requests import sys import json try: n = float(sys.argv[1]) except: sys.exit("Command-line argument is not a number") if len(sys.argv) != 2: sys.exit("Missing command-line argument") # elif not float(sys.argv[1]): # sys.exit("Command-line argument is not a number") else: # response = re...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2024 Alibaba Group Holding Ltd. # # 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-...
Python
1
!((a, c2) = iadd_cout(a1, c_int)), def!(c = bor(c1, c2)), ], ); expand.legalize( def!((a, b) = isub_borrow(x, y, b_in)), vec![ def!((a1, b1) = isub_bout(x, y)), def!(b_int = bint(b_in)), def!((a, b2) = isub_bout(a1, b_int)), de...
Rust
0
=> Err( Error::new("cannot return as a LOB locator") ) } } } }; } impl_from_lob!{ ColumnBuffer::CLOB => OCICLobLocator } impl_from_lob!{ ColumnBuffer::BLOB => OCIBLobLocator } impl_from_lob!{ ColumnBuffer::BFile => OCIBFileLocator } impl<'a> FromSql<'a> for RowID { fn ...
Rust
0
]] = source; moons[combo[1]] = dest; } // Apply velocity. for moon in &mut moons { moon.apply_velocity(); } } moons.iter().map(|moon| moon.get_energy()).sum() } fn process_data_a(data: &str) -> u128 { run_moons_a(data, 1000) } fn process_data_b(data...
Rust
0
# Copyright (c) 2022 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 appli...
Python
1
elf { 0: self.0 - other.0 } } } ) } macro_rules! impl_mul_f64 { ($type:ident) => ( impl Mul<f64> for $type { type Output = Self; fn mul(self, other: f64) -> Self { Self { 0: self.0 * other } } } ) } macro_rules! impl_mul_assign_f6...
Rust
0
} } /// Lowers the current precedence level by one. pub fn lower(&self) -> Precedence { match self { Precedence::Comma => Precedence::Comma, Precedence::Yield => Precedence::Comma, Precedence::Assignment => Precedence::Yield, Precedence::Condi...
Rust
0
e, np.array(sizes, dtype=np.float) / stride, np.array(aspect_ratios, dtype=np.float), ) def _generate_anchors(base_size, scales, aspect_ratios): """Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window. """...
Python
1
ns = parse::lex($ident); crate::IDENTS.intern(parse::parse_ident(&tokens)) }}; } macro_rules! get { ($ident:expr, $cxt:expr) => { $cxt.clone() .lookup(ident!($ident)) .expect(&format!("Ident not found: {:?}", $ident)) }; } macro_rules! primitive { ($name:expr, $...
Rust
0
cr1.modify(|_, w| w.re().clear_bit()); } } impl Tx<$USARTX, FullConfig> { /// Returns true if the tx fifo threshold has been reached. pub fn fifo_threshold_reached(&self) -> bool { let usart = unsafe { &(*$USARTX::ptr()) }; usart.isr.r...
Rust
0
se std::fmt; use log4rs; use log::{info, error, debug}; use byteorder::{LittleEndian, ReadBytesExt}; #[derive(Debug)] enum ConvertError { IoError(io::Error), NodeID, SubStep, Step, FileStep, } impl From<io::Error> for ConvertError { fn from(error: io::Error) -> Self { ConvertError::Io...
Rust
0
_MMCRXRIS_UCGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCRXRIS_UCGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bi...
Rust
0
fs image. This will download and cache the /// rootfs image from a mirror (based on `base_url()`). pub async fn download_base_image( version: &String, arch: &String, ) -> Result<(), Box<dyn Error + Send + Sync>> { if Path::new(&current_rootfs_tarball(&version, &arch)).exists() { info!("rootfs tarbal...
Rust
0
&str) -> Result<String> { if s.starts_with("/") { lazy_static! { static ref DRIVE_LETTER: Regex = Regex::new(r#"/(?P<letter>[A-Za-z])/"#).unwrap(); } if DRIVE_LETTER.is_match(s) { Ok(DRIVE_LETTER.replace(s, "$letter:\\").replace("/", "\\")) }...
Rust
0
size: u32, pub type_: u32, pub name: __IncompleteArrayField<raw::c_char>, } #[test] fn bindgen_test_layout_vdirent() { assert_eq!( ::std::mem::size_of::<vdirent>(), 8usize, concat!("Size of: ", stringify!(vdirent)) ); assert_eq!( ::std::mem::align_of::<vdirent>(), ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/1/4 19:07 @Author : alexanderwu @File : s3_config.py """ from metagpt.utils.yaml_model import YamlModelWithoutDefault class S3Config(YamlModelWithoutDefault): access_key: str secret_key: str endpoint: str bucket: str
Python
1
class baseconfig(): DEBUG = False SQLALCHEMY_DATABASE_URI = 'sqlite:///test.sqlite3' class localdev(baseconfig): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///test.sqlite3' SECRET_KEY = 'shhh_its secret' SECURITY_TRACKABLE = True SECURITY_TOKEN_AUTHENTICATION_HEADER = 'Authorizatio...
Python
1
import streamlit as st from PIL import Image import pandas as pd import plotly.express as px from streamlit_option_menu import option_menu def port(): with st.sidebar: selected = option_menu( menu_title=" ", options=["HOME","ABOUT ME","PROJECTS","EDUCATION","WHAT I KNOW!"] ) if sele...
Python
1
#!/usr/bin/env python3 import subprocess import time import sys # Test cases to validate test_cases = [ (90595490423, 428759, 211297, "11-digit"), (324625056641, 408337, 794993, "12-digit"), (2626476057461, 1321171, 1987991, "13-digit"), (3675257317722541, 91709393, 40075037, "16-digit"), (7362094...
Python
1
from .drugbank_parser import DrugBankParser from .drugbank_processor import DrugBankProcessor
Python
1
r supports setting media type (only used by ARM ethernet) pub const IFF_AUTOMEDIA: u32 = libc::IFF_AUTOMEDIA as u32; // /// Echo sent packets (testing feature, CAN only) // pub const IFF_ECHO: u32 = libc::IFF_ECHO as u32; // /// Dialup device with changing addresses (unused, BSD compatibility) // pub const IFF_DYNAMIC:...
Rust
0
_iter(new_constraints), TyEnv::new()) { // Ok(env) => env, // Err(_) => return false, // }; // for id in new.map().keys() { // if new.ty_of(*id) != prev.ty_of(*id) { // return false; // ...
Rust
0
ub fn is_cpdacbuf1_8(&self) -> bool { *self == CPDACBUF1_A::CPDACBUF1_8 } #[doc = "Checks if the value of the field is `CPDACBUF1_9`"] #[inline(always)] pub fn is_cpdacbuf1_9(&self) -> bool { *self == CPDACBUF1_A::CPDACBUF1_9 } #[doc = "Checks if the value of the field is `CPDACB...
Rust
0
ion_logits.device) self.fusion_params.fusion_logits.data = fusion_logits def _get_params_as_dict(self) -> Dict[str, Any]: """ 将当前模型参数转换为扁平化字典 Returns: 扁平化的参数字典 """ params = {} # 硬件参数 params['num_pes'] = self.hw_pa...
Python
1
m, front_end_option=test_front_end_option, document_label_map=test_id_table ) ) dataframe = pd.DataFrame( index=["Documents", "Cosine Similarity"], columns=[1, 0], data=[["F3.txt", "F1.txt"], [1., .42265]] ) dataframe = dataframe.transpose().sort...
Python
1
struct Config { pub groups: Vec<Group>, } const MSG_INVALID_GROUP_REF: &str = "GroupRef refers to nonexistent group"; const MSG_CIRCULAR_REF: &str = "group dependencies have cycle"; fn dfs(graph: &[Vec<usize>], used: &mut [u8], has_cycle: &mut bool, v: usize) { used[v] = 1; for &w in &graph[v] { ...
Rust
0
ts); let common = UniformCommon { color: sys.color, offset: vec2same(0.0), }; let un = ProgramUniformValues::new(0.0, gl::TRIANGLES); let buffer = sys.circle_buffer.get_info(self.verts.len()); Uniforms { sys, common, un...
Rust
0
x| x.to_min_max()).collect(), 3)); current.clear(); } probabilties } pub fn calculate(filters: &Vec<Option<i32>>) -> Vec<(Vec<MinMax<i32>>, i32)> { let min_price: i32 = filters.get(0).unwrap().unwrap_or(90); let max_price: i32 = filters.get(0).unwrap().unwrap_or(110); let mut results: Vec<(Vec<MinMax<i32...
Rust
0
import sys from copy import deepcopy from utils import * from collections import defaultdict inp = sys.stdin.read() sample = """COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L K)YOU I)SAN """ s = lmap(lambda i: tuple(i.split(')')), regular_process(inp)) orbits = defaultdict(list) for a, b in s: orbits[a].append(b) ...
Python
1
from typing import Callable import pytest import torch pytest.importorskip("torch.cuda") from .test_setup import DTYPES, DTYPE_TO_TOLS, PARAMS, SEED from flex_sae import ( triton_hierarchical_sae_loss, hierarchical_sae_loss, triton_topk_sae_loss, topk_sae_loss, ) @pytest.fixture(autouse=True) def _se...
Python
1
s.assume_init() } } } impl ::std::cmp::PartialEq for NoDebug { fn eq(&self, other: &NoDebug) -> bool { self.c == other.c } } /// This should derive Debug/Hash/PartialEq/Eq because the padding size is less than the max derive /// Debug/Hash/PartialEq/Eq impl for arrays. However, ...
Rust
0
CONTENT_TYPE) .max_age(3600); App::new() .wrap(cors) .data(data.clone()) .service(index) .service(get_count) .service(increment) .service(decrement) }) .bind(server_addr)? .run() .await }//! The most common usage of SNAFU — an enumeration of possible errors. //! //...
Rust
0
queue_id = 2 slice_number = 2 out_port = self.slice_ports[dpid][slice_number] actions = [parser.OFPActionSetQueue(queue_id),parser.OFPActionOutput(out_port)] match = self.set_match(parser, in_port, src, dst, pkt) self.add_flow(...
Python
1
at!("Something bad happened: {:?}", err).to_string(), StatusCode::INTERNAL_SERVER_ERROR, )) }, } } fn with_private_key( priv_key: Vec<u8>, ) -> impl Filter<Extract = (Vec<u8>,), Error = Infallible> + Clone { warp::any().map(move || priv_key.clone()) } #[tokio::main] asy...
Rust
0
# coding=utf-8 """ MongDB说明 ( 类比 Mysql ) : Mysql 有数据库和表的概念 在 MongoDB 中是数据库和集合的概念 查询: Mysql: select * from Table where 1=1 MongoDB: db.collection.find({'key':'value'}) 删除: Mysql: delete from Table where 1=1 MongoDB: db.collection.deleteOne({'key':'va...
Python
1
#!/usr/bin/python # -*- coding: UTF-8 -*- from typing import List permutations_list = [] # 全局变量,用于记录每个输出 def permutations(nums: List, n: int, pick_count: int): """ 从nums选取n个数的全排列 回溯法,用一个栈记录当前路径信息 当满足n==0时,说明栈中的数已足够,输出并终止遍历 :param nums: :param n: :param pick_count: :return: """ ...
Python
1
elds: Dict[str, Field] = {} tokens = [Token(t) for t in tokens] if upos_tags: for t, x in zip(tokens, upos_tags): t.tag_ = x text_field = TextField(tokens, self._token_indexers) fields["tokens"] = text_field if dependencies is not None: ...
Python
1
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def input_ListNone(arr: []): if not arr: return None head = ListNode(arr[0]) current = head for val in arr[1:]: current.next = ListNode(val) current = current.next retu...
Python
1
access enabled"] DSP_DRAM3_ACCESS_ENABLE = 1, } impl From<DSP_DRAM3_ACCESS_A> for bool { #[inline(always)] fn from(variant: DSP_DRAM3_ACCESS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DSP_DRAM3_ACCESS`"] pub type DSP_DRAM3_ACCESS_R = crate::R<bool, DSP_DRAM3_ACCESS_A>; impl DS...
Rust
0
vel='ERROR') as logs: enc.main() self.assertEqual(e.exception.code, 1) r = r'.*Statespace 2\^[0-9]+ not large enough to accommodate [0-9]+ states.*' self.assertTrue(any(re.match(r, log) for log in logs.output)) def test_encoding_too_small(self): with unit...
Python
1
field. /// TODO(H2CO3): check if field is numeric if bounded? fn field_def(field: &Field) -> Result<TokenStream> { let ty = &field.ty; let min_incl = meta::magnet_name_value(&field.attrs, "min_incl")?; let min_excl = meta::magnet_name_value(&field.attrs, "min_excl")?; let max_incl = meta::magnet_name_v...
Rust
0
await?) } // TODO verify if this really works without auth /// Get a stream of the public timeline pub async fn streaming_public(&self) -> Result<EventReader> { let mut url: url::Url = self.route("/api/v1/streaming")?; { let mut qpm = url.query_pairs_mut(); qpm.append_pair("stream", "public"); } str...
Rust
0
# coding: utf-8 import sys import os import json import time sys.path.append(os.getcwd() + "/class/core") import mw import db cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\'' info = mw.execShell(cmd) p = "/usr/local/lib/" + info[0].strip() + "/site-packages" sys.path.append(p) def ...
Python
1
""" 语义空间分析模块 提供高级语义空间分析和可视化功能,包括: - 多维度降维对比 - 语义相似性网络 - 语义演化分析 - 语义聚类和漂移检测 - 交互式3D可视化 """ import logging from typing import List, Dict, Any, Optional, Tuple, Union import numpy as np import pandas as pd from sklearn.metrics.pairwise import cosine_similarity from sklearn.manifold import TSNE from sklearn.decomposition...
Python
1
import json import os import socket import subprocess import sys import time import urllib.request def get_free_port(): s = socket.socket() s.bind(('', 0)) port = s.getsockname()[1] s.close() return port def req(method, url, data=None): if data is not None: data = json.dumps(data).en...
Python
1
import os from .common import * # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'accountant', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT':...
Python
1
/// Returns the root hash of the tree (a digest for the entire store which /// proofs can be checked against). If the tree is empty, returns the null /// hash (zero-filled). pub fn root_hash(&self) -> Hash { self.use_tree(|tree| tree.map_or(NULL_HASH, |tree| tree.hash())) } /// Applies a...
Rust
0
pub _unused2: [libc::c_char; 20], } pub type __off64_t = libc::c_long; pub type _IO_lock_t = (); pub type __off_t = libc::c_long; /* Copyright 2013 Google Inc. 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 o...
Rust
0
return ( m.GenCapacityInTP[g, t] * m.gen_availability[g] * m.gen_max_capacity_factor[g, t] ) else: return m.GenCapacityInTP[g, t] * m.gen_availability[g] mod.DispatchUpperLimit = Expression(mod.GEN_TPS, rule=DispatchUpperLimit_expr)...
Python
1
= r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct SY_PD_PCH_TUNER...
Rust
0
ypes::{PeerId, Uuid}, futures::{FutureExt, StreamExt}, }; use crate::{harness::profile::ProfileHarness, tests::timeout_duration}; /// This makes a custom BR/EDR service definition that runs over L2CAP. fn service_definition_for_testing() -> ServiceDefinition { let test_uuid: Uuid = "f0c451a0-7e57-1111-2222-12...
Rust
0
) query_output = query_outputs.last_hidden_state language_model_inputs = self.language_projection(query_output) language_attention_mask = torch.ones( language_model_inputs.size()[:-1], dtype=torch.long, device=language_model_inputs.device ) if input_ids is N...
Python
1
g!("Handling get basic info request"); // TODO implement versions for real const SPYWARE_VERSION: u32 = 1; GetBasicInfoResponse { version: SPYWARE_VERSION, arch: get_arch(), target_os: get_target_os(), operating_system_version: get_running_os_info(), pointer_width: ge...
Rust
0
println!("[{}_Factory]", serial_number); println!("fx = {}", p.fx); println!("fy = {}", p.fy); println!("cx = {}", p.cx); println!("cy = {}", p.cy); println!("k1 = {}", p.k1); println!("k2 = {}", p.k2); ...
Rust
0
import sys, os, shutil, inspect; CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))); ROOT = os.path.dirname(CURRENTDIR); sys.path.append(ROOT); from api.apt import Apt; from api.config import Config; from api.downloadinstall import DownloadInstall; from api.log import Log; from api...
Python
1
from __future__ import absolute_import, division, print_function from libtbx import easy_pickle from libtbx.utils import get_svn_revision, get_build_tag, plural_s from operator import itemgetter import glob, os, sys from six.moves import cStringIO as StringIO class analyse(object): def __init__(self): self.n_hk...
Python
1
 :Xc @@sddlmZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddlmZejeZddddddedd d ZdS( i(tabsolute_importN(tInstallRequirement(t COMMENT_RE(t...
Python
1
pub fn builder(config: NodeConfig) -> NodeBuilder { NodeBuilder { config } } } #[inline] async fn process_event(event: Event, network: &mut Network, peers: &mut PeerList) { match event { Event::EndpointAdded { epid, .. } => endpoint_added_handler(epid, network).await, Event::Endpoint...
Rust
0
nstants .into_iter() .chain(fields) .collect::<Vec<_>>() .join("\n"); Ok(representation) } pub fn const_string(&self, crate_prefix: &str) -> String { let mut output = Vec::<String>::new(); for field in &self.fields { if let Som...
Rust
0
er': BearerAuth, } # Define v4 signers depending on if CRT is present if HAS_CRT: from botocore.crt.auth import CRT_AUTH_TYPE_MAPS AUTH_TYPE_MAPS.update(CRT_AUTH_TYPE_MAPS) else: AUTH_TYPE_MAPS.update( { 'v4': SigV4Auth, 'v4-query': SigV4QueryAuth, 's3v4': S3Sig...
Python
1
(13, r); m } <filename>test/1.1.0/doc/doc_trpl_generics_md_0003.rs<gh_stars>1-10 fn main() { let x: Option<i32> = Some(5); let y: Option<f64> = Some(5.0f64); } use std::{ any::Any, collections::{BTreeMap, BTreeSet}, fmt, time::Duration, }; use crate::{Model, ModelDim}; macro_rules! err { ...
Rust
0
-> bool { if key == OsStr::new("WSL_INTEROP") { sanity_check_wsl_interop(value) } else { sanity_check_general_wsl_envs(value) } } fn sanity_check_wsl_interop(value: &OsStr) -> bool { let inner = || -> Result<bool> { let safe_path = regex::Regex::new("^/run/WSL/[0-9]+_interop$")...
Rust
0
_point!(u64); impl_unsigned_2d_data_point!(usize); impl_signed_2d_data_point!(i8); impl_signed_2d_data_point!(i16); impl_signed_2d_data_point!(i32); impl_signed_2d_data_point!(i64); impl_signed_2d_data_point!(isize); impl_float_3d_data_point!(f32); impl_float_3d_data_point!(f64); impl_unsigned_3d_data_point!(u8); impl...
Rust
0
BLE}; mod group; pub use self::group::GroupExt; pub use self::group::{Group, GroupClass, NONE_GROUP}; mod layer; pub use self::layer::LayerExt; pub use self::layer::{Layer, LayerClass, NONE_LAYER}; mod pipeline; pub use self::pipeline::GESPipelineExt; pub use self::pipeline::{Pipeline, PipelineClass, NONE_PIPELINE};...
Rust
0
def replace_time(match): '''replace the format of the time to it's value''' #Python time function differs from adium time #so we try to convert it but if that fails, #we fallback to simple time format = match.groups()[0] result = time.strftime(match.groups()[0]) if result == format: ...
Python
1
8(expr.span, v as u8)); } else { cx.span_err(expr.span, "non-ascii char literal in bytes!"); err = true; } } _ => { cx.span_err(expr.span, "unsupported literal in bytes!"); ...
Rust
0
from django.urls import path from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('course' , views.CourseViewset) router.register('review' , views.ReviewViewset) app_name = 'course' urlpatterns = [ path('course/<str:id>/rate_course/' , views.CourseViewset...
Python
1
&'a mut W { self.variant(HPM_LFSR_SIZEW::_011) } #[doc = "LFSR 15, tap mask 111010000000000"] #[inline] pub fn _100(self) -> &'a mut W { self.variant(HPM_LFSR_SIZEW::_100) } #[doc = "LFSR 17, tap mask 11110000000000000"] #[inline] pub fn _101(self) -> &'a mut W { ...
Rust
0
}; assert_eq!(frame, expected.0, "decoded frame matched"); assert_eq!(len, expected.1, "decoded frame len matched"); assert_eq!(buf.len(), expected.1, "output buffer len matched"); assert_eq!(buf.len() + bytes.len(), total_len, "total len matched"); } fn decode_and_verify_padded_some(bytes: &B...
Rust
0
ob::glob; use std::fs; use std::path::{Path, PathBuf}; mod parser; const USAGE: &str = r#" elm-strip-comments USAGE: elm-strip-comments Module.elm > ModuleNoComment.elm elm-strip-comments --replace src/*.elm "#; /// Main entry point. fn main() { parse_args() .and_then(run) .unwrap_or_els...
Rust
0
_func(): pass def not_callback_func(): pass assert ha.is_callback(callback_func) assert HassJob(callback_func).job_type == ha.HassJobType.Callback assert ha.is_callback_check_partial(functools.partial(callback_func)) assert HassJob(functools.partial(callback_func)).job_type == ha.H...
Python
1
import sys import os from abc import ABC from xml.etree import ElementTree from ..common import * def translate_bcp47(tag): subtags = tag.lower().split('-') if subtags[0] == 'en': return 'eng' elif subtags[0] == 'zh': if mult_in(('cn', 'sg', 'my', 'hans'), subtags[1:]): return ...
Python
1
al_answer async def chat_loop(self): """Run an interactive chat loop""" print("\nMCP Client Started!") print("Type your queries or 'quit' to exit.") while True: try: query = input("\nQuery: ").strip() if query.lower() == "quit": ...
Python
1
eshold=flow_threshold, cellprob_threshold=cellprob_threshold, do_3D=False ) # 记录检测到的细胞数量 unique_ids = np.unique(masks)[1:] # 跳过0(背景) cell_count = len(unique_ids) logger.info(f"检测到 {cell_count} 个细胞") ...
Python
1
total: {}", date_times.unwrap().len()); //! } //! ``` if self.ge(&end) { return Err(String::from( "start date/time is greater than end date/time", )); } let time_delta = end.signed_duration_since(*self); let mut rng = rand::thread_r...
Rust
0
from c3.signal.pulse import Envelope, EnvelopeNetZero from c3.c3objs import Quantity as Qty from c3.libraries import envelopes import numpy as np import pytest flux_env = Envelope( name="flux", desc="Flux bias for tunable coupler", shape=envelopes.rect, params={ "amp": Qty(value=0.1, unit="V"),...
Python
1
redictions_ / len(SEED) train[target_cols] = oof test[target_cols] = predictions # In[41]: len(target_cols) # In[42]: target # In[43]: valid_results = train_targets_scored.drop(columns=target_cols).merge(train[['sig_id']+target_cols], on='sig_id', how='left').fillna(0) y_true = train_targets_scored[targe...
Python
1
True, result['max_val'] return False, result['max_val'] def click_target(self, target_path, threshold, flag=True, timeout=30.0, offset=(0, 0, 0, 0), retry_in_map: bool = True, clicks=1, delay=0.05): """ 说明: 点击指定图片 参数: :param target_path:图片地址 :par...
Python
1
__all__ = ["router"] from fastapi import APIRouter, Depends from src import schemas from src import repositories as reps from src.utils import messages from src.middleware.auth_guard import get_id router = APIRouter(prefix="/user", tags=["Users"]) @router.get( "/me", responses={ 200: {"model": sche...
Python
1
, "[{}]", name), Type::Set(name) => write!(f, "{{{}}}", name), Type::Dict(key, value) => write!(f, "{{{}: {}}}", key, value), Type::Function(args, ret) => { write!(f, "(fn ")?; for (i, n) in args.iter().enumerate() { if i != 0 { ...
Rust
0
teau = make_schedulers(optimizer, CONFIG["train"]["warmup_epochs"], epochs) stopper = EarlyStopping(patience=CONFIG["train"]["early_stop_patience"]) best_val_acc = -1.0 use_amp = (device.type == 'cuda') scaler = torch.cuda.amp.GradScaler(enabled=use_amp) for epoch in range(epochs): if epoch ...
Python
1
Elem; fn index(&self, index: isize) -> &Self::Output { ListBase::get(self, index).unwrap() } } impl #impl_generics List for #name #ty_generics #where_clause { } }; expanded.into() } #[proc_macro_derive(ListMut)] pub fn derive_listmut(input: Tok...
Rust
0
JSONRenderer', ) } SIMPLE_JWT = { 'ROTATE_REFRESH_TOKENS': True, 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), 'AUTH_COOKIE': 'access_token', 'AUTH_COOKIE_DOMAIN': None, 'AUTH_COOKIE_SECURE': not DEBUG, # True in production with HTTPS 'AUT...
Python
1
//println!("{}", x1); //Error,x1已经失效了无法被用 } let y = &mut x; //此处开始,则前面涉及x的相关引用(包括x)也将无法再被使用,直到y不被使用了 //x.push_str(""); //Error //y = &mut z; //Error y.push_str("aa"); println!("{}", x); //println!("{}", y); //Error,可变引用的使用在不可变引用的使用之后,这是不行的 ...
Rust
0
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) pre = [1]*(n+1) pre[0] = nums[0] post = [1]*(n+1) post[n-1] = nums[n-1] for i in range(1,n): pre[i] = pre[i-1]*nums[i] for i in range(n-2,-1,-1): ...
Python
1
: Option<String>, } /// Helper trait for inserting different `Action`s with different `ActionType`s into a `BTreeMap` /// /// Using this trait will allow us to catch simple misconfigurations in Actions during compile time. trait ActionInsertions { /// Inserts an action with `ActionType::Exec` into a `BTreeMap` ...
Rust
0
.iter() .rev() .flat_map(|byte| { (0..8).rev().map(move |i| Choice::from((byte >> i) & 1u8)) }) .skip(4) { acc = acc.double(); acc += AffineNielsPoint::conditional_select(&zero, &self, bit); } acc ...
Rust
0
# To jest główny plik gry from Class_files.Chosen_class_write import write_class from locations.Write_map_chosen import write_chosen_map as map_write from locations.Read_map_chosen import RM from locations.Create_random_map_function import create_map from Movement import movement_2 def Game(): while True: # Pun...
Python
1
rate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [extmem_icache_autoload_sct1_addr](extmem_icache_autoload_sct1_addr) module"] pub type EXTMEM_ICACHE_AUTOLOAD_SCT1_ADDR = crate::Reg<u32, _EXTMEM_ICACHE_AUTOLOAD_SCT1_ADDR>; #[allow(m...
Rust
0
#3.17 dictionary #key-value 19=> çorum cities=['kocaeli', 'istanbul'] plakalar =[41, 34] """ print(plakalar[cities.index('kocaeli')]) #41 print(plakalar[cities.index('istanbul')]) #34 yazar plakalar={'kocaeli':41, 'istanbul':34} #{'key':'value'} print(plakalar['kocaeli']) print(plakalar['istanbul']) plakalar['a...
Python
1
assert_eq!(seg_fixed_length.clone_with_new_end(2).length(), None); assert_eq!(seg_fixed_length.clone_with_new_end(1).length(), None); let seg_no_length = ReadSegment { offset: 2, length: None, kind: SegmentType::Template }; assert_eq!(seg_no_length.clone_with_new_end(10).length().unwrap(), 8); ...
Rust
0
''' Arithmetic Functions np.min(x) np.max(x) np.argmin(x) np.argmax(x) np.sqrt(x) np.sin(x) np.cos(x) np.cumsum(x) ''' import numpy as np # * 1-D Arrays var = np.array([10,2,13,4,7]) maximum = np.max(var) # will find the maximum value of the array minimum = np.min(var) # will find the minimum value of the array max_p...
Python
1
Ok(( i, Buttons::Set { air_left, air_right, ground_left, ground_right, }, )) } fn line_buttons(i: &str) -> IResult<Buttons> { let (i, _) = tag("buttons")(i)?; if preceded(space1::<&str, ()>, not_line_ending)(i).is_ok() { c...
Rust
0