text
string
label_name
string
labels
int64
# Copyright 2021 CR-Suite Development Team # # 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 ...
Python
1
put_pixel(4, 4, Rgba([255, 255, 255, 255])); return image; } #[test] fn test_black_pixel_count() { let image1: DynamicImage = DynamicImage::new_rgb16(TEST_IMG_WIDTH, TEST_IMG_HEIGHT); let image2: DynamicImage = generate_colored_image(); assert_eq!(get_black_pixel_count(imag...
Rust
0
().unwrap()))); }, None => {}, }; // use HTTP2 match matches.value_of("http2") { Some(addr) => { let der = include_bytes!("kamasu.p12"); let mut tls_acceptor = TlsAcceptorBuilder::from_pkcs12(der, APP_NAME).expect("acceptor build error"); tls_acce...
Rust
0
# This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of...
Python
1
import matplotlib.pyplot as plt import random import pysal from splot.esda import lisa_cluster import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt from pysal.lib import weights from esda.moran import Moran_Local plt.rcParams["font.sans-serif"] = ["SimHei"] # 用来正常显示中文标签 plt.rcParams["axes.unico...
Python
1
s #![allow(clippy::unnecessary_operation)] #![warn(rust_2018_idioms)] #![cfg(feature = "full")] use tokio::sync::Barrier; use tokio_test::task::spawn; use tokio_test::{assert_pending, assert_ready}; use std::string::ToString; use crates_unittest::test_case; use std::prelude::v1::*; struct IsSend<T: Send>(T); #[test...
Rust
0
[doc = " \\brief Pointer to vtable for this context."] pub vtable: *const br_hash_class, pub buf: [cty::c_uchar; 64usize], pub __bindgen_padding_0: u32, pub count: u64, pub val_md5: [u32; 4usize], pub val_sha1: [u32; 5usize], pub __bindgen_padding_1: u32, } extern "C" { #[doc = " \\brief...
Rust
0
import requests # Import the requests library for making HTTP requests # Define the URL for the API endpoint to pull a specific image from a container registry url = "http://localhost:10001/v4.0.0/libpod/images/pull?reference=docker.io%2Flibrary%2Fnginx:1.24.0" # Define the payload for the request. This could be a s...
Python
1
b, 0xcd, 0x34, 0xda, 0x79, 0x0d, 0x35, 0x7c, 0xa4, 0xd1, 0xfa, 0x44, 0x09, 0xb9, 0xf0, 0x0b, 0xb2, 0xfb, 0xd3, 0xf1, 0xfd, 0xd8, 0x2f, 0x30, 0x15, 0xe2, 0x75, 0x18, 0x90, 0x3b, 0x33, 0xc5, 0x4a, 0x3d, 0x19, 0xd1, 0xb9, 0x35, 0x59, 0x2d, 0x2a, 0x0a, 0x51, 0xfe, 0xad, 0x03, 0xcd, 0x05, 0x8c, 0xb6, 0xeb, 0x5f,...
Rust
0
] = b"o\0"; pub const SCNu32: &'static [u8; 2usize] = b"u\0"; pub const SCNx32: &'static [u8; 2usize] = b"x\0"; pub const SCNd64: &'static [u8; 4usize] = b"lld\0"; pub const SCNi64: &'static [u8; 4usize] = b"lli\0"; pub const SCNo64: &'static [u8; 4usize] = b"llo\0"; pub const SCNu64: &'static [u8; 4usize] = b"llu\0"; ...
Rust
0
""" ============== Rotating a Map ============== How to rotate a map. """ import matplotlib.pyplot as plt import astropy.units as u import sunpy.data.sample import sunpy.map ############################################################################### # We start with the sample data. aia_map = sunpy.map.Map(sunp...
Python
1
food_position = create_food() current_score += score else: # 移除最后一格 snake_body.pop() else: is_dead = True # 画背景 screen.fill(background_color) # 画边框 draw_box() # 画蛇 draw_snake(food_positio...
Python
1
eighted loss loss = loss1 + loss2 elif args.noise_type in ['gaussian']: loss = torch.sum((model_output.float() - (clean_images - noise).float())**2) else: raise ValueError(f"Unsupported noise type: {args.noise_type}") ...
Python
1
{ binary.as_ref().to_owned() } else { OsString::from(format!("{}{}", binary_str, EXE_SUFFIX)) } } else { // Very weird case. Non-unicode command. binary.as_ref().to_owned() }; let bin_path = self.path.join("bin").j...
Rust
0
": "Fire Stone"}, {"_id": 63, "nome": "Abra", "tipos": ["Psíquico"], "pre_evolucao": None, "pre_requisito": None}, {"_id": 64, "nome": "Kadabra", "tipos": ["Psíquico"], "pre_evolucao": 63, "pre_requisito": "Level 16"}, {"_id": 65, "nome": "Alakazam", "tipos": ["Psíquico"], "pre_evolucao": 64, "pre_requisito...
Python
1
view: &frame.view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), store: true, }, }], ...
Rust
0
_webhook_url.is_ok() { let discord_client = reqwest::blocking::Client::new(); let body: Value = serde_json::from_str(&*format!("{{\"content\":\"{}\"}}", random_problem_url)) .expect("Error creating json from provided url string"); let response = discord_client ...
Rust
0
4, pdecout: *mut super::super::Foundation::DECIMAL) -> ::windows_sys::core::HRESULT; #[doc = "*Required features: `\"Win32_System_Ole\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub fn VarDecInt(pdecin: *const super::super::Foundation::DECIMAL, pdecresult: *mut super::super::Foundatio...
Rust
0
-> Result<()> { let ok = (_API.SciterSetMediaVars)(self.hwnd, media.as_cptr()); ok_or!(ok) } /// Set or append the master style sheet styles (globally). pub fn set_master_css(&self, css: &str, append: bool) -> Result<()> { let (s,_) = s2u!(css); let b = s.as_bytes(); let n = b.len() as UINT; let ok = i...
Rust
0
import random def d6_dice(): num_rolls = int(input("How many times do you want to roll the dice? ")) results = [] for _ in range(num_rolls): roll = random.randint(1, 6) results.append(roll) total = sum(results) print("Results of the rolls:", results) print("Total:", total) if _...
Python
1
len_orig, col4_part .iter() .map(|c| c.len(&dict).unwrap()) .sum::<usize>() ); let mut col4_part_mut = col4.part_mut(3, &dict).unwrap(); assert_eq!( len_orig, col4_part_mut .iter_mut(...
Rust
0
9; let e: i64 = 3; let r: i64 = transmute(vcvtad_s64_f64(transmute(a))); assert_eq!(r, e); } #[simd_test(enable = "neon")] unsafe fn test_vcvtas_u32_f32() { let a: f32 = 2.9; let e: u32 = 3; let r: u32 = transmute(vcvtas_u32_f32(transmute(a))); assert...
Rust
0
alize)] #[serde(deny_unknown_fields)] pub struct MergeMiningProxyConfig { override_from: Option<String>, pub monerod_url: StringList, pub monerod_username: String, pub monerod_password: String, pub monerod_use_auth: bool, pub base_node_grpc_address: Multiaddr, pub console_wallet_grpc_address...
Rust
0
Ok(Arc::new( VfioContainer::new(Arc::new(dev_fd), &sys_mem) .chain_err(|| "Failed to create vfio container")?, )) } <reponame>Madadog/bevy-tower-defense use std::time::Duration; use bevy::prelude::*; use crate::rectangle::Hitbox; pub struct ComponentsPlugin; impl Plugin for ComponentsP...
Rust
0
poly.evaluate_at(&zero)?, one); for _trial in 0..100 { let r = EccScalar::random(curve, &mut rng)?; let r_plus_1 = r.add(&one)?; assert_eq!(poly.evaluate_at(&r)?, r_plus_1); } } Ok(()) } #[test] fn poly_simple_polynomial_x2_x_1() -> ThresholdEcdsaResult<()>...
Rust
0
lumn, Value>>; /// Represents the return type of `.for_update()` pub type ForUpdate<Source> = <Source as LockingDsl<lock::ForUpdate>>::Output; /// Represents the return type of `.for_no_key_update()` pub type ForNoKeyUpdate<Source> = <Source as LockingDsl<lock::ForNoKeyUpdate>>::Output; /// Repre...
Rust
0
mul_with_column_f64() { // pick a few random sizes let mut rng = SmallRng::from_entropy(); for i in 0..10 { let m = rng.gen_range(1, 350); let k = rng.gen_range(1, 350); let a = gen_f64(Ix2(m, k)); let b_owner = gen_f64(Ix2(k, k)); let b_row_col; let b_sq; ...
Rust
0
import re import json import traceback from aiogram import html from aiogram.types import Message from utils import get_base_llm_response, get_security_rag_response from logger import logger from aiogram import Dispatcher from aiogram.filters import CommandStart dp = Dispatcher() @dp.message(CommandStart()) async def...
Python
1
fn param_info(&self) -> ParamInfo { ParamInfo { num_required: 0, num_optional: 0, param_docs: vec![], } } } <reponame>spruceid/treeldr<filename>build/src/error/literal_unexpected.rs use treeldr::{ Vocabulary, vocab::Literal, vocab::Display }; #[derive(Debu...
Rust
0
# coding: utf-8 # @author: kaimin # @time: 2024-04-01 11:19 import json from typing import List, Dict from .base_eval import BaseEval class ChoiceEval(BaseEval): def __init__(self): super().__init__() @staticmethod def check_choice(p_options, p_reference, p_response): for tc in p_respons...
Python
1
for ProjectPathsArgs { fn metadata(&self) -> Metadata { Metadata::named("Project Paths Args Provider") } fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> { let value = Value::serialize(self)?; let error = InvalidType(value.to_actual(), "map".into()); let mut dic...
Rust
0
ue) pub fn can_split(&self) -> bool { self.cards.len() == 2 && self.cards[0].value() == self.cards[1].value() } /// Whether or not the hand can be surrendered (i.e. whether or not it has just 2 cards) pub fn can_surrender(&self, surrender_rule: Surrender, dealer: Card) -> bool { if self...
Rust
0
r_volume_level = (stream.user_volume_level * 100.0).floor() / 100.0; self.stored_stream = new_stream_value; let proxy = self.proxy.as_ref().unwrap(); if self.stored_stream.user_volume_level != new_stream_value.user_volume_level { if proxy.set_volume(new_stream_value.user_volume_leve...
Rust
0
arc", target_arch = "asmjs", target_arch = "wasm32", target_arch = "hexagon", target_arch = "riscv32" )))] const MIN_ALIGN: usize = 8; #[cfg(all(any( target_arch = "x86_64", target_arch = "aarch64", target_arch = "mips64", target_arch = "s390x", target_arch = "sparc64", target_ar...
Rust
0
import numpy as np import os import sys import unittest parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # print(parent_dir) sys.path.insert(0, parent_dir) from deep_sort.sort import kalman_filter class TestDistanceFunction(unittest.TestCase): def setUp(self): self.fn = kalman...
Python
1
d_query_str = result.text print(f"DEBUG: web_search - transformed query: {transformed_query_str}") # Conduct a search with the transformed query string using direct API call search_text = self._firecrawl_search(transformed_query_str) print(f"DEBUG: web_sear...
Python
1
#✅ What It Is: #A variable is like a box that stores data (name, age, number, etc.) name = "Mohamed" age = 22 height = 1.75 is_student = True #❓ Can variable names have spaces? #❌ No. Use underscores or camelCase #✅ first_name, userAge first_name ='Mohamed' firstName ='Mohamed' #❓ Can I change a variable value late...
Python
1
); let mut display = MockDisplay::new(); image.draw(&mut display).unwrap(); display.assert_pattern(CHESSBOARD_PATTERN); } fn test_tga<C>(data: &[u8], pattern: &[&str]) where C: PixelColor + From<<C as PixelColor>::Raw> + ColorMapping, { let tga: Tga<C> = Tga::from_slice(data).unwrap(); let im...
Rust
0
e sure we account for all terminations: normal or errors. if not decremented: with self._lock: self._runs_per_session[sess] -= 1 def create_threads(self, sess, coord=None, daemon=False, start=False): """Create threads to run the enqueue ops for the given session. This method requires...
Python
1
from os import environ import base64 class ParseConnector: def __init__(self, cnxString): #standard cnx Env username:password@server:port/database self.cnxString = environ[cnxString] if self.cnxString : if self.cnxString.startswith("SK|") : base64_bytes = cnxStri...
Python
1
for i, image in enumerate(images, 1): print(f"\n🖼️ [{i}/{len(images)}] Processing: {image['original_filename']}") print(f" 🆔 ID: {image['id']}") print(f" 📁 Uploaded path: {image['uploaded_path']}") print(f" 📁 Processed path: {image.get('processed_path', 'N/A...
Python
1
_node = getter() except: continue if _node is not None: return _node _last_timestamp = None def uuid1(node=None, clock_seq=None): """Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the har...
Python
1
if proj_dim > 0: print '<AffineTransform> <InputDim> ' + str(actual_cell_dim) + ' <OutputDim> ' + str(proj_dim) + ' <ParamRange> ' + param_range print model_type + ' <InputDim> ' + str(proj_dim) + ' <CellDim> ' + str(actual_cell_dim) + lstm_comm else: print model_ty...
Python
1
import pickle import pandas as pd import json import os from global_parameters import ( IVQA_PATH, MSRVTT_PATH, MSVD_PATH, ACT_PATH, HOWTO_PATH, HOW2QA_PATH, ) # Load HowTo100M narrations and csv videos = pickle.load( open(os.path.join(HOWTO_PATH, "caption_howto100m_with_stopwords.pkl"), "...
Python
1
/// Parse a string into a JSON value. /// /// If unsuccessful, returns a `TracebackError`, giving information about the location of the syntax error within the JSON string. /// /// ## Usage /// ``` /// let value = Value::parse("[1, 2, 3]"); /// ``` pub fn parse(s: impl AsRef<str>) -> R...
Rust
0
config_path, 'w', encoding='utf-8') as f: json.dump(config, f, indent=2, ensure_ascii=False) logger.info("配置保存成功: %s", self.config_path) return True except Exception as e: logger.error("配置保存失敗: %s", e) return False ...
Python
1
ub Size: USHORT, pub TransactionContext: USHORT, pub Filter: PFLT_FILTER, pub Volume: PFLT_VOLUME, pub Instance: PFLT_INSTANCE, pub FileObject: PFILE_OBJECT, pub Transaction: PKTRANSACTION, } pub type PFILE_OBJECT = MISS_TYPE_PTR; pub type PCFLT_RELATED_OBJECTS = *const FLT_RELATED_OBJECTS; p...
Rust
0
fn verify_toolchains(config: &Experiment, tcs: &[Toolchain]) -> Result<()> { for tc in tcs { if !config.toolchains.contains(tc) { bail!("toolchain {} not in experiment", tc.to_string()); } } Ok(()) } fn build(ex: &Experiment, source_path: &Path, toolchain: &Toolchain) -> Result...
Rust
0
(x, y, Element::Sand(strength)) } else { ( x + destabilize_offset(left, right, 1.3), y, Element::Sand(0), ) } ...
Rust
0
lds thresholds = calculator.calculate_variance_based_thresholds(variance_signals) print("📈 Variance Regime Thresholds:") for regime, threshold in thresholds.items(): if isinstance(threshold, float): print(f" {regime}: {threshold:.6f}") if 'percentiles' in thresholds: ...
Python
1
evaluate the tree using matches(), storing the result in map. // // - if the complete tree returns (matches() == true) for the document, // collect all text matches by looking at leaf matchTrees // type matchTree interface { docIterator // returns whether this matches, and if we are sure. matches(cp *content...
Rust
0
pacity() ); println!( "string4.len : {}", string4.len() ); println!( "" ); // < &string3 : 0x7ffe02f6e978 - stack segment // < string3.as_ptr : 0x55d846136ae0 - heap segment // < string3.capacity : 7 // < string3.len : 7 // < &string4 : 0x7ffe02f6e990 - stack segment // < string4.as_ptr : 0x55d846136b00...
Rust
0
er seems valid -- caller_pc: 0x{:016x}, caller_sp: 0x{:016x}", caller_pc, caller_sp, ); let mut caller_ctx = ArmContext::default(); caller_ctx.set_register(PROGRAM_COUNTER, caller_pc); caller_ctx.set_register(LINK_REGISTER, caller_lr); caller_ctx.set_register(FRAME_POINTER, caller_f...
Rust
0
#[inline] fn deserialize<T: AsRef<[u8]>>(deserializer: &mut Deserializer<T>) -> Result<Self, Error> { let len = deserializer.deserialize_u8()? as usize; if len > SessionId::MAX_LEN { return Err(Error::from(ErrorKind::DecodeError)); } let mut buf = [0u8; 32]; de...
Rust
0
ne_3.text().strip(): errors.append("请选择家庭地址") # 验证学号是否填写,如果未填写,添加错误信息 if not self.family_Info_Edit_widgets.inputLine_13.text().strip(): errors.append("请输入备注") # 验证班级是否选择,如果未选择班级,添加错误信息 if self.massage_type == 1 and self.BaseQueryWidget.tableWidget.rowCount() != 0: ...
Python
1
-> Vec<u8> { json::to_string(input).into_bytes() } } <filename>src/melee/moves.rs<gh_stars>0 #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct Move { id: u8, name: &'static str, short_name: &'static str, } impl Move { pub fn from_move_id(id: u8) -> crate::SlippiResult<Self> { ...
Rust
0
_ = Uniforms!(irradiance_shd, ("env_cubetex", &e), ("MVPMat", cam), ("iDelta", 0.025)); let mut surf = Fbo::<RGBA, f32>::new((64, 64)); surf.bind(); Skybox::Draw(); fImage::<RGB>::from(surf.tex) }) .collect::<Vec<_>>() .try_into() .unwrap(); let mips = TexParam::mip_levels(cubemap.param.w...
Rust
0
License for the specific language governing permissions and // limitations under the License. //! google compute engine metadata fetcher use std::collections::HashMap; use openssh_keys::PublicKey; use update_ssh_keys::AuthorizedKeyEntry; use errors::*; use network; use providers::MetadataProvider; use retry; head...
Rust
0
from celery import shared_task from pbaabp.integrations.mailjet import Mailjet @shared_task def sync_to_mailjet(event_signin_id): from events.models import EventSignIn event_sign_in = EventSignIn.objects.get(id=event_signin_id) print(event_sign_in, event_sign_in.newsletter_opt_in) if event_sign_in....
Python
1
import requests import re import html from lib.ocr_api import ocr_space_url # 确保从正确的文件导入ocr_space_url函数 def download_and_extract_json(url, board): try: response = requests.get(url) response.raise_for_status() data = response.json() except requests.RequestException as e: print...
Python
1
from bs4 import BeautifulSoup import concurrent.futures import requests import functools import pandas as pd import requests import time import json from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker def immo_pag...
Python
1
] ConnectToArchiveAccessor(#[source] anyhow::Error), #[error("Failed to connect to TestSuite: {0:?}")] ConnectToTestSuite(#[source] anyhow::Error), #[error("Failed to stream logs from embedded Archivist: {0:?}")] StreamIsolatedLogs(StreamError), #[error("Failed to resolve test: {0:?}")] R...
Rust
0
yield _compose_chunk(model_id, build_fc_args_message(total_response[pos:])) found_action_name = True finish_reason = "function_call" else: yield _compose_chunk(model_id, DeltaMessage(content=delta)) yield _compose_chunk(model_id, DeltaMessag...
Python
1
, t3:&T3, t4:&T4, t5:&T5, function:F) -> Self { let src1 = watch_stream(t1); let src2 = watch_stream(t2); let src3 = watch_stream(t3); let src4 = watch_stream(t4); let src5 = watch_stream(t5); let def = AllWith5Data {src1,src2,src3,src4,src5,function}; let thi...
Rust
0
TEMPLATES = { "worker_pr_template": """ <!-- BEGIN_TITLE --> # {title} <!-- END_TITLE --> ## Description ### Task <!-- BEGIN_TODO --> {todo} <!-- END_TODO --> ### Acceptance Criteria <!-- BEGIN_ACCEPTANCE_CRITERIA --> {acceptance_criteria} <!-- END_ACCEPTANCE_CRITERIA --> ### Summary of Work <!-- BEGIN_DESCRIPT...
Python
1
atlab_proxy_sync(parent_id, caller_id) headers = matlab_proxy_info.get("headers") mwi_auth_token = headers.get("MWI-AUTH-TOKEN") matlab_proxy_url = build_url( matlab_proxy_info.get("absolute_url"), {"mwi-auth-token": mwi_auth_token}, ) mpm_auth_token = mat...
Python
1
import pandas as pd from datetime import timedelta from datetime import date symbols = [ 'PEPEUSDT', 'BTCUSDT', 'SOLUSDT', 'ETHUSDT' ] """ symbol_meme = [ "DOGEUSDT", "SHIBUSDT", "PEPEUSDT", "WIFUSDT", "BONKUSDT", "FLOKIUSDT", "BOMEUSDT", # "MOGUSDT" # "POPCATUSDT" ...
Python
1
ent and add to the Vec let seg = Segment::new(x1, y1, x2, y2, direction, distance, t_distance, i); segments.push(seg); }; }; // Sort segments by x1 segments.sort_by(|s1, s2| s2.x1.cmp(&s1.x1)); segments.reverse(); // Build a swee...
Rust
0
k: &SystemId) -> Option<&System> { self.0.get(k) } } impl From<Vec<System>> for SystemMap { fn from(systems: Vec<System>) -> Self { let mut system_map = HashMap::new(); for system in systems { system_map.insert(system.id, system); } Self(system_map) } }...
Rust
0
from datetime import datetime from sqlalchemy import ( JSON, Column, DateTime, ForeignKey, Integer, String, ) from sqlalchemy.orm import relationship from app.infra.db.async_database import Base class XhsKeywordGroup(Base): """小红书关键词群表""" __tablename__ = "xhs_keyword_groups" gr...
Python
1
into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] ...
Python
1
from pydantic import BaseModel import pytest from sqlalchemy.orm import Mapped, mapped_column from src.fifi import DatetimeDecoratedBase from src.fifi import LoggerFactory from faker import Faker fake = Faker() LOGGER = LoggerFactory().get(__name__) @pytest.fixture def user_factory(): def create_user(count: i...
Python
1
ict_has_value(dict_inputs, input_custom, 'execute_at_creation') dict_inputs = dict_has_value(dict_inputs, input_custom, 'execute_at_modification') dict_inputs = dict_has_value(dict_inputs, input_custom, 'custom_options_message') dict_inputs = dict_has_value(dict_inputs, input_custom...
Python
1
res ); assert_eq!(res.unwrap(), expected); } let invalid_req = [ ("truc:machin", InvalidSyntax { name: S("truc:machin") }), ("truc:deesc", InvalidSyntax { name: S("truc:deesc") }), ("truc:asc:deesc", InvalidSyntax { name: S("truc:asc:deesc") }...
Rust
0
n_equal_end_point(self): """ Test 2. Make end point of B-spline coincident with the Origin """ self.setCoincidentWithOrigin(self.mySpline.endPoint()) self.myPoles[-1].setX(0) self.myPoles[-1].setY(0) self.assertPoles() def test_origin_equal_pole(self): """ Test 3. Make one of B-spline pol...
Python
1
self.parse_word(); let last_token = self.last_token().take().expect("last token"); if last_token.is_empty() { self.set_last_token(last_token); self.abort_with(UNEXPECTED_END_OF_FILE); } else { match self.find(&last_token) { Some(found_index) =...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import path from setuptools import setup readme_file = path.join(path.dirname(path.abspath(__file__)), 'README.rst') with open(readme_file) as f: readme = f.read() install_requires = [ 'tornado>=5.0', ] test_requires = [ 'parameterized', 'seleniu...
Python
1
None, otherwise if not possible */ pub fn is_move_possible( &self, colour: Rang, start_coord: (u8, u8), mut dist: u8, ) -> Option<(u8, u8)> { if self.board[start_coord.0 as usize][start_coord.1 as usize].cell_type == LudoCellType::NoUse { ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/4/30 20:58 @Author : alexanderwu @File : __init__.py """
Python
1
"✅ Trading manual habilitado\n" "✅ IA preditiva ativa\n" "✅ Monitoramento 24/7\n\n" "Digite /start para começar!" ) except Exception as e: logger.warning(f"Não foi possível enviar mensagem de inicialização: {e}") # Executar mensage...
Python
1
auth_header.macaroon = Some(value.clone()); } if let Some(value) = headers.get("token") { auth_header.token = Some(value.clone()); } Ok(auth_header) } } <reponame>torao/tinymt use tinymt::tinymt32::*; use tinymt::TinyMT32; /// https://github.com/MersenneTwister-Lab/...
Rust
0
import json import re def convert_astm_to_json(astm_message): segments = astm_message.strip().split('\n') # Initialize variables results = [] test_panel_name = "" lab_test_request = 1 test_panel_id = 1 record_id = 1 patient_name = "" patient_id = "" unit_of_measurement = "" ...
Python
1
import torch from pyg_lib.ops.scatter_reduce import fused_scatter_reduce from pyg_lib.testing import onlyCUDA, onlyTriton @onlyCUDA @onlyTriton def test_fused_scatter_reduce(): x = torch.randn(5, 4, device='cuda') index = torch.tensor([0, 1, 0, 1, 0], device='cuda') out = fused_scatter_reduce(x, index, ...
Python
1
= lb2 + (lb2 <= 0) - (lb2 >= 0) ub = ub2 + (ub2 <= 0) - (ub2 >= 0) if lb1 >= 0: # result will be positive if first argument is positive return 0, max(-lb, ub, 0) # lb = 0 elif ub1 <= 0: # result will be negative if first argument is negative return ...
Python
1
import torch from maskrcnn_benchmark.structures.bounding_box import BoxList from gluoncv.torch.data.gluoncv_motion_dataset.dataset import AnnoEntity def boxlists_to_entities(boxlists, firstframe_idx, timestamps, class_table=None): """ Convert a list of boxlist to entities :return: """ if isinstan...
Python
1
509Name}; use openssl::pkey::PKey; use openssl::hash::MessageDigest; use openssl::rsa::Rsa; use openssl::nid::Nid; use openssl::asn1::Asn1Time; pub struct SelfSignedCertificate { certificate: X509, private_key: openssl::pkey::PKey<openssl::pkey::Private> } impl SelfSignedCertificate { pub fn build_certifi...
Rust
0
.items.len(); for (expr, _) in &self.items { expr.assemble(c, Needs::Value)?.apply(c)?; c.scopes.decl_anon(expr.span())?; } c.asm.push(Inst::Vec { count }, span); c.scopes.undecl_anon(span, self.items.len())?; // Evaluate the expressions one by one, the...
Rust
0
of `Variables`. fn from(vars: Variables<f64>) -> Self { let mut map: HashMap<String, f64> = HashMap::new(); for i in 0..vars.names.len() { map.insert(vars.names[i].clone(), vars.values[i]); } let Variables { names, values, .. } = vars; OpResult { names, values, m...
Rust
0
private devices"] pub bb_wlprivaddptr: BB_WLPRIVADDPTR, #[doc = "0xd8 - Devices in white list"] pub bb_wlnbdev: BB_WLNBDEV, _reserved40: [u8; 4usize], #[doc = "0xe0 - AES-128 ciphering control register"] pub bb_aescntl: BB_AESCNTL, #[doc = "0xe4 - AES encryption 128-bit key register (bits 3...
Rust
0
assert!(ONE <= ONE); assert!(ONE >= ONE); assert!(!(ZERO > ONE)); assert!(!(ZERO >= ONE)); assert!(!(ONE < ZERO)); assert!(!(ONE <= ZERO)); } #[test] fn infinities_equality() { assert!(INF == INF); assert!(NEGINF == NEGINF); assert!(INF <= INF); assert!(NEGINF <= NEGINF); assert!(INF >= INF); assert!(NEGIN...
Rust
0
tv_episodes(self, rssid): """ 查询数据库中订阅的电视剧缺失集数 """ return self.dbhelper.get_rss_tv_episodes(rssid) def check_history(self, type_str, name, year, season): """ 检查订阅历史是否存在 """ return self.dbhelper.check_rss_history(type_str=type_str, ...
Python
1
es(&self) -> Bodies<N> { Bodies { rbs_iter: self.rbs.iter(), mbs_iter: self.mbs.iter() } } */ /// Mutable iterator yielding all the bodies on this set. #[inline] pub fn bodies_mut(&mut self) -> BodiesMut<N> { BodiesMut { rbs_iter: self.rbs...
Rust
0
); } #[wasm_bindgen] pub struct TestTraitHolder { hold: Vec<Box<TestTrait>>, } #[wasm_bindgen] pub struct TestStruct { a: Rc<RefCell<u32>>, f: Rc<RefCell<ButtonState>>, } #[wasm_bindgen] impl TestStruct { pub fn new() -> TestStruct { TestStruct { a: Rc::new(RefCell::new(0)), ...
Rust
0
tl { pub dronectl_type: DroneCtlType, pub host_data: Option<Host>, pub job_data: Option<Job>, pub msg: Option<String>, } impl DroneCtl { pub fn new(dronectl_type: DroneCtlType, host_data: Option<Host>, job_data: Option<Job>, msg: Option<String>) -> Self { DroneCtl { dronectl_type, ...
Rust
0
"""Module for building tree data structures from coding system hierarchies.""" def build_tree_data( child_map, code_to_term, code_to_status, tree_tables, sort_by_term=True ): """ Builds a hierarchical tree structure from coding system data. Args: child_map: Dictionary mapping codes to their c...
Python
1
from __future__ import annotations """Witness network for broadcasting memory updates.""" from .entry import MemoryEntry from .node import IntelligenceNode class WitnessNetwork: """Event bus recording and broadcasting memory updates.""" def __init__(self) -> None: self.log: list[MemoryEntry] = [] ...
Python
1
exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2) if amsgrad: # Maintains the maximum of all 2nd moment running avg. till now torch.max(max_exp_avg_sq, exp_avg_sq, out=max_ex...
Python
1
IAL_STD_CEM) min_cost_this_mpc_step = float('inf') for cem_iter in range(N_ITER_CEM): # 1. 采样 perturbations = np.random.normal(loc=0.0, scale=1.0, size=(N_SAMPLES_CEM, PREDICTION_HORIZON, 2)) sampled_control_sequences = ce...
Python
1
import pandas as pd from scripts.config import BULLISH_SIGNAL, BEARISH_SIGNAL, BULLISH_TREND, BEARISH_TREND, NEUTRAL_TREND, OVERBOUGHT, OVERSOLD, NO_SIGNAL, HIGH_VOLUME, LOW_VOLUME, HIGH_VOLATILITY, LOW_VOLATILITY, INCREASING_VOLATILITY, DECREASING_VOLATILITY, STABLE_VOLATILITY, INCONCLUSIVE def signal_cmo(series: pd....
Python
1
序)的方法调用树 pub fn get_sequenced_call_tree(&mut self, thread_id: i64, start_time: &mut i64, end_time: &mut i64, fill_method_name: bool) -> io::Result<Box<tree::TreeNode>> { let mut start_step = 0; let mut end_step = 0; let mut sw = Stopwatch::start_new(); sw.start(); let mut ts_...
Rust
0