text
string
label_name
string
labels
int64
drop(new_node_ref); node_info::set_pred_info(Arc::clone(&new_node), deep_cloned_new_node.clone()); println!("first_node at join: {:?}", new_node.lock().unwrap()); return; } drop(new_node_ref); // ダウンしているノードの情報が与えられることは想定しない let tyukai_node = endpoints::rrpc_call__g...
Rust
0
_path}文件内容成功") return content else: logger.warning(f"{file_path}文件不存在") return default_content except Exception as e: logger.error(f"读取{file_path}文件失败: {str(e)}") return default_content def calculate_tokens(self, in...
Python
1
# Regular Expressions # import re # MATCH my_string = "Esta es la lección número 7: Lección llamada Expresiones Regulares" my_other_string = "Esta no es la lección número 6: Manejo de ficheros" match = re.match("Esta es la lección", my_string, re.I) print(match) print(match.span()) # NOS DICE QUE ESTA ENTRE LA CADE...
Python
1
class Solution: def intToRoman(self, num: int) -> str: """ Convert an integer to a Roman numeral. Args: num: An integer between 1 and 3999 Returns: A string representing the Roman numeral version of the input """ dict = {}...
Python
1
ontent_type}" ) if not progress: return True return progress.due_time == None class CardBelongsToRequestingUser(BasePermission): def has_permission(self, request, view): if "pk" not in view.kwargs: return False card = view.get_object() u...
Python
1
let contents = match clip { Some(line) => password .get(line.saturating_sub(1)) .ok_or(format!("File at line {} was empty", line))?, None => password.first().ok_or("Vec was empty")?, }; ...
Rust
0
class Warehouse: """ Lớp đại diện cho kho hàng """ def __init__(self, id_warehouse, name, address, phone): """ Khởi tạo đối tượng kho hàng Args: id_warehouse: ID kho hàng name: Tên kho address: Địa chỉ kho phone: Số điện thoại liê...
Python
1
const OS_TYPE_DESCRIPTOR: &[u8; 4] = b"Objc"; /// 'VlLs' = List const OS_TYPE_LIST: &[u8; 4] = b"VlLs"; /// 'doub' = Double const OS_TYPE_DOUBLE: &[u8; 4] = b"doub"; /// 'UntF' = Unit float const OS_TYPE_UNIT_FLOAT: &[u8; 4] = b"UntF"; /// 'TEXT' = String const OS_TYPE_TEXT: &[u8; 4] = b"TEXT"; /// 'enum' = Enumerated...
Rust
0
## @file # This file is used to provide board specific image information. # # Copyright (c) 2023 - 2025, Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent # ## # Import Modules # import os import sys import time sys.dont_write_bytecode = True sys.path.append (os.path.join(...
Python
1
from mlc import utils import os import configparser def preprocess(i): os_info = i['os_info'] env = i['env'] logger = i['automation'].logger # Initialize ConfigParser config = configparser.ConfigParser() if env.get('MLC_MLPERF_POWER_SERVER_CONF_FILE', '') != '': server_config_file = ...
Python
1
# -*- coding: utf-8 -*- from collections import defaultdict import utils import numpy as np import random import gc class Action(object): def __init__(self): self.n = 0 # 初始化为1,使得概率分布smooth一丢丢 self.w = 0 # W(s, a) : total action value self.q = 0 # Q(s, a) = N / W : action value ...
Python
1
-> Vec<Tag>; fn to_lineproto(&self) -> String; fn build(&self, buffer: &mut String) -> std::io::Result<usize>; } // measurement[,tag=val[,tag=val]] field=value[,field=value] /// Escapes the provided tag value `s` and adds the newly escaped values to `buff`. /// > NOTE: Source for this is an adaptation from s...
Rust
0
Script IDs const COINGECKO_DATA_SOURCE_DS: i64 = 1; #[no_mangle] fn prepare_impl(input: Input) { // Calldata should be something like "https://gateway-endpoint.example BTC,ETH,UNI" oei::ask_external_data(COINGECKO_DATA_SOURCE, COINGECKO_DATA_SOURCE_DS, &[input.endpoint, input.symbols.join(",")].join(" ").as_by...
Rust
0
name__ == '__main__': batch_size = 16 train_data = SingleLabel(data_folder="/home/.../RFMiD_All_Classes_Dataset/1. Original Images/a. Training Set", label_path="/home/.../RFMiD_All_Classes_Dataset/2. Groundtruths/a. RFMiD_Training_Labels.csv", csv_name = "train.c...
Python
1
{ ($string_semiring: ident) => { impl CommonDivisor<$string_semiring> for LabelCommonDivisor { fn common_divisor( w1: &$string_semiring, w2: &$string_semiring, ) -> Result<$string_semiring> { let mut iter1 = w1.iter(); ...
Rust
0
ct Freq100MHz; impl Frequency for Freq100MHz { fn frequency() -> u32 { 100000000 } } /// 16MHz `Frequency` #[derive(Debug)] pub struct Freq16MHz; impl Frequency for Freq16MHz { fn frequency() -> u32 { 16000000 } } /// 1MHz `Frequency` #[derive(Debug)] pub struct Freq1MHz; impl Frequenc...
Rust
0
impl_expected = ["generic::Bar", "generic::Foo"]; let expected = ["generic::Baz<generic::Bar>", "generic::Baz<generic::Foo>"]; test( "generic", "test_bound", "target_bound", &impl_expected, &expected, ); test( "generic", "test_where_clause", ...
Rust
0
ents') # Drop project_versions table op.drop_index('idx_project_version_number', table_name='project_versions') op.drop_index(op.f('ix_project_versions_project_id'), table_name='project_versions') op.drop_table('project_versions') # Drop project_members table op.drop_index('idx_project_member_...
Python
1
/ 50] * dexhand.n_dofs)), "medium_pose": torch.tensor(np.array([np.pi / 10] * dexhand.n_dofs)), } # Inspire hand 특별 포즈 추가 if dexhand.name == "inspire": inspire_special = torch.zeros(dexhand.n_dofs) if dexhand.n_dofs > 9: inspire_specia...
Python
1
ass__.__name__ # print(classname) if classname.find('Conv') != -1 or classname.find('ConvTranspose') != -1: init.kaiming_normal_(m.weight.data, a=0, mode='fan_in', nonlinearity='relu') if m.bias is not None: m.bias.data.zero_() elif classname.find('Linear') != -1: init.ka...
Python
1
size, end_idx: usize, ) -> ((usize, usize), (usize, usize)) { debug_assert!(start_idx <= end_idx); debug_assert!(self.len() > 0); let mut accum_char_idx = 0; let mut idx = 0; // Find left child and info for info in self.info()[..(self.len() - 1)].iter() { ...
Rust
0
EitherRefMut<'_, T> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { match self { EitherRefMut::Std(std) => std.deref_mut(), EitherRefMut::Locked(lck) => unsafe { &mut *lck.guard.deref().get() }, } } } #[cfg(test)] mod refs_tests { use supe...
Rust
0
Err(err()), (_, _, Some(old_k)) if old_k != k => Err(err()), _ => Ok((m, n, k)), } } fn get_inner(outer: usize, inner: Option<usize>, shape: &[usize], trans: bool) -> ::std::result::Result<usize, String> { if trans { return get_outer(outer, inner, shape, false); }; let (i, o) = shape.iter().fold((1, 1), |(m...
Rust
0
rm(); if self.show_output() || prompt_confirmation { println!("\n{} release status:", bin_name); println!(" * Current exe: {:?}", bin_install_path); println!(" * New exe release: {:?}", target_asset.name); println!(" * New exe download url: {:?}", target_asset....
Rust
0
l { channel_id: s.cid, part: carl.1, // Carl wants to withdraw receiver: cosmwasm_std::Addr::unchecked(ALICE), }; let sig = sign(&withdrawal, &carl.0); // Carl signed assert_eq!( do_withdraw(deps.as_mut(), &withdrawal, &sig).unwrap_err(), ContractError::UnknownDeposi...
Rust
0
as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(ibv_packet_pacing_caps), "::", stringify!(qp_rate_limit_max) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<ibv_packet_pa...
Rust
0
content=instance.ttwid_conf["data"], headers=instance.ttwid_headers, ) response.raise_for_status() ttwid = httpx.Cookies(response.cookies).get("ttwid") if ttwid is None: raise APIResponseError( _("ttwid: 检查没有通过,...
Python
1
} // Texturing. if (references.test(CombinerReference::TEXEL_0) && self.texture_0.is_some()) || (references.test(CombinerReference::TEXEL_1) && self.texture_1.is_some()) { write!(glsl, "ivec2 texCoord = ivec2(round(v_texCoord));\n").unwrap(); } i...
Rust
0
r"not a valid item", // 21 r"no way down", // 22 ]).unwrap(), detect_enemy: Regex::new(r"(?i)the.*?(?P<enemy>\w)").unwrap(), detect_item: Regex::new( r"You now have (?P<num>a|\d*)[ |[\w^a]](?P<item>.*?)\((?P...
Rust
0
4SET = crate::Reg<u1ep4set::U1EP4SET_SPEC>; #[doc = "U1EP4SET register"] pub mod u1ep4set; #[doc = "U1EP4INV register accessor: an alias for `Reg<U1EP4INV_SPEC>`"] pub type U1EP4INV = crate::Reg<u1ep4inv::U1EP4INV_SPEC>; #[doc = "U1EP4INV register"] pub mod u1ep4inv; #[doc = "U1EP5 register accessor: an alias for `Reg<...
Rust
0
} } pub fn map_stage_flags(stages: pso::ShaderStageFlags) -> vk::ShaderStageFlags { use self::pso::ShaderStageFlags; let mut flags = vk::ShaderStageFlags::empty(); if stages.contains(ShaderStageFlags::VERTEX) { flags |= vk::SHADER_STAGE_VERTEX_BIT; } if stages.contains(ShaderStageFlags:...
Rust
0
import contextlib import json from typing import Any, Dict, Iterator, cast from opentrons.protocol_api import InstrumentContext def load_config(name: str) -> Dict[str, Any]: """Load a configuration file""" with open(name, "rb") as f: return cast(Dict[str, Any], json.load(f)) @contextlib.contextmanag...
Python
1
_base_ = [ '../rotated_retinanet/rotated_retinanet_obb_r50_fpn_1x_dota_le135.py' ] model = dict( bbox_head=dict( reg_decoded_bbox=True, loss_bbox=dict( _delete_=True, type='GDLoss_v1', loss_type='kld', fun='log1p', tau=1, l...
Python
1
r.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') parser.add_argument('--augment', action='store_true', help='augmented inference') parser.add_argument('--verbose', action='store...
Python
1
en | | | 146 | Christmas & Winter | Decoration | Apartment & Balcony | | | 147 | Christmas & Winter | Food and Wine | Online Supermarket w. Delivery | | | 148 | Christmas & Winter | Food and Wine | Online Store | | | 149 | Christmas & Winter | Fireplace & Wood Burning Stove | | |...
Python
1
numpy(token_has_space[hidden_acts[:, f_id]>0]), barmode="overlay", marginal="box", title="Acts with(out) space").show() i = 0 make_feature_vis_gradio(token_df.batch.iloc[i], token_df.pos.iloc[i], f_id) # %% # Feature 1 ends_with_ed = vocab_df.str_token.apply(lambda s: s.endswith("ed")).values px.histogram(to_numpy(fea...
Python
1
import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout from tensorflow.keras.datasets import mnist # Загрузка датасета MNIST (цифры 0-9) (x_train, y_train), (x_test, y_test) = mnist.load_d...
Python
1
) results_new_code = query_newcode_any("newcode_crawler", newcode_columns, position = position, company = company, description = city) results_xiaohongshu = query_xiaohongshu_any("xiaohongshu_table", xiaohongshu_columns, position = position, city = city, company = company) # 输出结果 ...
Python
1
#!/usr/bin/python3 #-*- coding:utf-8 -*- #Date:20-10-2017 #Author:jhinno #Version=.3 import sys sys.path.append("..") from tools.tools import * import unittest import main class Testdesktopclose(unittest.TestCase): """测试 appform 关闭桌面 case:""" def setUp(self): print("开始测试关闭桌面【desktopClose api】 ..."...
Python
1
mp = true, _ => { generate_bmp = false; println!("No bmps"); } } } } let reader = BufReader::new(File::open(full_name).unwrap()); let mut res: AocResult = AocResult { day: 6, phase_1: None, ...
Rust
0
e_add_bias() { let mut m1 = TMap::new(); let mut m2 = TMap::new(); let op1 = map::Op::Rm { clock: Dot::new(1, 1).into(), keyset: vec![102].into_iter().collect(), }; let op2 = m2.update(102, m2.get(&102).derive_add_ctx(2), |map, ctx| { map.update(42, ctx, |reg, ctx| reg.writ...
Rust
0
ua,'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'sec-fetch-site': 'none', 'sec-fetch-mode': 'navigate', 'sec-fetch-user': '?1', 'sec-fetch-dest': 'document', 'accept-encoding': 'gzip, deflate, br', 'accept-language':...
Python
1
), ( 6109, ("UDJ", "UKLU", 48.634300231933594, 22.263399124145508), ), (6110, ("CSH", "ULAS", 65.0299987793, 35.7333335876)), (6111, ("CEE", "ULBC", 59.273601532, 38.015800476100004)), (6112, ("AMV", "ULDD", 69.76329803466797, 61.556400299072266)), (6113, ("KSZ", "ULKK", 61.23580...
Rust
0
) # bsz x 1 bos_embeds = self.llama_model.model.embed_tokens( bos ) # bsz x 1 x embed_dim inputs_embeds = torch.cat( [bos_embeds, p_before_embeds, feature_embeds, p_middle_embeds, obj_feat, p_middle_img_embeds, multi_view, p_after_embeds], dim=1 ) # b...
Python
1
import streamlit as st import requests import geopandas as gpd import folium from folium.features import GeoJsonPopup from streamlit_folium import st_folium from pymongo import MongoClient st.set_page_config(layout="wide") @st.cache_resource def init_connection(): return MongoClient("mongodb+srv://kuquanghuy:qua...
Python
1
import pytest from camdweb.html import Range, RangeS, RangeX from camdweb.utils import process_pool @pytest.fixture(scope='module') def r(): return Range('ABC', 'x') @pytest.mark.parametrize( 'query, result', [({}, ''), ({'to_x': '1'}, 'x<=1'), ({'from_x': '1'}, 'x>=1'), ({'from_x': '1',...
Python
1
category: { text: '后端开发', code: 1, }, title: '全面系统Python3.8入门+进阶 (程序员必备第二语言)', introduction: '语法精讲/配套练习+思考题/原生爬虫实战', img: 'https://img.mukewang.com/szimg/59b8a486000107fb05400300-360-202.jpg', banner: 'https://img.mukewang.com/szimg/5b51c78300015e0220000560.jpg', type: { tex...
Python
1
#!/usr/bin/env python3 # _ ____ ____ ___ ___ _ # / \ / ___| / ___|_ _|_ _| __ _ _ __| |_ # / _ \ \___ \| | | | | | / _` | '__| __| # / ___ \ ___) | |___ | | | | | (_| | | | |_ # /_/ \_\____/ \____|___|___| \__,_|_| \__| # # - from github.com/basnijholt/home-assistant-con...
Python
1
import os import pathlib import subprocess assets = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets") def test_alifestd_join_roots_cli_help(): subprocess.run( [ "python3", "-m", "hstrat._auxiliary_lib._alifestd_join_roots", "--help", ...
Python
1
[KeyCode::W, KeyCode::Up]), backward: Box::new([KeyCode::S, KeyCode::Down]), left: Box::new([KeyCode::A, KeyCode::Left]), right: Box::new([KeyCode::D, KeyCode::Right]), move_sensitivity: 2.0, } } } pub fn camera_movement( mut game_state: ResMut<State<Game...
Rust
0
.PWM0, p.P0_13, NoPin, NoPin, NoPin); // set_period doesnt actually set what you give it, because it only has a // few options from the hardhware so be explicit instead // Div128 is slowest, 125khz still crazy fast for our eyes pwm.set_prescaler(Prescaler::Div128); info!("pwm initialized!"); /...
Rust
0
print("\n\n===================================\n") print("<<<<<<<< CADASTRO DE PRODUTO >>>>>>>>>>") print("\n\n===================================\n") # INPUT DE INFORMAÇÕES Nome_Prod = input("NOME: ") # receber o nome do produto Desc_Prod = input("DESCRIÇÃO: ") #receber a descrição do ...
Python
1
.HMMResult). feature_name: the name of the matching AntismashDomain feature in the same record as this qualifier Returns: None """ assert not isinstance(domain, str) if domain.hit_id == "PKS_AT": self.at_count...
Python
1
r: """Get a logger instance""" return get_logging_manager().get_logger(name) def log_scientific_event( message: str, context: Dict[str, Any], level: str = "INFO" ) -> None: """Log a scientific event for reproducibility""" get_logging_manager().log_scientific_event(message, context, level) ...
Python
1
)> where X: 'static + TeaclaveService<V, U> + Clone + core::marker::Send, { let pool = threadpool::ThreadPool::new(self.n_workers); let listener = std::net::TcpListener::bind(self.addr)?; let mut tls_config_ref = self.tls_config.server_config(); for stream in listener.inc...
Rust
0
(self.as_dvec2() * scale).as_vec2() } } impl crate::TweenValue for glam::UVec2 { const ZERO: Self = Self::ZERO; fn calculate_delta(destination: Self, start: Self) -> Self { destination - start } fn add(self, other: Self) -> Self { self + other } fn scale(self, scale: f...
Rust
0
.push(NetworkBehaviourAction::GenerateEvent(RPCMessage { peer_id, conn_id, event, })) } Err(RateLimitedErr::TooLarge) => { // we set th...
Rust
0
:Year), fromymd(2021, 12, 31) ); assert_eq!( eop(&fromymd(2021, 1, 15), Period::Semiannual), fromymd(2021, 6, 30) ); assert_eq!( eop(&fromymd(2021, 5, 15), Period::Quarter), fromymd(2021, 6, 30) ); assert_eq!( ...
Rust
0
t(lambda: 0) populate_counts(counts, base_fun=base_fun) else: basis_counts = collections.defaultdict(lambda: 0) populate_counts(basis_counts) results = [] def get_result(test_name, test_fun, basis=None): result = { 'fact': test_name, } ...
Python
1
exceeds known input length {}", span, self.s.len() ); } &self.s[span.start()..span.end()] } fn span_lines_str(&self, span: Span) -> &'input str { debug_assert!(span.end() >= span.start()); if span.end() > self.s.len() { pa...
Rust
0
UP_KNOWN_STATUS_CODE_METHOD_NOT_ALLOWED: SoupKnownStatusCode = 405; pub const SOUP_KNOWN_STATUS_CODE_NOT_ACCEPTABLE: SoupKnownStatusCode = 406; pub const SOUP_KNOWN_STATUS_CODE_PROXY_AUTHENTICATION_REQUIRED: SoupKnownStatusCode = 407; pub const SOUP_KNOWN_STATUS_CODE_PROXY_UNAUTHORIZED: SoupKnownStatusCode = 407; pub c...
Rust
0
](dfsr::W) writer structure"] impl crate::Writable for DFSR {} #[doc = "Debug Fault Status Register"] pub mod dfsr; #[doc = "MemManage Fault Address Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](cr...
Rust
0
import unittest from mil.data.datasets import musk1, musk2, protein, elephant, corel_dogs, \ ucsb_breast_cancer, web_recommendation_1, birds_brown_creeper, \ mnist_bags class TestLoadDatasets(unittest.TestCase): def test_load_musk1(self): (x_...
Python
1
from typing import List def convert_currency_multiple( api_key: str, from_currency: str, to_currency: str, amounts: List[float], ) -> str: """ Convert multiple currency amounts from one currency to another using the Amdoren Currency API. :param api_key: API key for the Amdoren Currency API...
Python
1
sg); } fn main() -> Result<(), Error> { let opt = Cli::from_args(); match opt { Cli::Decode => { let stdin = io::stdin(); let mut write = io::stdout(); for line in stdin.lock().split(b'\n') { let mut read = GarbageRemovingReader(Cursor::new(line?));...
Rust
0
MigratedFundsEntry as RustMigratedFundsEntry, MilestonePayloadEssence as RustMilestonePayloadEssence, Output as RustOutput, Payload as RustPayload, ReferenceUnlock as RustReferenceUnlock, RegularEssence as RustRegularEssence, SignatureLockedDustAllowanceOutput as RustSignatureLockedDust...
Rust
0
seed=self.seed, thinking_config=types.ThinkingConfig(thinking_budget=self.thinking_budget) if self.thinking_budget is not None else None, max_output_tokens=128, ) backoff = 1.0 for attempt in range(1, self.max_retries + 1): await se...
Python
1
Paren => Token::LeftParen, Token::LeftBrace => Token::RightBrace, Token::RightBrace => Token::LeftBrace, Token::LeftArrow => Token::RightArrow, Token::RightArrow => Token::LeftArrow, Token::LeftBracket => Token::RightBracket, Token::RightBracket =>...
Rust
0
from sqlalchemy.ext.orderinglist import OrderingList, ordering_list, count_from_0 # Simulate what would happen in a real SQLAlchemy scenario class Bullet: """Simulates a SQLAlchemy model""" def __init__(self, text): self.text = text self.position = None # This would be a Column in SQLAlchemy ...
Python
1
ers, then it's possible to just do the same as prefix-varint and have a tag bit to save binary size // TODO: Semantically this is a sequence of case-folded canonically encoded utf-8 words (though, this is not quite implemented as such here) // This is prime for some kind of dictionary compression. Most applications won...
Rust
0
[IndexMap]. /// /// Text parsed to [IndexMap], where keys are tags and values are queries. /// [IndexMap] used instead [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html) /// because with [IndexMap] it's possible execute queries in defined order what can be important on /// database scheme creatio...
Rust
0
from utils import load_model_and_config model, le, si = load_model_and_config() import json import datetime from gui.utils import load_model_and_config def ask_follow_ups(symptom): print(f"\n🩺 Follow-up questions for: {symptom}") duration = input("📆 How long have you had this symptom? (e.g. 2 days 5 hou...
Python
1
IPool child = self._make_resource(registry, parent=pool) child2 = self._make_resource(registry, parent=pool) result = inst.search(query._replace(interfaces=IPool, limit=1, sort_by='name')) assert res...
Python
1
if isinstance(m, nn.Conv2d): init.kaiming_normal(m.weight, mode='fan_out') if m.bias is not None: init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): init.constant(m.weight, 1) init.constant(m.bias, 0) ...
Python
1
"{k}: {v1}, {v2}, {v3} ", k = fake_key, v1 = fake_values[0], v2 = fake_values[1], v3 = fake_values[2] ); Control::format_vec(fake_key, &fake_values, &mut acc); assert_eq!(acc, expected); } } <reponame>smmalis37/aoc2019 use crat...
Rust
0
road. let mut houses = Vec::new(); for l in empty_sidewalks { let lane = map.get_l(l); let mut dist_along = rand_dist(rng, 1.0, 5.0); while dist_along < lane.lane_center_pts.length() { let (sidewalk_pt, angle) = lane.lane_center_pts.must_dist_along(dist_along); l...
Rust
0
{ let sin_theta = sin_theta(v); if sin_theta == 0.0 { 1.0 } else { linalg::clamp(v.x / sin_theta, -1.0, 1.0) } } /// Compute the value of sine phi for a vector in shading space pub fn sin_phi(v: &Vector) -> f32 { let sin_theta = sin_theta(v); if sin_theta == 0.0 { 0.0 ...
Rust
0
stem_prompt}\n\n일기: {diary_entry}\n공감 메시지:" # class StoppingCriteriaSub(StoppingCriteria): # def __init__(self, stops=[], encounters=1): # super().__init__() # self.stops = [stop for stop in stops] # self.sentence_ender = re.compile(r'[.?!]$') # def __call__(self, input_ids: torch.Lon...
Python
1
from fastapi import APIRouter, Depends from schemas import webtoon_schemas, user_schemas from sqlalchemy.orm import Session from models.database import get_db from auth.oauth import get_current_user from util import webtoon_util api_webtoon = APIRouter(prefix="/api/webtoon") @api_webtoon.post('/create') def create_w...
Python
1
from fastapi import FastAPI, Request import time import logging import os from .env_wrapper import searchqa_env_server from .model import * from .utils import debug_flg app = FastAPI(debug=debug_flg) VISUAL = os.environ.get("VISUAL", "false").lower() == "true" if VISUAL: print("Running in VISUAL mode") from...
Python
1
from lc import * # https://leetcode.com/problems/find-the-winner-of-the-circular-game/discuss/1152420/Python3-simulation class Solution: def findTheWinner(self, n: int, k: int) -> int: return reduce(lambda a,x:(a+k)%x,range(2,n+1),0)+1 class Solution: def findTheWinner(self, n: int, k: int) -> int: ...
Python
1
ntln!("Not in a git repository"); process::exit(1); } } Err(e) => { eprintln!("Could not get current_dir: {:?}", e); process::exit(1); } }; // find maximum/latest semver let (major, minor, patch) = if let Ok(tags) = tags(&repo) { ...
Rust
0
64 data, which should decode to no bytes self.assertEqual(e.get_bytes(), six.b('')) self.assertEqual(e.content_type(), 'text/plain') def test_from_uri_data_format_invalid_base64(self): self.assertRaises( InvalidUriError, DataMemoryElement.from_uri, 'data:...
Python
1
import torch from typing import TypeAlias Tensor: TypeAlias = torch.Tensor def torsion_angle_loss( alpha: Tensor, torsion_gt: Tensor, torsion_mask: Tensor, torsion_alt: Tensor | None = None, eps: float = 1e-8, ) -> tuple[Tensor, Tensor]: """Compute torsion angle loss. See alphafold suppl...
Python
1
} else { return Err(serde::de::Error::invalid_length(64, &self)); } } Ok(SignatureBytes(result)) } } deserializer.deserialize_tuple(64, Vis) } } impl Serialize for SignatureBytes { fn serialize<S>(&s...
Rust
0
<u32>, } #[doc = "Retention Register"] pub mod ret108_reg; #[doc = "Retention Register"] pub struct RET109_REG { register: VolatileCell<u32>, } #[doc = "Retention Register"] pub mod ret109_reg; #[doc = "Retention Register"] pub struct RET110_REG { register: VolatileCell<u32>, } #[doc = "Retention Register"] pub...
Rust
0
lation, these are migrating arrays. In a serial simulation they are ordinary Numeric arrays. """ natoms = len(self.atoms) self.q = np.zeros((natoms, 3), float) self.q_past = np.zeros((natoms, 3), float) self.q_future = np.zeros((natoms, 3), float) class WeakMethodWrapp...
Python
1
<Data, String> { let result = match binop(data) { (Data::Real(_), Data::Real(r)) if r == 0.0 => Err("Division by zero")?, (Data::Real(l), Data::Real(r)) => Data::Real(l.rem_euclid(r)), (Data::Integer(_), Data::Integer(n)) if n == 0 => Err("Division by zero")?, (Data::Integer(l), ...
Rust
0
"""attitude constraint corrections Revision ID: 420f9b8b9e Revises: 162f93d4393 Create Date: 2015-06-24 16:52:02.606637 """ # revision identifiers, used by Alembic. revision = '420f9b8b9e' down_revision = '162f93d4393' branch_labels = None depends_on = None from alembic import op def upgrade(): op.drop_constr...
Python
1
import pandas as pd import numpy as np import automl_alex from automl_alex import DataPrepare from automl_alex import AutoML, AutoMLClassifier, AutoMLRegressor print('AutoML-Alex version:', automl_alex.__version__) MODEL_FILE_NAME = 'AutoML_model' MODEL_DIR ='./model/' def load_data(): ''' here you can inse...
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
import logging from typing import TYPE_CHECKING from telegram.ext import Application from csm_bot.texts import NO_NEW_BLOCKS_ADMIN_ALERT logger = logging.getLogger(__name__) logging.getLogger("apscheduler.executors.default").setLevel(logging.WARNING) if TYPE_CHECKING: from csm_bot.app.context import BotContext...
Python
1
_LL], dists: [0; ZOPFLI_NUM_D], ll_symbols: [0.0; ZOPFLI_NUM_LL], d_symbols: [0.0; ZOPFLI_NUM_D], } } } impl SymbolStats { fn randomize_stat_freqs(&mut self, state: &mut RanState) { fn randomize_freqs(freqs: &mut [usize], state: &mut RanState) { l...
Rust
0
import math import requests import re from bs4 import BeautifulSoup from fake_useragent import UserAgent from tqdm import tqdm import pandas as pd import jieba import wordcloud import imageio from PIL import Image barrages_num = 20 # 单个视频爬取弹幕数 video_num = 300 # 爬取视频数 pagenum = 0 ua = UserAgent() headers = { "co...
Python
1
::R](dma4sz::R) reader structure"] impl crate::Readable for DMA4SZ {} #[doc = "`write(|w| ..)` method takes [dma4sz::W](dma4sz::W) writer structure"] impl crate::Writable for DMA4SZ {} #[doc = "DMA Channel 4 Transfer Size"] pub mod dma4sz; #[doc = "DMA Channel 5 Control\n\nThis register you can [`read`](crate::ge...
Rust
0
my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; }; my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<...
Rust
0
) -> Result; } extern "C" { pub fn svcSetThreadAffinityMask( thread: Handle, affinitymask: *const u8, processorcount: s32, ) -> Result; } extern "C" { pub fn svcGetThreadIdealProcessor(processorid: *mut s32, thread: Handle) -> Result; } extern "C" { pub fn svcSetThreadIdealPr...
Rust
0
fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TezosSignedTx { static instance: ::protobuf::rt::LazyV2<TezosSignedTx> = ::protobuf::rt::LazyV2::INIT; instance.get(TezosSignedTx::new) } } impl ::protobuf::Clear for TezosSignedTx ...
Rust
0
from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession from api.dependencies.database import get_async_db from crud.industry import industry_curd from crud.specialization import specialization_crud from schemas.specialization import ( Sp...
Python
1
print("Couldn't extract squashfs. Removing image file to be safe") os.remove(RootFSImagePath) return False if not os.path.exists(RootFSPath + "/usr"): print("Couldn't extract squashfs. Removing image file to be safe") os.remove(RootFSImagePath) return False ...
Python
1