text string | label_name string | labels int64 |
|---|---|---|
odes, dtype='int', format='csr')
rp = np.empty([data.num_nodes, self.steps])
inv_deg = ssp.lil_matrix((data.num_nodes, data.num_nodes))
inv_deg.setdiag(1 / adj.sum(1))
P = inv_deg * adj
if self.steps < 5:
Pi = P
for i in range(self.steps):
... | Python | 1 |
ath: &Path, access_type: AccessType) -> Database {
match Database::open(&ledger_path.join("rocksdb"), access_type, None) {
Ok(database) => database,
Err(err) => {
eprintln!("Unable to read the Ledger rocksdb: {:?}", err);
exit(1);
}
}
}
// This function is duplic... | Rust | 0 |
import openai
import os
import json
from dotenv import load_dotenv
from io import BytesIO
import zipfile
import utils
from google.cloud import texttospeech
load_dotenv(os.path.join(os.path.dirname(__file__), '.env'))
openai_api_key = os.environ.get("OPENAI_API_KEY")
client = openai.OpenAI(
api_key=openai_api_key,
... | Python | 1 |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from federatedscope.cv.model.cnn import ConvNet2, ConvNet5, VGG11
def get_cnn(model_config, input_shape):
# check the task
# input_shape: (batch_size, in_channels, h, w) or (in_channels, h, w)
if ... | Python | 1 |
from app.database import PatientDB
from app.patients import generate_mock_patient
from datetime import datetime, timedelta
import random
import json
from app.enums import TriageCategory # Import the enum
def populate_database(num_patients=9):
db = PatientDB(db_name='ed_tracker.db')
with db.get_connection() as... | Python | 1 |
ime_version',
'nvidia_gpu_models',
'nvidia_driver_version',
]
all_cuda_fields = dynamic_cuda_fields + ['cudnn_version']
all_dynamic_cuda_fields_missing = all(mutable_dict[field] is None
for field in dynamic_cuda_fields)
if TORCH_AVAILABLE and not... | Python | 1 |
:chtype can either
// be u32 or u64 depending on the platform, therefore we need an extra .into() at the
// moment.
ncurses::waddch(self.window, (' ' as u32).into());
}
self.print_header();
ncurses::attroff(ncurses::A_STANDOUT());
ncurses::attroff(ncur... | Rust | 0 |
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, UniqueConstraint, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
__abstract__ = True
__table_args__ = {'extend_existing': True}
created_at: Mapped[datetime] = mappe... | Python | 1 |
ject.cpu().numpy(), box_class.cpu().numpy())
for i, box_object in enumerate(patches_object):
max_iou = np.max(iou_matrix[i])
if max_iou < 0.5:
box_object = box_object.cpu().numpy() * np.array([w, h, w, h], dtype=np.float32)
... | Python | 1 |
ion(file, segment.DesignParameters, rail_head_distance)
elif predefined_type == "HELMERTCURVE":
result = _map_helmert_curve(file, segment.DesignParameters, rail_head_distance)
elif predefined_type == "BLOSSCURVE":
result = _map_bloss_curve(file, segment.DesignParameters, rail_head_distance)
... | Python | 1 |
pub blinded_ms: BlindedMasterSecret,
pub blinded_ms_correctness_proof: BlindedMasterSecretCorrectnessProof,
pub nonce: Nonce,
}
impl JsonEncodable for CredentialRequest {}
impl<'a> JsonDecodable<'a> for CredentialRequest {}
#[derive(Debug, Serialize, Deserialize)]
pub struct CredentialRequestMetadata {
... | Rust | 0 |
from pathlib import Path
from typing import Union
from calibrationpinn.io import ProjectDirectory
from calibrationpinn.io.readerswriters.utility import (
ensure_correct_file_ending,
join_output_file_path,
)
from calibrationpinn.types import PDDataFrame
class PandasDataWriter:
def __init__(self, project_d... | Python | 1 |
null());
}
```
*/
pub struct Container<T>
where
T: SymBorApi<'static>,
{
#[allow(dead_code)] lib: Library,
api: T,
}
impl<T> Container<T>
where
T: SymBorApi<'static>,
{
///Open dynamic link library and load symbols.
pub unsafe fn load<S>(name: S) -> Result<Self, Error>
where
S: AsRe... | Rust | 0 |
> Result<()> {
let home = home_dir().ok_or_else(|| eyre!("Failed to determine home director"))?;
let install_directory = var(XDG_CONFIG_HOME)
.wrap_err("failed to get the install directory")
.map(|config| PathBuf::from(config))
.unwrap_or_else(|_| home.join(".config"))
.join("kus... | Rust | 0 |
from __future__ import annotations
import array
from typing_extensions import assert_type
# Casting to bytes.
buf = b"abcdefg"
view = memoryview(buf).cast("c")
elm = view[0]
assert_type(elm, bytes)
assert_type(view[0:2], memoryview[bytes])
# Casting to a bool.
a = array.array("B", [0, 1, 2, 3])
mv = memoryview(a)
bo... | Python | 1 |
254, 312,
];
#[inline]
pub fn forward(code: u8) -> u16 {
FORWARD_TABLE[code as uint]
}
#[inline]
pub fn backward(code: u16) -> u8 {
match code {
128 => 0, 129 => 1, 130 => 2, 131 => 3, 132 => 4, 133 => 5, 134 => 6,
135 => 7, 136 => 8, 137 => 9, 138 => 10, 139 => 11, 140 => 12,
141 => ... | Rust | 0 |
/// The currency is not enabled in protocol.
NotValidUnderlyingAssetId,
/// Error that never should happen
InternalError,
/// Pool not forund in liquidity-pools storage
PoolNotFound,
}
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
/// MNT speed ha... | Rust | 0 |
aad = [0u8; AAD_LEN];
aad[0] = TASK_APP_ID;
aad[1..].copy_from_slice(version_id.as_bytes());
aead::Aad::from(aad)
}
}
/// Secret represents a secret key as used for encryption and decryption.
pub(super) struct Secret(pub(super) Vec<u8>);
impl From<Vec<u8>> for Secret {
fn from(bytes: ... | Rust | 0 |
import os
os.environ["ONEFLOW_MLIR_CSE"] = "1"
os.environ["ONEFLOW_MLIR_ENABLE_INFERENCE_OPTIMIZATION"] = "1"
os.environ["ONEFLOW_MLIR_ENABLE_ROUND_TRIP"] = "1"
os.environ["ONEFLOW_MLIR_FUSE_FORWARD_OPS"] = "1"
os.environ["ONEFLOW_MLIR_FUSE_OPS_WITH_BACKWARD_IMPL"] = "1"
os.environ["ONEFLOW_MLIR_GROUP_MATMUL"] = "1"
o... | Python | 1 |
n_layers: 2,
dropout_prob: 0.1,
layer_dropout_prob: 0.1,
layer_norm_eps: 0.01,
},
)
.unwrap();
let layer1 = LayerOutput::EncoderWithAttention(HiddenLayer {
attention: Tensor::zeros(&[1, 3, 2], (Kind::Float,... | Rust | 0 |
d, Write};
mod builder;
pub use builder::Stmpe1600Builder;
mod device;
use device::{Register, Stmpe1600Device};
mod pins;
use pins::modes;
pub use pins::Pin;
/// The default I²C address for the STMPE1600.
pub const DEFAULT_ADDRESS: u8 = 0x42;
/// The types that the pins on the STMPE1600 may be configured as.
#[allow... | Rust | 0 |
st BASIC_ROM: &'static [u8] = include_bytes!("../../rsrc/basic_rom.img");
#[test]
fn test_dec_basic_rom() {
// https://www.pagetable.com/c64disasm/
//
// => starts at 0xa000, subtract it within the loo
//
// NOTE: the website shows some absolute addresses which are in fa... | Rust | 0 |
from os.path import join
from typing import Dict, List
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes import Axes
from corebehrt.functional.utils.azure_save import save_figure_with_azure_copy
def plot_hist(p_exposure, output_dir):
fig, ax = plt.subplots(figsize=(8, 6))
ax.hist(p_exp... | Python | 1 |
complex formatting and tricky test cases !
!**************************************************!
! example 4.1
l = 0
DO r = 1, 10
SELECT CASE (r)
CASE (1)
DO i = 1, 100; IF (i <= 2) THEN ! comment
DO j = 1, 5
DO k = 1, 3
l = l + 1
! uninde... | Python | 1 |
],
suffix: HashMap::new(),
}
}
pub fn new() -> Self {
MarkovGenerator {
rng: None,
prefix: vec![],
suffix: HashMap::new(),
}
}
pub fn generate(&mut self, length: i32) -> String {
let mut res: Vec<String> = vec![];
le... | Rust | 0 |
import requests
from bs4 import BeautifulSoup
import pandas as pd
# URL of the e-commerce website to scrape
URL = "http://books.toscrape.com/"
# Function to get the HTML content of the page
def get_html(url):
response = requests.get(url)
return response.text
# Function to parse the HTML content and extract p... | Python | 1 |
def set_lexer_matchers(self, lexer_matchers: list[LexerType]) -> None:
"""Set the lexer struct for the dialect.
This is what is used for base dialects. For derived dialects
(which don't exist yet) the assumption is that we'll introduce
some kind of *patch* function which could be us... | Python | 1 |
ed();
t
}
/// 1: EVENT_TYPE_WORKFLOW_EXECUTION_STARTED
/// 2: EVENT_TYPE_WORKFLOW_TASK_SCHEDULED
/// 3: EVENT_TYPE_WORKFLOW_TASK_STARTED
/// 4: EVENT_TYPE_WORKFLOW_TASK_COMPLETED
/// 5: EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED
/// 6: EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED
/// 7: EVENT_TYPE_W... | Rust | 0 |
"""
MongoDB索引配置文件
定义所有集合的索引结构
"""
import logging
from pymongo import ASCENDING
from panda_server.config.mongodb_index_manager import sync_collection_indexes
logger = logging.getLogger(__name__)
# 工作流日志索引定义
WORKFLOW_LOGS_INDEXES = [
{
"name": "workflow_logs_by_user_workflow_time_asc_idx",
"keys": [... | Python | 1 |
::Unsafe,
"Normal" => Unsafety::Normal,
e => panic!("Found unknown unsafety: {}", e),
};
let abi = match table.get::<_, String>("abi")?.as_str() {
"Cdecl" => Abi::Cdecl,
"C" => Abi::C,
"Ru... | Rust | 0 |
n".join(main_blocks):
if check_only:
return True
else:
print(f"Overwriting {file}.")
with open(file, "w") as f:
f.write("\n".join(main_blocks))
def sort_imports_in_all_inits(check_only=True):
failures = []
for root, _, files in os.walk(PATH_T... | Python | 1 |
effective_sample_size' in diagnostics:
f.write("各组分有效样本量:\n")
for i, ess in enumerate(diagnostics['effective_sample_size']):
f.write(f" Mx_{i+1}: {ess:.0f}\n")
if diagnostics['convergence_issues']:
f.write(f"收敛问题: {', '.join(diagnostics['convergence_... | Python | 1 |
ltHash>, A: Allocator = Global> {
Occupied(OccupiedEntry<'a, K, V, H, A>),
Vacant(VacantEntry<'a, K, V, H, A>),
}
impl<'a, K, V, H, A> Entry<'a, K, V, H, A>
where
K: Eq + Hash + Clone + 'a,
V: Value + 'a,
H: BuildHasher + Default,
A: Allocator,
{
/// Ensures a value is in the entry by inser... | Rust | 0 |
# ---------------------------------------------------------------------
# Copyright (c) 2025 Qualcomm Technologies, Inc. and/or its subsidiaries.
# SPDX-License-Identifier: BSD-3-Clause
# ---------------------------------------------------------------------
from __future__ import annotations
import numpy as np
import... | Python | 1 |
ability>>> {
<Self as RtActivatable<IUserConsentVerifierStatics>>::get_activation_factory().check_availability_async()
}
#[inline] pub fn request_verification_async(message: &HStringArg) -> Result<ComPtr<foundation::IAsyncOperation<UserConsentVerificationResult>>> {
<Self as RtActivatable<IUserC... | Rust | 0 |
import math
import json
import numpy as np
vocab_size = 0
frequencies = []
with open('../train_scores.npy.txt') as loss_file:
for line in loss_file:
vocab_size += 1
frequency = int(line.strip().split('\t')[1])
frequencies.append(frequency)
print(vocab_size)
def additional_embeddings(log_... | Python | 1 |
_drop: Some(Box::new(move || unsafe {
// Drop all callbacks.
if !cancel_cb_param.is_null() {
drop(Box::from_raw(cancel_cb_param as *mut ContinueCancelCb));
}
})),
_p: PhantomData,
}
}
/// Creates a user confirmation dialog screen.
/// `result` - w... | Rust | 0 |
(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Gets a page by blog id and page id.
///
/// A builder for the *get* method supported by a *page* resource.
/// It is not used directly, but through a `PageMethods` instance.
///
/// # Example
///
/// Instantiate a resource m... | Rust | 0 |
linecard all
"""
cli_command = ['show redundancy linecard all']
def cli(self, output=None):
if output is None:
output = self.device.execute(self.cli_command[0])
# 9 - 0 Active Stdby Warm 0 - Active Primary
p1 = re.compile(r'^(?P<slot>... | Python | 1 |
ity > int(laptop_quantity):
print("We don't have Enough Laptops in Stock. Sorry for the Inconvenience.")
#buy_more = False
user_quantity = int(input("How many Laptops would you like to Purchase: "))
else:
break
if user_quantity <= 0... | Python | 1 |
,
},
PrettyDuration(self.duration)
);
}
}
/// What item should be debug printed
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugOption {
Spec,
Query,
Layout,
Graph,
/// Stop just before the search starts, to let the user see what's been printed out wit... | Rust | 0 |
import asyncio
import logging
from fastapi import FastAPI
from services.fastapi_endpoint.fastapi_app import app
is_running = False
api_loop = None
api_task = None
async def start_api():
global is_running, api_loop, api_task
is_running = True
api_loop = asyncio.get_running_loop()
try:
imp... | Python | 1 |
},
/*
* {
* "description": "Cloudflare 'Nimbus2021' Log",
* "key": "<KEY>
* "maximum_merge_delay": 86400,
* "operated_by": [
* 1
* ],
* "url": "ct.cloudflare.com/logs/nimbus2021/"
* }
*/
&sct::Log {
description: "Cloudflare 'Nimbus2021' ... | Rust | 0 |
thod to check, if the rule is a CSS rule.
@return flag indicating a CSS rule (boolean)
"""
return self.__cssRule
def regExpPattern(self):
"""
Public method to get the regexp pattern of the rule.
@return regexp pattern (QRegExp)
"""
... | Python | 1 |
* y_offset,
**ARROW_VARIANTS[3],
width=MAIN_STROKE_WIDTH,
)
)
img.append(
arrow(x_0, y_0, x_0, y_0 + B_LEN, **ARROW_VARIANTS[4], width=MAIN_STROKE_WIDTH)
)
img.append(
arrow(x_0, y_0, x_0, y_0 - B_LEN, **ARROW_VARIANTS[4], width=MAIN_STROKE_WIDTH)
)
... | Python | 1 |
"{} {} {} {} {}",
note,
note.to_midi(),
note.to_cv(),
note.to_hz(),
note_from_midi
);
assert!(note == note_from_midi);
assert!(note.to_midi() == midi[i]);
assert!((note.to_hz() - hz[i]).abs() ... | Rust | 0 |
, 27, 5,
92, 30, 90, 36, 38, 79, 84, 50, 40, 8, 59, 24, 81, 63, 66, 74, 86,
95, 99, 16, 52, 105, 69, 46, 42, 33, 21, 13, 10, 28, 77, 6, 61, 93,
103, 31, 26, 91, 89, 37, 83, 39, 58, 80, 65, 85, 98, 51, 68, 41, 20,
9, 76, 60, 102, 25, 88, 82, 57, 64, 97, 67, 19, 75, 101, 87... | Rust | 0 |
impl From<MouseButton> for u8 {
fn from(b: MouseButton) -> u8 {
match b {
MouseButton::Left => 1,
MouseButton::Middle => 2,
MouseButton::Right => 3,
MouseButton::ScrollUp => 4,
MouseButton::ScrollDown => 5,
}
}
}
impl TryFrom<u8> for... | Rust | 0 |
PARAM_STRING_ZERO),
};
ctx.require(params.hash.exists(), "missing mandatory hash");
ctx.require(params.hname.exists(), "missing mandatory hname");
ctx.require(params.hname_zero.exists(), "missing mandatory hnameZero");
ctx.require(params.int64.exists(), "missing mandatory int64");
ctx.require(pa... | Rust | 0 |
d_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
# 配置 data_load_frame 的 grid 权重
data_load_frame.grid_rowconfigure(0, weight=1)
data_load_frame.grid_columnconfigure(0, weight=1)
# 删除按钮,保留拖入功能
self.drop_area_xyxy = ttkb.Label(data_load_frame, text="Drag Here (XYXY)"... | Python | 1 |
"asset-pipeline")]
use std::path::Path;
use edict::world::World;
use eyre::WrapErr;
use goods::Loader;
use scoped_arena::Scope;
#[cfg(feature = "client")]
use evoke::client::ClientSystem;
#[cfg(feature = "server")]
use evoke::server::ServerSystem;
#[cfg(feature = "visible")]
use winit::window::{Window, WindowBuild... | Rust | 0 |
import pytest
from vsa_explainer import (
load_crippen_data,
get_vsa_bin_bounds,
get_bin_bounds,
visualize_vsa_contributions,
)
def test_load_crippen_data():
data = load_crippen_data()
assert isinstance(data, list)
# each entry is a tuple of length 5
assert all(len(t) == 5 for t in data... | Python | 1 |
ri) + 1
)
# exclude the objects with less than 1000 pixels in 3D
gt_data_ori = cc3d.dust(
gt_data_ori, threshold=voxel_num_thre3d, connectivity=26, in_place=True
)
# remove small objects with less than 100 pixels in 2D slices
for slice_i in range(gt_data_ori.shape[0]):
gt_i... | Python | 1 |
import itertools
import matplotlib as mpl
import numpy as np
from matplotlib import pyplot as plt
from tqdm import tqdm
from ngboost.distns import Normal
from ngboost.manifold import manifold
from ngboost.scores import LogScore
if __name__ == "__main__":
rvs = np.random.randn(500)
nll_fn = (
lambda... | Python | 1 |
import codecs # to use a consistent encoding
from os import path
from setuptools import setup, find_packages # prefer setuptools over distutils
# Get the long description from the README file
PATH = path.abspath(path.dirname(__file__))
with codecs.open(path.join(PATH, 'README.rst'), encoding='utf-8') as f:
LONG... | Python | 1 |
ian};
use result::ResultOptionExt;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>;
use std::io::{Read, Write};
pub trait Communicate {
fn send(&mut self, message: &[u8]) -> Result<()>;
fn receive(&mut self) -> Result<Option<Vec<u8>>>;
}
pub trait CommunicateNew {... | Rust | 0 |
(self):
for i in self.sectionExpandButton:
i.update_window()
for i in self.position_buttons:
i.update_window()
for i in self.arrowButtons:
i.setStyleSheet("QToolButton {border: none; color: " + self.mwindow.colorscheme().color + ";}")
p = QtGui.QPalet... | Python | 1 |
&CacheChange> {
self.history_cache.get_change(instant)
}
pub fn add_change(&mut self, instant: &Timestamp, cache_change: CacheChange) {
self.history_cache.add_change(instant, cache_change)
}
pub fn get_all_changes(&self) -> Vec<(&Timestamp, &CacheChange)> {
self.history_cache.get_all_changes()
}... | Rust | 0 |
counts.retain(|_, v| *v != 0);
assert_eq!(get_counts(&buffer), counts);
}
#[test]
fn copy_selections_returns_what_is_expected_in_this_two_tab_in_case() {
use TestEdit::*;
use ReplaceOrAdd::*;
let mut buffer = t_b!("A");
buffer.set_cursor(cur!{l 0 o 0 h l 0 o 1}, Replace);
TestEdit::ap... | Rust | 0 |
from youlexical import lex, SymbolTable
from sylvasyntax import Token, SyntaxAnalyzer
from sylvasemantic import SemanticAnalyzer
from codegeneration import CodeGenerator
from intermediatecode import IntermediateCodeGenerator # Importing the IntermediateCodeGenerator class
def main():
code = """
num rr = 88;
... | Python | 1 |
ret: 1
}
}
}
machine_id: 1001
}
packet {
ftrace_events {
cpu: 0
event {
timestamp: 100003000000
pid: 15
irq_handler_entry {
irq: 100
name : "resource... | Python | 1 |
#[connector_test(schema(schema_1))]
async fn create_and_return_item_woi_1(runner: Runner) -> TestResult<()> {
insta::assert_snapshot!(
run_query!(&runner, r#"mutation {
createOneParent(data: {p: "Parent", id: "Own Id"}){p, id}
}"#),
@r###"{"data":{"createOneParent":... | Rust | 0 |
let top = (n as f64).sqrt() as usize;
for d in 3..top {
if (n % d) == 0
{
if !primes.contains(&(d + n / d)) {
return false;
}
}
}
return true;
}
fn find(n: usize) -> usize {
let start_time = precise_time_s();
let primes = Box::new... | Rust | 0 |
type to a block message.
"""
self.message_type = message_type
self.set_content(message_type.value)
return self
def set_status(self, status: ResponseStatus) -> Message:
"""
Set the status code and message of the message.
"""
self.status_code = status.... | Python | 1 |
ensure_range_impl!($val, $low, $high, fensure)
};
}
/// Internal macro used for implementing other validation macros.
///
/// Not to be directly invoked. Use one of the other `ensure*` macros.
#[macro_export]
macro_rules! ensure_greater_impl {
($val:expr, $low:expr, $ensure:tt) => {
match (&$v... | Rust | 0 |
sage(chat_id=message.from_user.id,text=f"<b>Get All Files in a Single Click!!!\n\n📂 ʟɪɴᴋ ➠ : {g}\n\n<i>Note: This message is deleted in 5 mins to avoid copyrights. Save the link to Somewhere else</i></b>", reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboard... | Python | 1 |
import rospy
import json
import socket
from datetime import datetime,timezone
import paho.mqtt.client as mqtt
import ros_sub
def utc_now_ms():
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def on_connect(client, userdata, reason_code, properties):
print(f"Robot ... | Python | 1 |
2;
pub const MACH_MSG_OOL_VOLATILE_DESCRIPTOR: mach_msg_descriptor_type_t = 3;
pub const MACH_MSG_OPTION_NONE: mach_msg_option_t = 0x0000_0000;
pub const MACH_SEND_MSG: mach_msg_option_t = 0x0000_0001;
pub const MACH_RCV_MSG: mach_msg_option_t = 0x0000_0002;
pub const MACH_RCV_LARGE: mach_msg_option_t = 0x0000_0004... | Rust | 0 |
targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
# 性能指标
predictions = model(images)
p, r, f1 = calculate_metrics(predictions, targets)
val_precision += p
val_recall += r
val_f1 += f1
num_val_batches += 1
... | Python | 1 |
,基本形,です,デス,デス",
"sysdict",
)
check_token(tokens[13], "。", "記号,句点,*,*,*,*,。,。,。", "sysdict")
# Verify that user dictionary tokens are properly identified
user_dict_tokens = [
token for token in tokens if "user" in token.node_type.lower()
]
assert l... | Python | 1 |
_extent, CommandBuffer, Device, Extent2D, ImageView, PipelineCache, RenderPass,
};
use crate::{
depth::{DepthContext, DepthView},
renderer::RenderConfiguration,
scene::{SceneContext, SceneView},
terrain::{TerrainContext, TerrainView},
};
pub struct GameView {
pub depth: DepthView,
pub terrain:... | Rust | 0 |
: Clone> MiniVec<T> {
/// `extend_from_slice` will append each element from `elems` in a left-to-right order, cloning
/// each value in `elems`.
///
/// # Example
///
/// ```
/// let mut vec = minivec::mini_vec![1, 2];
///
/// let s : &[i32] = &[3, 4];
///
/// vec.extend_from... | Rust | 0 |
_dir, "tech_docs.txt"), "w") as f:
f.write(tech_content)
# Financial Report
financial_content = """
Q4 2024 Financial Performance Report
Revenue: $2.4M (up 15% from Q3)
Customer Count: 12,450 (up 8% from Q3)
Data Processing: 45TB processed th... | Python | 1 |
import torch
import numpy as np
from torch import nn
class BiLSTMTagger(nn.Module):
# Module for sequence tagging using bidirectional LSTM and a pretrained embedding
def __init__(self, text, label, emb_dim=50, num_layers=1, hidden_size=100, class_weights=None, dropout_rate=0.3):
super(BiLSTMTagger, se... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
1. ShuffleNetV1:ShuffleNetV1UnitA (stride=1,通道不升维),ShuffleNetV1UnitB (原始stride=2,通道升维,这里改为stride=1)
ShuffleNetV1Block:[ShuffleNetV1UnitA, ShuffleNetV1UnitB] - Pooling - Dropout.
1. ShuffleNetV2:ShuffleNetUnitA (stride=1,通道不升维),ShuffleNetUnit... | Python | 1 |
# Copyright 2020 Open Source Robotics Foundation, Inc.
#
# 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 applicable law... | Python | 1 |
s.
///
/// - `fix` type commits are translated to PATCH releases.
/// - `feat` type commits are translated to MINOR releases.
/// - Commits with `BREAKING CHANGE` in the commits, regardless of type, are translated to MAJOR releases.
///
/// If the project is in major version zero (0.y.z) the rul... | Rust | 0 |
# -*- coding: utf-8 -*-
import re
import os
import json
import urllib
from urlparse import urljoin
import scrapy
def GetDate(text):
matchTerm = re.search(u'''
(?P<year>[\d]+)[\s]*(年|[./-])[\s]*
(?P<month>[\d]+)[\s]*(月|[./-])[\s]*
(?P<day>[\d]+)
''', text, re.X)
if matchTerm:
... | Python | 1 |
"""
Constraints:
- -10^5 <= num <= 10^5
- There will be at least one element in the data structure before calling findMedian.
- At most 5 * 10^4 calls will be made to addNum and findMedian.
<Solution 1: 리스트 활용>
Time Complexity:
- addNum(): O(nlogn)
- 매번 정렬하기 때문
- findMedian(): O(1)
- 정렬된 리스트에서 인덱스 접근
Space Comp... | Python | 1 |
|r| (r.base, r.size))?;
let mem_slot = self.delete_slot(aligned_addr.raw_value(), aligned_size)?;
let kvm_region = kvm_userspace_memory_region {
slot: mem_slot.index | (self.as_id.load(Ordering::SeqCst) << 16),
guest_phys_addr: mem_slot.guest_addr,
memory_size: 0_u6... | Rust | 0 |
icCalendar.html#handleGetMonthLength(int,%20int))
// fn handleGetMonthLength<'env>(&'env self, arg0: i32, arg1: i32) -> __jni_bindgen::std::result::Result<i32, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> {
// // class.path == "android/icu/util/IslamicCalendar", java.flags == PROTECTED,... | Rust | 0 |
config = await self._init_config()
storage = await self._init_storage(config)
logger_group = await self._init_logger_group(config)
token_manager = await self._init_token_manager(storage)
services = await self._init_services(config, token_manager, storage)
i18n = await sel... | Python | 1 |
import pytest
from Обучение.Rest_API.DatabaseHandler import DatabaseHandler
@pytest.fixture
def db_handler():
handler = DatabaseHandler()
yield handler
handler.close() # Закрытие соединения после тестов
def test_add_user(db_handler):
email = "hopi@example.com"
user_id = db_handler.add_user(emai... | Python | 1 |
gates: RefCell<StatsigGates>,
}
impl StatsigBindings {
pub fn new() -> StatsigBindings {
return StatsigBindings {
statsig_enabled: Cell::new(false),
statsig_gates: RefCell::default(),
};
}
pub fn check_statsig_enabled(&self) {
if !self.statsig_enabled.get() {
let statsig_enabled = ... | Rust | 0 |
print("======" "DESAFIO 96" "======")
def área(l, c):
print('-=' * 20)
a = l * c
print(f"A área de um terreno {l}m x {c}m é {a}m²")
print(" CONTROLE DE TERRENOS ")
print("-=" * 20)
v = float(input("LARGURA (m): "))
v2 = float(input("COMPRIMENTO (m): "))
área(v, v2)
| Python | 1 |
# Copyright (c) MONAI Consortium
# 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 applicable law or agreed to in writing, so... | Python | 1 |
Compute cell anchor shapes at multiple sizes and aspect ratios for the current feature map.
Args:
anchor_shapes: [w, h] or [w, h, d], sized (N, spatial_dims),
represents N anchor shapes for the current feature map.
dtype: target data type of the output Tensor.
... | Python | 1 |
str) -> Result<Array2<f64>, Box<dyn Error>> {
// unzip file
let file = GzDecoder::new(File::open(path)?);
// create a CSV reader with headers and `;` as delimiter
let mut reader = ReaderBuilder::new()
.has_headers(true)
.delimiter(b',')
.from_reader(file);
// extract ndarray... | Rust | 0 |
lar::*;
use quizx::vec_graph::Graph;
use quizx::decompose::Decomposer;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let debug = true;
let args: Vec<_> = env::args().collect();
let (qs, n_ccz, seed) =
if args.len() >= 4 {
(args[1].parse().unwrap(),
args[2].parse().u... | Rust | 0 |
import _plotly_utils.basevalidators
class WeightsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="weightsrc", parent_name="scatter3d.hoverlabel.font", **kwargs
):
super(WeightsrcValidator, self).__init__(
plotly_name=plotly_name,
... | Python | 1 |
"###
);
insta::assert_snapshot!(
run_query!(&runner, r#"mutation { updateOneParent(where: { id: 1 }, data: { uniq: "u1" }) { id }}"#),
@r###"{"data":{"updateOneParent":{"id":1}}}"###
);
insta::assert_snapshot!(
run_query!(&runner, r#"query { findManyChild ... | Rust | 0 |
= l1 = L1.split("=")[1]
bar_labels = conf['order_l2']
group_labels = conf['order_l3']
bar_vals = [[0]*len(group_labels) for i in bar_labels]
bar_sdvs = [[0]*len(group_labels) for i in bar_labels]
for b in range(len(bar_labels)):
l2 = bar_labels[b]
for g in range(len(group_labels)):
... | Python | 1 |
import logging
import pydantic
import pydantic_settings
import reflex
from rxconfig import config
from .ragnroll import app
log = logging.getLogger("ragnroll")
def load():
from .backend import router
from .backend.endpoint import search
from .backend.endpoint.resource import expertise
from .page i... | Python | 1 |
from eth_account import Account as EthAccount
from eth_account.signers.local import LocalAccount
from eth_utils import to_checksum_address
from flask import current_app as app
from hexbytes import HexBytes
from app.extensions import w3
class Account(LocalAccount):
@staticmethod
def from_key(private_key: str)... | Python | 1 |
import json
import time
from vllm_model import Qwen7BChatModel
from rerank.rerank_model import reRankLLM
from retriever.chroma_retriever import ChromaRetriever
from retriever.bm25_retriever import BM25
def get_emb_bm25_merge(faiss_context, bm25_context, query):
"""合并FAISS和BM25召回结果构造prompt"""
max_length = 2500
... | Python | 1 |
"""
Test slider value logic
"""
import vcs.vtk_ui
from vtk_ui_test import vtk_ui_test
class test_vtk_ui_slider_values(vtk_ui_test):
def __init__(self):
self.failed = False
self.updated = False
super(test_vtk_ui_slider_values, self).__init__()
def do_test(self):
self.win.SetSize(... | Python | 1 |
ansfer call decodes back to contract type");
assert!(contract_call == contract_call_decoded);
}
}
<filename>src/sox_utils.rs<gh_stars>0
/// LibSOX read and write WAV file in Rust.
///
/// Author: <NAME>
/// Date: 2022.01.01
///
/// Description: This is a simple example of the implementation and usage of a... | Rust | 0 |
)
}
}
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published b... | Rust | 0 |
"""Statistics analyzer for HotShot."""
import profile
import pstats
import hotshot.log
from hotshot.log import ENTER, EXIT
def load(filename):
return StatsLoader(filename).load()
class StatsLoader:
def __init__(self, logfn):
self._logfn = logfn
self._code = {}
self._stack = []
... | Python | 1 |
(*curr).type_0,
);
}
}
}
/*
* (adx ady bchar achar) endchar
*/
if (*cd).flags & 1i32 << 2i32 != 0 {
let mut seac: [f64; 4] = [0.; 4];
seac[0] = (*cd).seac.adx;
seac[1] = (*cd).seac.ady;
seac[2] = (*cd).seac.bchar as f64;
s... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.