text string | label_name string | labels int64 |
|---|---|---|
`RsaPrivKeyAnyBits` is an enum of [`RsaPrivKey`]s over all supported bit
/// lengths. It is returned from [`RsaPrivKeyAnyBits::parse_from_der`].
#[allow(missing_docs)]
#[derive(Debug)]
pub enum RsaPrivKeyAnyBits {
B2048(RsaPrivKey<B2048>),
B3072(RsaPrivKey<B3072>),
B4096(RsaPrivKey<B4096>),
B6144(RsaPr... | Rust | 0 |
from uuid import UUID
from app.domain.entities.draft_order import DraftOrder
from app.infrastructure.repositories.draft_order.base import BaseDraftOrderRepository
class FakeDraftOrderRepository(BaseDraftOrderRepository):
def __init__(self) -> None:
self._draft_orders: dict[UUID, DraftOrder]
self._... | Python | 1 |
ormer, merged_field_name, default_date,
)
for parent_key in parents
)
if not block_date:
# no value on this block so take value from parents
merged_date_value = merged_all_parents_date
else:
# compute m... | Python | 1 |
li 10|27.8 mile # Chinese unit of length
# 100 li is considered a day's march
liang 11|3 oz # Chinese weight unit
# Medieval time units. According to the OED, these appear in Du Cange
# by Papias.
timepoint 1|5 hour ... | Rust | 0 |
from django.urls import path
from .views import NewsListView, NewsUpdateView,NewsDetailView, NewsDeleteView, NewsCreateView
urlpatterns = [
path('', NewsListView.as_view(), name='news'),
path('<int:pk>/edit/', NewsUpdateView.as_view(), name='news_edit'),
path('<int:pk>/', NewsDetailView.as_view(), name='ne... | Python | 1 |
::{
data_transfer::{payload::TaskTransfer, DataTransfer, DragEffect},
event_bus::{EventBus, EventBusRequest},
};
#[derive(Debug, Clone, PartialEq, Properties)]
pub struct Props {
/// The unique identifier for the stage
pub id: StageId,
/// A human readable description of the stage
pub descripti... | Rust | 0 |
return Err(err);
}
}
}
}
let time_str = &String::from_utf8_lossy(&time_str);
match Time::from_str(time_str) {
Ok(time) => Ok(time),
Err(err) => scanner.make_generic_err(&format!(
"Invalid time format '{time_str}'. Parse error: {err}"
... | Rust | 0 |
a.as_array().to_owned();
let ranges_b = b.as_array().to_owned();
let cov_a = coverage::create_nested_ranges_from_py(ranges_a);
let cov_b = coverage::create_nested_ranges_from_py(ranges_b);
let result = spatial_coverage::difference(&cov_a, &cov_b);
let result: Array2<u64> = re... | Rust | 0 |
ed in given unit price?"),
default=plata.settings.PLATA_PRICE_INCLUDES_TAX,
)
tax_class = models.ForeignKey(
TaxClass,
on_delete=models.CASCADE,
verbose_name=_("tax class"),
related_name="+",
)
def __str__(self):
return _("%(currency)s %(value).2f") % {
... | Python | 1 |
= float(auroc)
except Exception as e:
print(f"[Warning] AUROC 계산/그림 저장 실패: {e}")
test_metrics['auroc'] = None
test_results[test_modality] = test_metrics
with open(os.path.join(fc_dir, f'test_metrics_{test_modality}.json'), 'w') as f:
json.dump(test_metrics, f,... | Python | 1 |
import tkinter as tk
from tkinter import ttk
import requests
from tkinter import messagebox
# Função para buscar os dados do backend Django
def fetch_data():
api_url = "http://localhost:8000/Urls/ViewsStudy/" # Substitua pela URL correta da sua API
try:
response = requests.get(api_url)
if res... | Python | 1 |
width: 100%;
height: 100%;
}
body {
background: #111;
color: #fff;
margin: 0;
padding: 2%;
box-sizing: border-box;
font-family: monospace;
}
... | Rust | 0 |
slice.len() - idx
);
ptr::write(slice.get_unchecked_mut(idx), val);
}
unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
let ret = ptr::read(slice.get_unchecked(idx));
ptr::copy(
slice.as_ptr().offset(idx as isize + 1),
slice.as_mut_ptr().offset(idx as isize),
sl... | Rust | 0 |
2().ok_or(EvalError::ExpectedStackValue)?;
let v1 = v1.into_f32().ok_or(EvalError::ExpectedStackValueFloat)?;
let v2 = v2.into_f32().ok_or(EvalError::ExpectedStackValueFloat)?;
let value = v2 - v1;
frame.stack.push(RuntimeValuePrimitive::F32(value))?;
Ok(RunInstContinueValue::... | Rust | 0 |
Expressions {
///The comma separated expressions.
pub exprs: Vec<Expression>,
}
impl Print for Expressions {
fn print_with<W: Write>(&self, f: &mut Formatter<W>) -> io::Result<()> {
let mut first = true;
for expr in &self.exprs {
if !first {
try!(f.write(", "));... | Rust | 0 |
trace!("input {:?} of {} is blocked by resource usage; ", t, op.info());
//block_count += 1;
}
if capacity != ::std::usize::MAX {
trace!("output capacity of {}:{:?} is {}", op.info(), t, capacity);
... | Rust | 0 |
DB):
if t.task_id == task_id:
COURSEWARE_TASKS_DB[i].status = "completed"
COURSEWARE_TASKS_DB[i].progress = 1.0
COURSEWARE_TASKS_DB[i].updated_at = datetime.now()
COURSEWARE_TASKS_DB[i].file_path = output_path
COURSEWARE_TASKS_D... | Python | 1 |
"::",
stringify!(query_device_info)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__DRI2interopExtensionRec>())).export_object as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(__DRI2interopExtensi... | Rust | 0 |
)
# some Trainer classes need to use `gather` instead of `gather_for_metrics`, thus we store a flag
self.gather_function = self.accelerator.gather_for_metrics
# deepspeed and accelerate flags covering both trainer args and accelerate launcher
self.is_deepspeed_enabled = getattr(s... | Python | 1 |
.and_then(|addr| addr.downcast_ref::<Address<A>>().cloned()),
)
}
}
// --- Broker messages ---
pub struct Subscribe<A, M>
where
A: Actor + Handler<M>,
M: Clone + Message<Result = ()>,
{
address: WeakAddress<A>,
_m: PhantomData<fn() -> M>,
}
impl<A, M> Subscribe<A, M>
where... | Rust | 0 |
ined_path', type=str, default="/data/wst/video-pace/pretrain_cks/sr_4_mymodelv4_lr_0.001_len_16_sz_112_mytrain3/2023-08-31/mlpepoch-18.pth.tar", help='256 [2,2,4]')
# parser.add_argument('--pre_trained_path', type=str, default="/data/wst/video-pace/pretrain_cks/sr_4_mymodelv4_lr_0.001_len_16_sz_112_mytrain3/2023-10... | Python | 1 |
nd return a list of coordinates of the object
deltas_1_2 - deltas between reciever 1 and reciever 2
deltas_1_3 - deltas between reciever 1 and reciever 3
p1-3 - GPS coordinates of the recievers
'''
reciever_pos_1 = position.lat_lon_to_utm(p1[0],p1[1])
reciever_pos_2 = position.lat_lon_to_utm(p... | Python | 1 |
c[i] = Share(c_val, machine, Q=P)
# Line 14
d_p0 = [s[i] * w_c[p0]['c'][i] for i in range(L)]
d_p1 = [s[i] * w_c[p1]['c'][i] for i in range(L)]
π(d_p0); π(d_p1)
d_shared = [SharedScalar([d0, d1], Q=P) for d0, d1 in zip(d_p0, d_p1)]
# Line 15
p2 = VirtualMachine('p2')
d = [... | Python | 1 |
s/bird_image.jpg
metadata={"help": "The name of image input."},
)
input_audio: str = field(
default="",
# wget https://github.com/facebookresearch/ImageBind/blob/main/.assets/bird_audio.wav
metadata={"help": "The name of audio input."},
)
@dataclass
class ModelArguments:
... | Python | 1 |
from dash.dependencies import Input, Output
from dash.exceptions import PreventUpdate
from Callbacks.CallbackBase import CallbackBase
from DependencyContainer import DependencyContainer
from Logging.Logger import Logger
from Pages.GamesDetailsPage.GamePlayerCard import GamePlayerCard
class LoadGameDetailsPlayers(Ca... | Python | 1 |
#!/usr/bin/python
#
# \file 2_build.py
# \brief Build sheets
# \date 2014-02-19 22:39GMT
# \author Jan Boon (Kaetemi)
# Python port of game data build pipeline.
# Build shard sheets
#
# NeL - MMORPG Framework <https://wiki.ryzom.dev/>
# Copyright (C) 2010-2014 by authors
#
# This program is free software: you can re... | Python | 1 |
t == 'harfbuzz':
build_port('harfbuzz', 'libharfbuzz.a', ['-s', 'USE_HARFBUZZ=1'])
elif what == 'sdl2-ttf':
build_port('sdl2-ttf', 'libsdl2_ttf.bc', ['-s', 'USE_SDL=2', '-s', 'USE_SDL_TTF=2', '-s', 'USE_FREETYPE=1'])
elif what == 'binaryen':
build_port('binaryen', None, ['-s', 'WASM=1'])
e... | Python | 1 |
meout: Duration,
role_name: &str,
ip_addr: &str,
token: &str,
) -> Result<String, CredentialsError> {
let credentials_provider_url = format!(
"http://{}/{}/{}",
ip_addr, AWS_CREDENTIALS_PROVIDER_PATH, role_name
);
let request = Request::builder()
.method("GET")
.... | Rust | 0 |
entry.
next_ipc_entry_index: AtomicU64,
/// IPC entries for endpoints shared with other tasks.
///
/// Since this can be modified after/during the thread being invoked, we need to use a RwLock
/// for it. Mutex is not good because this is a spinlock and with multitasking there can be high latency
... | Rust | 0 |
a [destination](Dest), a
/// [computation](Comp) and a [jump](Jump).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Inst {
/// The destination field.
dest: Dest,
/// The computation field.
comp: Comp,
/// The jump field.
jump: Jump,
}
/// Serialize an instruction to text.
///
/// # Examples
///
/... | Rust | 0 |
import os
import shutil
from PIL import Image
import cv2
import numpy as np
import tqdm
# 定义原始文件夹和目标文件夹路径
source_folder = './x'
target_folder = './x_mask'
# 确保目标文件夹存在,如果不存在则创建
if not os.path.exists(target_folder):
os.makedirs(target_folder)
for filename in os.listdir(source_folder):
# 检查文件是否为PNG图片并且以_mask结尾
... | Python | 1 |
, peer,
SyncSupplier::return_block_bodies,
|e| format!("Error sending block bodies: {:?}", e)),
GetBlockHeadersPacket => SyncSupplier::return_rlp(
io, &rlp, peer,
SyncSupplier::return_block_headers,
|e| format!("Error sending block headers: {:?}", e)),
GetReceiptsPacket => SyncSupplie... | Rust | 0 |
"This typically occurs on Windows machines. The suggested solution is to modify "
"HKEY_CLASSES_ROOT in the registry to specify the content type for JavaScript "
"files.\n"
"\n"
"[HKEY_CLASSES_ROOT\\.js]\n"
'"Con... | Python | 1 |
put.parse();
/// assert!(invalid.is_err());
/// ```
LayerName,
LayerNameError,
r"^(?!(build|launch|store)$).+$"
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layer_name_validation_valid() {
assert!("gems".parse::<LayerName>().is_ok());
assert!("Abc 123.-_!".parse... | Rust | 0 |
[4], "bounceback")
@pytest.fixture
def simple_2d_block():
return Block([(5, 6), (2, 10)], [4, 4], "bounceback")
@pytest.fixture
def small_circle():
return Circle((8, 8), 4, [4, 4], "bounceback")
@pytest.fixture
def circle_2():
return Circle((16, 16), 10, [8, 8], "bounceback")
@pytest.fixture
def ci... | Python | 1 |
import logging
from celery import shared_task
from pymysql.err import OperationalError
from magplan.models import Post
logger = logging.getLogger()
@shared_task(
autoretry_for=(OperationalError,),
retry_kwargs={'max_retries': 5, 'countdown': 10}, # Retry up to 3 times with a 60 seconds delay between retri... | Python | 1 |
md.png"), "Command"),
(QPixmap("images/_plugin.png"), "Plugin"),
(QPixmap("images/_results.png"), "Result")
]
# Loop to create a button for each item in the icons list
for icon, tooltip in icons:
button = QPushButton() # Creating a button
button.... | Python | 1 |
import requests
class SSRFTestingTool:
def __init__(self):
self.payloads = [
"http://localhost:8080",
"http://127.0.0.1/admin",
"http://target-website.com/internal-service"
]
def generate_payload(self):
print("SSRF Payloads:")
for payload in ... | Python | 1 |
mpilerShutUp>::poll_close(sink, cx).map_err(|e| e)
}
}
/// Registers a message receiver for a specific message type (as defined by the implementation `M`).
///
/// # Panics
///
/// Panics if a message receiver for this message type is already registered.
///
/// # TODO
///
... | Rust | 0 |
_points.append(i)
dist2poi.append(dist)
close_points = np.array(close_points)
print("Number of close points: %d\n"%close_points.size)
prev = 0 # Keeps in memory the last timestamp displayed
for i in range(close_points.size):
# If the delta between timestamps is bigger than the group size, or if it's t... | Python | 1 |
(label="クラスタ数決定完了!", state="complete")
# クラスタリング実行
with st.status("K-meansクラスタリング実行中...", expanded=True) as status:
# 最終的なスケーリング
if use_scaling:
scaler_final = StandardScaler()
X_scaled = scaler_final.fit_transform(X)
else:
X_scaled = X.values
... | Python | 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.exceptions import UserError
@tagged('post_install_l10n', 'post_install', '-at_install')
class PaymentReferenceTest(AccountTestInvoi... | Python | 1 |
x4 = i32x4::new(9, 10, 11, 12);
let b: i16x8 = i16x8::new(1, 2, 3, 4, 9, 10, 11, 12);
let c: i16x8 = i16x8::new(10, 10, 10, 10, 20, 0, 2, 4);
let e: i32x4 = i32x4::new(20, 20, 20, 20);
let r: i32x4 = transmute(vabal_high_s16(transmute(a), transmute(b), transmute(c)));
assert_eq!(... | Rust | 0 |
Addr,
proposal: &Proposal,
) -> StdResult<()> {
PROPOSALS.save(storage, prop_id, proposal)?;
IDX_PROPS_BY_STATUS.save(storage, (proposal.status as u8, prop_id), &Empty {})?;
IDX_PROPS_BY_PROPOSER.save(storage, (proposer.clone(), prop_id), &Empty {})?;
Ok(())
}
fn create_deposit(
storage: &mut ... | Rust | 0 |
from django.urls import include, path
from Account.views import ReferralToken, SendPasswordResetEmailView, UserAudioFilesListView, UserChangePasswordView, UserDeleteFilesListView, UserDocumentsFilesListView, UserEarningsView, UserFavouriteFilesListView, UserFilesListView, UserImagesFilesListView, UserLoginView, UserOth... | Python | 1 |
std::slice::from_raw_parts_mut::<FFIBalance>(buff, buff_len);
// let ffi_balances: Vec<FFIBalance> = resp.into_iter().map(to_ffi_balance).collect();
// let l = std::cmp::min(buff_len, ffi_balances.len());
//
// balances[0..l].copy_from_slice(&ffi_balances[0..l]);
// (*actual_buff_len) = l;
// ... | Rust | 0 |
out, i, spec.width
)
}
x_to_2_to_n.pin_mut().sqr();
let mut fac = copy_polyrem(&x_to_2_to_n);
fac += &x;
// (fac = x^(2^n) + x)
cumulative_prod *= &fac;
}
drop(x_to_2_to_n);
let reduced_prod = cumulative_prod.rep();
drop(cumulative_prod);
l... | Rust | 0 |
pub TIMER1: nrf52::TIMER1,
/// nRF52 peripheral: TIMER2
pub TIMER2: nrf52::TIMER2,
/// nRF52 peripheral: RTC0
pub RTC0: nrf52::RTC0,
/// nRF52 peripheral: TEMP
pub TEMP: nrf52::TEMP,
/// nRF52 peripheral: RNG
pub RNG: nrf52::RNG,
/// nRF52 peripheral: ECB
pub ECB: nrf52::... | Rust | 0 |
import os
import shutil
import tempfile
from fastapi import UploadFile
def process_vapi_webhook(webhook_data):
message_data = webhook_data["message"]
return {
"source": "vapi",
"transcript": message_data["transcript"],
"summary": message_data["analysis"]["summary"],
"is_succes... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from tools.sphinx_ext import changelog, missing_references
if TYPE_CHECKING:
from sphinx.application import Sphinx
def setup(app: Sphinx) -> dict[str, bool]:
ext_config = {}
ext_config.update(missing_references.setup(app))
ext_conf... | Python | 1 |
# Copyright (C) 2010-2024 RhodeCode GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# (only), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WIT... | Python | 1 |
.4f' % data.E_auc
S_scores.append(data.S_auc)
E_scores.append(data.E_auc)
if len(scores) > 0:
name = pipeline.get_name() + '_' + classifier_name
summary = get_score_summary(name, scores)
summaries.append... | Python | 1 |
# Break- Based on the condition exit the loop
for i in range(0,10):
if i == 6:
print(i)
else:
print("No o/p")
# | i | condition | o/p |
# | 0 | 0 == 6 | -> False | O/P -> No o/p
# | 1 | 1 == 6 | -> False | O/P -> No o/p
# | 2 | 2 == 6 | -> False | O/P -> No o/p
# | 3 | 3 == 6 | -> False | O/P -... | Python | 1 |
;
let front;
let back;
match nodes[index].kind {
AreaNodeKind::Branch(ref mut b) => {
b.axis = axis;
b.dist = dist;
front = b.front;
back = b.back;
}
AreaNodeKind::Leaf => return,
}
... | Rust | 0 |
# 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 |
egister the static path (without version param - Home Assistant will handle it)
await hass.http.async_register_static_paths([
StaticPathConfig(js_url, str(js_path), cache_headers=False),
])
# Get version from manifest for cache busting
manifest_version = get_version()
# Register as a Lovel... | Python | 1 |
#!/usr/bin/env python
# encoding: utf-8
from .fetcher import *
from .territory import *
class KKBOXAlbumFetcher(Fetcher):
'''
Get metadata and tracks of an album.
See `https://docs-en.kkbox.codes/v1.1/reference#albums`.
'''
@assert_access_token
def fetch_album(self, album_id, terr=KKBOXTe... | Python | 1 |
"""Config flow for SRP Energy."""
from __future__ import annotations
from typing import Any
from srpenergy.client import SrpEnergyClient
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ID, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
fro... | Python | 1 |
type(filtered_source, filtered_destination);
}
// Prints 64 bit signed integer
#[no_mangle]
pub extern "C" fn print_integer(num64: i64) {
println!("{}", num64);
}
// Prints 8 bit signed byte
#[no_mangle]
pub extern "C" fn print_byte(num8: i8) {
println!("{}", num8);
}
// Prints 64 bit float
#[no_mangle]
pub ... | Rust | 0 |
if not self.save_path_var.get(): messagebox.showerror("错误", "请先选择保存位置"); return
self._add_task(user_input, self.save_path_var.get()); self.url_entry.delete(0, tk.END)
def _add_task(self, user_input, save_path):
self.task_id_counter += 1
task_id = f"task_{int(time.time() * 1000)}_{self.tas... | Python | 1 |
import numpy as np
import os
_base_ = "../../default.py"
##################################################
### NARUTO (General)
##################################################
general = dict(
dataset = "Replica",
scene = "office1",
num_iter = 2000,
)
##################################################... | Python | 1 |
import sys
colorfile = sys.argv[1]
R = int(sys.argv[2])
G = int(sys.argv[3])
B = int(sys.argv[4])
def dtc(P, Q):
d = 0
for p, q in zip(P, Q):
d += abs(p - q)
return d
def find_color(file, R, G, B):
closest_color = None
min_distance = 100000000
with open(file) as file:
for line in file:
words = line.spl... | Python | 1 |
),
(
IXIN,
nop,
CacheFunction::IXIN,
INTEGER_LOAD_STORE,
req::LS,
Cap::no_req
),
(
IXLDT,
nop,
CacheFunction::IXLDT,
INTEGER_LOAD_STORE,
req::LS,
Cap::no_req
),
(
IXLTG,
cop0::cache::ixltg,
CacheFunction::IXLTG,
INTEGER... | Rust | 0 |
import tkinter as tk
from tkinter import messagebox
import os
def check_winner():
for combo in [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]:
if buttons[combo[0]]["text"] == buttons[combo[1]]["text"] == buttons[combo[2]]["text"] !="":
buttons[combo[0]].config(bg="green")
... | Python | 1 |
= [1.0/len(contributor_ids)] * len(contributor_ids)
logger.info(f"使用等比例假设: {true_ratios}")
return contributor_ids, true_ratios
def extract_v5_features(self, sample_file, sample_peaks):
"""提取V5特征集(继承并扩展Q1的特征提取)"""
logger.info(f"开始提取V5特征 - 样本: {sample_file}")
logger.info(f... | Python | 1 |
oded) => decoded,
Err(e) => {
let err_msg = format!("{:?}", e);
warn!("{}", &err_msg);
return HttpResponse::BadRequest().body(err_msg);
}
};
let mut request_id: String;
if compute_data_ref.request_id.len() > 0 {
request_id = compute_data_ref.reque... | Rust | 0 |
es the average and current value"""
def __init__(self, is_ddp):
self.is_ddp = is_ddp
self.reset()
def reset(self):
self.val = 0.0
self.avg = 0.0
self.sum = 0.0
self.count = 0.0
def update(self, val, n=1):
self.val = val
self.sum += val * n
... | Python | 1 |
report_path: 报告保存路径
Returns:
报告文件路径
"""
logger.info("生成风险报告")
# 设置默认日期范围
if end_date is None:
end_date = datetime.now()
if start_date is None:
start_date = end_date - timedelta(days=30) # 默认30天
... | Python | 1 |
::warn!("Unhandled file key {:?}", file_key);
continue;
}
}
("ANCILLIARY_SERVICES",Some("CONTRACTAGC"), version) if version <= 1_i32 => {
#[cfg(feature = "ancillary_services")]
{
let d: Vec<d... | Rust | 0 |
def armstrong(n):
original = n
last = 0 # initialize to 0
while n > 0:
last += (n % 10) ** 3
n //= 10
return last == original # boolean return
if __name__ == "__main__":
num = int(input("Enter the number"))
print(armstrong(num))
'''
this function checks if a given number n i... | Python | 1 |
nputs, [-1, self.final_size])
inputs = tf.expand_dims(inputs, axis=1)
inputs = tf.tile(inputs, [1, self.trn_num_frames, 1])
multi_scale_rel = trn_model.MultiScaleRelation(
self.trn_num_frames, 512, use_mean=self.use_mean)
inputs = multi_scale_rel(inputs)
global ENDING_POINTS
ENDING_POIN... | Python | 1 |
_real_id).unwrap() {
let v_virt_id = id_map.virt_id_of(v_real_id);
dist[u_virt_id][v_virt_id] = edge.get_weight().clone();
}
}
for k in 0..vertex_count {
for &i in &vertices {
let i_virt_id = id_map.virt_id_of(i);
f... | Rust | 0 |
x_length)
return [TextContent(
type="text",
text=f"🌐 网页内容: {url}\n"
f"📊 内容长度: {len(content)} 字符\n"
f"{'='*50}\n"
f"{content}"
)]
except Exception as e:
logger.exception("Webpage fetching failed")
... | Python | 1 |
id=self.course_id)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("expires_at", response.data["field_errors"])
self.assertIn("to_file", response.data["field_errors"])
@get_user_by_username_or_email_patch
@course_instructor_role_patch
@course_staff... | Python | 1 |
k::BlockData;
use models::plasma::{params, AccountMap};
use models::*;
use std::sync::mpsc::{channel, Receiver, Sender};
use storage::ConnectionPool;
use web3::types::{H256, U128, U256};
fn sorted_and_padded_for_deposits(
accounts_updated: AccountMap,
) -> [u64; config::DEPOSIT_BATCH_SIZE] {
assert_eq!(account... | Rust | 0 |
from datetime import datetime, timedelta
users = [
{"name": "John Doe", "birthday": "1985.01.23"},
{"name": "Jane Smith", "birthday": "1990.01.28"},
{"name": "Maria Tramp", "birthday": "1988.01.30"},
{"name": "Jon Snow", "birthday": "1965.02.01"}
]
def get_upcoming_birthdays(users=None):
today=dat... | Python | 1 |
"var_5",
"var_6",
"var_8",
"var_9",
"var_10",
"var_11",
]
# test transform output
pd.testing.assert_frame_equal(sel.transform(X), Xtransformed)
def test_sample_weights():
X = pd.DataFrame(
dict(
x1=[1000, 2000, 1000, 1000, 2000, 3000],
... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# References:
# ELECTRA https://github.com/google-research/elect... | Python | 1 |
d_image)
else:
openpose_keypose = cv2.cvtColor(cond_image, cv2.COLOR_RGB2BGR)
openpose_keypose = resize_numpy_image(
openpose_keypose, max_resolution=opt.max_resolution, resize_short_edge=opt.resize_short_edge)
opt.H, opt.W = openpose_keypose.shape[:2]
if cond_inp_type == 'openpose':
... | Python | 1 |
"""
Write a function to find kth element from the given two sorted arrays.
assert find_kth([2, 3, 6, 7, 9], [1, 4, 8, 10], 5) == 6
"""
def find_kth(a, b, k):
if len(a) > len(b):
return find_kth(b, a, k)
if len(a) == 0:
return b[k-1]
if k == 1:
return min(a[0], b[0])
pa = min(k//... | Python | 1 |
spawn(async move {
let mut req = String::new();
recv.read_to_string(&mut req).await.unwrap();
let mut words = req.split(' ');
match (words.next(), words.next()) {
(Some("GET"), Some(path)) => {
let path = PathBuf::from(WWW).join(path.tr... | Rust | 0 |
import requests
from dotenv import load_dotenv
import os
import json
load_dotenv()
INFO_URL_BASE = os.getenv("INFO_URL_BASE")
INFO_API_KEY = os.getenv("INFO_API_KEY")
GOOGLE_MAPS_BASE = os.getenv("GOOGLE_MAPS_BASE")
BITLY_TOKEN = os.getenv("BITLY_TOKEN")
BITLY_SHORTEN_URL = os.getenv("BITLY_SHORTEN_URL")
def get_... | Python | 1 |
RU: dict[str, str] = {
"/start": "Привет!\n\nЯ эхо-бот для демонстрации работы реляционной базы данных <b>PostgreSQL</b> "
"совместно с <code>aiogram</code>!\n\n"
"Если хотите - можете мне что-нибудь прислать или "
"отправить команду /help",
"/help": "Я бот, созданный д... | Python | 1 |
"""Catch all for categorical functions"""
import warnings
import pytest
import numpy as np
import matplotlib as mpl
from matplotlib.axes import Axes
import matplotlib.pyplot as plt
import matplotlib.category as cat
from matplotlib.testing.decorators import check_figures_equal
class TestUnitData:
test_cases = [(... | Python | 1 |
pub diagnostics_signs_max: Option<usize>,
pub diagnostics_max_severity: DiagnosticSeverity,
pub diagnostics_ignore_sources: Vec<String>,
pub document_highlight_display: HashMap<u64, DocumentHighlightDisplay>,
pub selection_ui_auto_open: bool,
pub use_virtual_text: UseVirtualText,
pub echo_pr... | Rust | 0 |
Descriptor {
Self::descriptor_static()
}
fn new() -> ValidatorSet {
ValidatorSet::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT... | Rust | 0 |
> {
// Request userid
let msg = "Welcome to Idlecoin!\nPlease enter your account: ".to_string();
stream.write_all(msg.as_bytes())?;
// Read userid
let mut id_raw: [u8; 1024] = [0; 1024];
let _ = stream.read(&mut id_raw[..])?;
// Calculate the hash of the userid
let mut hash = xxh3::Xxh... | Rust | 0 |
card_number = {"A": 1, "2": 2, "3": 3, "4": 4, "5": 5,
"6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
"J": 11, "Q": 12, "K": 13}
def verification(calculation_order):
try:
result = eval(calculation_order)
except ZeroDivisionError:
return None
return result == 24
d... | Python | 1 |
e for a Constant effect.
///
/// This struct is exclusively for the ::SDL_HAPTIC_CONSTANT effect.
///
/// A constant effect applies a constant force in the specified direction
/// to the joystick.
///
/// \sa SDL_HAPTIC_CONSTANT
/// \sa SDL_HapticEffect
#[repr(C)]
#[derive(Debug, Copy)]
pub struct SDL_HapticConstant {
... | Rust | 0 |
BitMapBackend::with_buffer(&mut buf, (W, H)).into_drawing_area();
let background = RGBColor(19, 43, 33);
root.fill(&background)?;
let caption_style = ("sans-serif", 25_i32, FontStyle::Bold, &WHITE);
let mut chart = ChartBuilder::on(&root)
.x_label_area_size(40_i32)
... | Rust | 0 |
SystemCommitted should hang until when the Paver responds to QueryConfigurationStatus.
#[fasync::run_singlethreaded(test)]
async fn is_current_system_committed_hangs_until_query_configuration_status() {
let (throttle_hook, throttler) = mphooks::throttle();
let env = TestEnv::builder()
.paver_service_bu... | Rust | 0 |
#!/usr/bin/python3
# Copyright 2022 Alibaba Group Holding Limited. All Rights Reserved.
import argparse
import os.path as osp
import sys
sys.path.insert(0, osp.dirname(osp.dirname(__file__)))
from essmc2.utils.config import Config
from essmc2.utils.ext_module import import_ext_module
from essmc2.utils.registry impor... | Python | 1 |
y1 -> x2,y2'. Got {}",
s
))
}
}
impl Line {
fn points(&self) -> Vec<(u16, u16)> {
if self.from.0 == self.to.0 {
// vertical line
(min(self.from.1, self.to.1)..=max(self.to.1, self.from.1))
.map(|y| (self.from.0, y))
.collect()
... | Rust | 0 |
"--digits",
TEST_CASE,
]);
grex.assert().success().stdout(predicate::eq(
"^I ♥♥♥ \\d(?:\\d and ){2}(?:y̆){2} and 💩💩\\.$\n",
));
}
}
}
mod space_conversion {
use super::*;
mod no_repetition {
use super::*;
#... | Rust | 0 |
# uncompyle6 version 3.6.2
# Python bytecode 2.7
# Decompiled from: Python 2.7.17 (default, Oct 23 2019, 08:25:46)
# [GCC 4.2.1 Compatible Android (5220042 based on r346389c) Clang 8.0.7 (https://
# Embedded file name: <NantaID>
import os, sys, string, random, time
preman = ' __ __\n / / / /_ ______ ___ ____ _... | Python | 1 |
ult<()> {
if unsafe {
libc::unlinkat(
dir_fd,
path.as_ptr(),
if dir { libc::AT_REMOVEDIR } else { 0 },
)
} < 0
{
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
#[inline]
pub fn symlinkat(target: &CStr, dir_fd: RawFd, path: &CS... | Rust | 0 |
import os
import numpy as np
from PIL import Image
from pathlib import Path
import cv2
from .dataset_template import DatasetTemplate
class ArgoverseDataset(DatasetTemplate):
def __init__(self, data_info, data_cfg, mode):
super().__init__(data_info, data_cfg, mode)
self.return_right_disp = self.da... | Python | 1 |
tance_id, {})
.get("publicly_accessible", {})
)
self.assertEqual(
publicly_accessible,
False,
f"DB instance {instance_id} is publicly accessible",
)
class AWSProvisionStageTwoBackendTwoServerlessTwoDatabaseTest(
A... | Python | 1 |
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
addresses = addressbook.AddressBook.newMessage()
people = addresses.init('people', 1)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
... | Python | 1 |
utf8(&output.stdout)
.expect("stdout is not utf8! need to handle arbitrary bytes"),
std::str::from_utf8(&output.stderr)
.expect("stderr is not utf8! need to handle arbitrary bytes")
);
}
Ok(())
}
use include_dir::{include_dir, Dir};
use std::path::Path;
use t... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.