text string | label_name string | labels int64 |
|---|---|---|
# LSTM 的基本原理
# 记忆单元(Cell State):LSTM 的核心是细胞状态,它像传送带一样,在序列中传递信息。信息可以在细胞状态中流动,受到最小程度的修改,从而保持长期的依赖信息。
# 门控机制:
# 遗忘门(Forget Gate):决定应该从细胞状态中遗忘哪些信息。
# 输入门(Input Gate):决定哪些新的信息需要添加到细胞状态中。
# 输出门(Output Gate):决定从细胞状态中输出哪些信息。
# 通过这些门控,LSTM 可以选择性地记忆或遗忘信息,从而在处理长序列时保持稳定的梯度。
import torch
import ... | Python | 1 |
toperator = {:?},\n\ttype = {},\n\ta = {:?},\n\tb = {:?},\n\tc = {:?},\n)",
operator,
r#type,
a,
b,
c,
);
let (imms, args) = match operator.immediates_arity() {
0 => {
assert_eq!(operator.parameters_arity(), 3);
... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from __future__ import annotations
from typing_extensions import TypedDict
from ..._types import SequenceNotStr
__all__ = ["DestroyWithAssociatedResourceDeleteSelectiveParams"]
class DestroyWithAssociatedResourceDeleteSelectiveP... | Python | 1 |
_set_input_mode(mode: u8) -> KEPSStatus;
pub fn k_eps_set_heater(cmd: u8, heater: u8, mode: u8) -> KEPSStatus;
pub fn k_eps_reset_system_config() -> KEPSStatus;
pub fn k_eps_reset_battery_config() -> KEPSStatus;
pub fn k_eps_reset_counters() -> KEPSStatus;
pub fn k_eps_get_housekeeping(buff: *mut Ep... | Rust | 0 |
, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct AuraReport {
// The first skipped slot.
start_slot: usize,
// The number of times authorities were skipped.
skipped: usize,
}
impl AuraReport {
/// Call the closure with (validator_indices, punishment_count) for each
/// validator to punish... | Rust | 0 |
, 0x00400000,
0x00488AF0 => increment_death_scores(@edi *mut Unit, @edx u8);
0x004465C0 => choose_placement_position(u32, u32, *mut Point, u32, @ecx *mut Unit) -> u32;
0x00473FB0 => update_building_placement_state_hook(*mut Unit, u8, u32, u32, u16, u8, u8, u8, u8) -> u32;
0x004A13C0 => ai_spellcast(bool... | Rust | 0 |
import os.path
import h5py
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks
from src.general import *
from src.general import *
from src.general.figure import set_figure
datapath1 = r"D:\ExpData\SPE\20250513_SPE_hBN_SEM_array\hBN-1-1\measurement-1.h5"
def the_figure(ax):
"""拟... | Python | 1 |
let mut buffered = BufReader::new(input);
let mut input = String::new();
buffered.read_line(&mut input)?;
let wire1_path = get_wire_path(&input)?;
let wire1: HashSet<&Point> = wire1_path.iter().collect();
let mut input = String::new();
buffered.read_line(&mut input)?;
let wire2_path =... | Rust | 0 |
'''
ida_callstrings_static.py - string deobfuscation for Hodur
Takahiro Haruyama (@cci_forensics)
'''
import idaapi
idaapi.require('hexrays_utils', package='*')
from hexrays_utils import *
g_DEBUG = False
g_CACHE = True
g_memcpy_names = ['qmemcpy', 'wmemcpy', 'strcpy']
def info(msg):
print("\033[34m\033[1m[*]\03... | Python | 1 |
, Gf256)> = shares
.iter()
.map(|s| {
(
Gf256::from_byte(s.member_index),
Gf256::from_byte(s.share_value[i]),
)
})
.collect();
let poly = lagrange::interpolate(&points);
let y = poly.evaluate_at(Gf256::from_byte(x));
ret_share.share_value.push(y.to_byte());
}
Ok(ret_s... | Rust | 0 |
tensors))
},
Err(err) => return Err(err)
}
}
fn assemble_scalar<T: Copy, F>(vs: &mut [Vec<f64>], vi: &[T], f: F)
where F: Fn(T) -> f64 {
for (a, b) in vs.iter_mut().zip(vi.iter().map(|x| f(*x))) {
a.push(b)
}
}
fn assemble_tensor<T: Copy, F>(vs: &mut [Vec<f64>], vt: &... | Rust | 0 |
###############################',
'#',
f'# {value}',
'#',
'#######################################################################',
newline
])
... | Python | 1 |
_color = colors::dragged_rotation_angle_lines();
self.draw_line(rp.point, mouse_start_resized, 1.0, line_color)?;
self.draw_line(rp.point, rd.mouse_coords, 1.0, line_color)
}
fn draw_photo_border_rectangle(&self, photo: &Photo, color: Vec4) -> Result<(), Error> {
let draw_corner_line... | Rust | 0 |
sk from the two sequences passed to be used in a sequence-pair classification task.
A BERT sequence pair mask has the following format:
::
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
If :obj:`token_ids_1` is :obj:`None`, this method ... | Python | 1 |
. low <= n < high
Some(
self.malicious_public_api_endpoints
.remove(rng.gen_range(0..self.malicious_public_api_endpoints.len())),
)
} else {
None
}
}
/// Returns a permutation of the available malicious [IcEndpoint]. The
... | Rust | 0 |
numbers = []
for i in range(1, 101):
numbers.append(i)
print(numbers)
# The option below is an example of list comprehensions
numbers = [i for i in range(1, 101)]
print(numbers)
# Imagine that we now want to generate numbers from 1 to 100 again, but we want to skip numbers that are divisible by three.
# Notice th... | Python | 1 |
detach_from_network
pub fn new(network: i32) -> DetachLoadBalancerFromNetworkRequest {
DetachLoadBalancerFromNetworkRequest {
network,
}
}
}
<filename>pallets/template/src/lib.rs
#![cfg_attr(not(feature = "std"), no_std)]
/// Edit this file to define custom logic or remove it if i... | Rust | 0 |
--------------------------------------------------- */
pub const TYPE_PARSE_FAILED: &str = "Configuration File Parse Failed: ** type ** Is not correct.";
pub const OVERWRITE_PARSE_FAILED: &str =
"Configuration File Parse Failed: ** overwrite_emoji ** Is not correct.";
use core::{
mem,
sync::atomic::{AtomicBoo... | Rust | 0 |
from langchain_core.prompt_values import StringPromptValue
from langchain_core.prompts import (
BasePromptTemplate,
StringPromptTemplate,
check_valid_template,
get_template_variables,
jinja2_formatter,
validate_jinja2,
)
from langchain_core.prompts.string import _get_jinja2_variables_from_templa... | Python | 1 |
match &segment_size {
Lit::Int(seg_size_int) => {
seg_size_int.base10_parse::<u8>().unwrap()
},
_ => {
span.unwrap().error("Segment size has to be an int").emit();
0u8
}
};
let segment_type = match segment_size_int {
1 => quote!{u8},
... | Rust | 0 |
_calculate_area(m,mid_point,newpr)
area_ratio=area1/area2
result[filename]['spike']['length']=length
result[filename]['spike']['grading_width']=grading_width
result[filename]['spike']['perimeter']=perimeter
result[filename]['spike']['area']=area
result[filename][... | Python | 1 |
when storing a STMOC into a FITS file
///
/// # Info
///
/// The output Array1 stores the STMOC under the nested format.
/// Its memory layout contains each time range followed by the
/// list of space ranges referred to that time range.
/// Time ranges are negatives so that one can distinguish them
/// from space ran... | Rust | 0 |
from_items(items, matching, selected_index, custom_keybindings)
}
#[derive(Debug)]
pub struct RofiSelectedItem<TValue: fmt::Display + Clone, TCommand: fmt::Display + Clone> {
pub index: Option<usize>,
pub value: Option<TValue>,
pub command: Option<TCommand>,
}
impl<TValue: fmt::Display + Clone, TCommand: ... | Rust | 0 |
pub const LZMA_LCLP_MIN: u32 = 0;
pub const LZMA_LCLP_MAX: u32 = 4;
pub const LZMA_LC_DEFAULT: u32 = 3;
pub const LZMA_LP_DEFAULT: u32 = 0;
pub const LZMA_PB_MIN: u32 = 0;
pub const LZMA_PB_MAX: u32 = 4;
pub const LZMA_PB_DEFAULT: u32 = 2;
pub const LZMA_BACKWARD_SIZE_MIN: lzma_vli = 4;
pub const LZMA_BACKWARD_SIZE_... | Rust | 0 |
out_dir / f"stage{stage}_f{str(frac).replace('.', '')}.csv"
stage_df.to_csv(stage_csv, index=False)
print(f"Saved stage {stage} results → {stage_csv}")
all_rows.extend(stage_rows)
# Rank and prune
good = stage_df.copy()
good = good.sort_values(["sharpe", "overall_ret_%"... | Python | 1 |
#!/usr/bin/python3
# Copyright 2022 Carnegie Mellon University.
# Released under a MIT (SEI)-style license, please see LICENSE.md in the project
# root or contact permission@sei.cmu.edu for full terms.
import subprocess
import paramiko
from paramiko import *
def grade_challenge():
results = {}
ssh = param... | Python | 1 |
ds0BundleCompliance.setStatus(
"current"
)
# Export all MIB objects to the MIB builder
mibBuilder.exportSymbols(
"DS0BUNDLE-MIB",
**{"ds0Bundle": ds0Bundle,
"dsx0BondingTable": dsx0BondingTable,
"dsx0BondingEntry": dsx0BondingEntry,
"dsx0BondMode": dsx0BondMode,
"dsx0... | Python | 1 |
: None }
}
pub fn is_none(&self) -> bool {
self.start.is_none() && self.end.is_none()
}
}
impl<T: PartialOrd> Range<T> {
pub fn contains(&self, t: Option<&T>) -> bool {
let t = match t {
None => return self.is_none(),
Some(t) => t,
};
match (&sel... | Rust | 0 |
"""Deprecated module for BaseLanguageModel class, kept for backwards compatibility."""
from __future__ import annotations
from langchain_core.language_models import BaseLanguageModel
__all__ = ["BaseLanguageModel"]
| Python | 1 |
let mut set_cell = Mutation_SetCell::new();
set_cell.set_column_qualifier(column.to_string().into_bytes());
set_cell.set_timestamp_micros(-1);
set_cell.set_value(greeting.to_string().into_bytes());
set_cell.set_family_name(column_family_id.to_string());
let mut mutation = Mutati... | Rust | 0 |
.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Spear', u'Spear D... | Python | 1 |
"""
visualize_nucleus.py: Visualize the results of a nucleus simulation (radial distribution of nucleons).
"""
import argparse
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Visualize nucleus simulation results (radial distribution).")
... | Python | 1 |
Pool(num_cores)
lst_simi = pool.starmap(_simi_comp_operator, tasks)
pool.close()
# extend lst_simi to matrix simi and pad 0s
lst_simi = sum(lst_simi, [])
for i, row_simi in enumerate(lst_simi):
lst_simi[i] = [0]*(i+1) + row_simi
assert sum(map(len, lst_simi)) == l ** 2
logging.info(... | Python | 1 |
_label.setText(_translate("MainWindow", "Source Only"))
self.sim2real_label.setText(_translate("MainWindow", "Sim-to-Real"))
self.client = paramiko.SSHClient()
self.client.load_system_host_keys()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.conne... | Python | 1 |
with tf.GradientTape() as tape:
loss = (10.0 - restored_model(tf.constant(2.0))) ** 2
variables = tape.watched_variables()
grads = tape.gradient(loss, variables)
optimizer.apply_gradients(zip(grads, variables))
return loss
for _ in range(10)... | Python | 1 |
import contextvars
from typing import Optional, NamedTuple
class ExecutionContext(NamedTuple):
"""
Context information about the currently executing node.
Attributes:
node_id: The ID of the currently executing node
list_index: The index in a list being processed (for operations on batches/... | Python | 1 |
class Solution {
public:
vector<int> resultsArray(vector<int>& nums, int k)
{
int n=nums.size();
int t=0;
for(int i=1;i<k;i++) // k window size evaluated first
{
if(nums[i-1]+1==nums[i]) t++; //storing the count of trues
}
vector<int>ans;
i... | Python | 1 |
Vovida Software License v1.0"#,
IS_OSI_APPROVED,
),
("Vim", r#"Vim License"#, IS_FSF_LIBRE),
(
"W3C",
r#"W3C Software Notice and License (2002-12-31)"#,
IS_OSI_APPROVED | IS_FSF_LIBRE,
),
(
"W3C-19980720",
r#"W3C Software Notice and License (1998-07-20... | Rust | 0 |
else:
actor_first = "other"
# 构造新的路径:分类/演员首字/演员名/标题
new_path = (self.root_dir / category /
actor_first / actor_name /
format_folder_name(title, self.config))
... | Python | 1 |
eq!(jpholiday.month_holidays(2000, 12).len(), 1);
}
#[test]
fn test_count_year_2000() {
let jpholiday = JPHoliday::new();
assert_eq!(jpholiday.year_holidays(2000).len(), 15);
}
#[test]
fn test_between_2000() {
let jpholiday = JPHoliday::new();
assert_eq!(
jpholiday.between(NaiveDate::from_ymd(... | Rust | 0 |
encoder from one of the many base formats.
/// Subsequently encode() on this value will encode the supplied `data`.
pub fn with_base(base: multibase::Base, data: &[u8]) -> Result<Multibase> {
Ok(Multibase {
base,
data: Some(data.to_vec()),
})
}
/// Create a mult... | Rust | 0 |
.as_slice(),
[
TestEvent::PhalaMining(mining::Event::MinerSettled(_, v, 0)),
TestEvent::PhalaMining(mining::Event::MinerStopped(_)),
TestEvent::PhalaStakePool(Event::PoolSlashed(0, slashed)),
TestEvent::PhalaMining(mining::Event::MinerReclaimed(_, _, _))
]
if FixedPoint::from_bits... | Rust | 0 |
se if *r>0 {
open.push(*r);
} else {
assert!(open.pop() == Some(-r));
}
}
open
}
pub fn passed_tokens(&self) -> usize {
self.satisfied_rules.iter().filter(|&n| *n == 0).count()
}
pub fn run_tokens(&self) -> usize {
let mut run = 0;
f... | Rust | 0 |
length as usize];
stream.read_exact(&mut padding)?;
Ok(Self {
version,
fcgi_type,
request_id,
content_length,
padding_length,
reserved,
content_data: content,
padding_data: padding,
})
}
}
impl ... | Rust | 0 |
from typing import Any, Dict, List, Type, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="TableLineageTableListModelProperties")
@_attrs_define
class TableLineageTableListModelProperties:
"""A dictionary of mapping properties stored as a key/valu... | Python | 1 |
from src.utils import setup_llm
from src.comprehender.prompter import FuncPurposePrompter
from src.generator.llm import Chat
import json
from pathlib import Path
this_dir = Path(__file__).parent
def run():
llm_client = setup_llm("llama3_2_remote")
library_name = "pugixml"
library_purpose = "pugixml is a C... | Python | 1 |
import numpy as np
import torch
import torchvision.transforms as transforms
"""
preprocess reference : https://github.com/google-research/federated/blob/master/utils/datasets/cifar100_dataset.py
"""
# def cifar100_transform(img_mean, img_std, train=True, crop_size=(24, 24)):
def cifar100_transform(img_mean, img_std,... | Python | 1 |
#!/usr/bin/env python
usage='''
input format:
[1] gzipped wsub pairs file
[2] gzipped target word embedding
[3] gzipped subs word embeddings
[4] # of line in test file
[5] lowercase option is on if present
output format:
stdout, <word word embedding > word embedding size of [2]+[3], [4] many number of lines
'''
impo... | Python | 1 |
import requests
import json
url = "https://vyntr.com/api/search?q=harry%20potter"
payload = {"q": "harry potter"}
try:
response = requests.get(url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
print("Request URL:", response.url)
print("Request Method:", response.reque... | Python | 1 |
ution for XORI {
fn execute(&self, p: &mut Processor) -> Result<(), Exception> {
let rs1 = *p.state().xreg(self.rs1(p.state().ir()));
let rs2 = sext(self.imm(p.state().ir()) as RegT, self.imm_len()) & p.state().config().xlen.mask();
let rd = self.rd(p.state().ir());
let value = (rs1 ... | Rust | 0 |
import os
from modules import ui_extra_networks, sd_hijack, shared
from modules.ui_extra_networks import quote_js
class ExtraNetworksPageTextualInversion(ui_extra_networks.ExtraNetworksPage):
def __init__(self):
super().__init__('Textual Inversion')
self.allow_negative_prompt = True
def refr... | Python | 1 |
ty.index, avg_humidity.values, marker='o')
plt.xlabel('Month')
plt.ylabel('Average Relative Humidity (%)')
plt.title('Average Monthly Relative Humidity (%) Trend')
plt.xticks(ticks=range(1, 13), labels=month_order, rotation=45)
plt.savefig(os.path.join(trend_plot_dir, f'Relative_Humidity_Trend_{loca... | Python | 1 |
256 color VGA animations");
println!("");
println!("Give QuickFLI a list of FLICs to play.");
println!("<ESC> to abort playback.");
println!("<space> to go to next FLIC.");
}
fn render_to_texture(
texture: &mut sdl2::render::Texture,
w: usize, h: usize, buf: &[u8], pal: &[u8]) {
te... | Rust | 0 |
ap for k in ["start", "end", "style", "text"]):
return dialogues, tags
# 歌词行解析
for line in events_header.splitlines():
if not line.lower().startswith("dialogue:"):
continue
parts = [p.strip() for p in line[len("Dialogue:") :].split(",", maxsplit=len(field_map) - 1)]
... | Python | 1 |
/// ```
/// let parallelogram = Parallelogram::build_parallelogram(9,5, 4).expect("error");
/// assert_eq!(36.0, parallelogram.get_area());
/// ```
fn get_area(self) -> f64 {
self.a * self.h
}
}
impl Perimeter for Parallelogram {
/// Calculates the perimeter of a parallelogram
//... | Rust | 0 |
### Linear Search Algorithm
# linearSearch(input, searchValue){
# from typing import TypeVarTuple
# for(i = 0 to input.length -1){
# if(input[i] == searchValue)
# return True
# }
# return False
# }
## In Python
def linearSearch(input,searchValue):
for i in range(len(input)):
if input[i] == se... | Python | 1 |
kind,
element,
doc,
};
types.insert(oid, ty);
}
types
}
fn make_header(w: &mut BufWriter<File>) -> std::io::Result<()> {
writeln!(w, "// Autogenerated file - DO NOT EDIT")
}
fn make_impl(w: &mut BufWriter<File>, types: &BTreeMap<u32, Type>) -> std::io::Resu... | Rust | 0 |
max_length=data_args.max_len,
**iterative_params
)
# Start iterative training with proper resume handling
if resume_from_iteration is not None:
# Check if the found iteration is complete
is_iteration_complete = check_iteration_complete(training_args.o... | Python | 1 |
error!("skip amount must be > 0");
std::process::exit(1);
}
let dryrun: bool = matches.is_present("dryrun");
pair(output_path, dryrun, start, stepping);
}
if let Some(matches) = matches.subcommand_matches("scale") {
let _output_path = Path::new(matches.va... | Rust | 0 |
ILE_FOLDER")
addOp.settingsType = 0
# asset blend dirs selection
box = layout.box()
drawMultilineLabel(context, "Assign downloaded blend directories below if you wish to enable full model visualization with layout import", box)
for i, assetDir in enumerate(self.assetBlendDirs):
... | Python | 1 |
unwrap();
let base64 = base64::encode(&writer);
assert_eq!("DS/2U8royDnJDiNY2ps3f6ZoTbpZo8ZtUGYLGEjwLDQ=", base64);
assert_eq!("http://magiclen.org", mc.decrypt_base64_to_string(&base64).unwrap());
# }
```
## No Std
Disable the default features to compile this crate without std.
```toml
[dependencies.magic-crypt]... | Rust | 0 |
EAP_TRACKING_EVENT>())).pHands as *const _ as usize },
36usize,
concat!(
"Offset of field: ",
stringify!(_LEAP_TRACKING_EVENT),
"::",
stringify!(pHands)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_LEAP_TRACKING_EVENT... | Rust | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 breakwall
#
# 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 b... | Python | 1 |
me 3D context
if desc_fence.fence_ctx_idx != completed.fence_ctx_idx {
return false;
}
true
}
<filename>Kernel/Core/arch/armv7/pci.rs
pub fn write(addr: u32, value: u32) {
todo!("PCI write {:#x} v {:#x}", addr, value);
}
pub fn read(addr: u32) -> u32 {
log_trace!("TODO: PCI read {:#x}", addr);
... | Rust | 0 |
unittest.skip("Buggy on MPS for now (mistakenly promotes to float64)"),
"TestCommon",
"test_numpy_ref_mps",
),
),
),
make_signal_windows_opinfo(
name="signal.windows.kaiser",
ref=reference_signal_window(scipy.signal.windows.kaiser)
... | Python | 1 |
})?;
// only need the last event to set to the current value
let fee_per_claim = if let Some(e) = events.iter().last() {
e.value
} else {
created_event.fee_per_claim
};
// `fee_redeemed` events
let events = fee_manager_facet
.fee_... | Rust | 0 |
efix = ""
if args.runtime == "osx-x64":
src_prefix = "/usr/local"
elif args.runtime == "osx-arm64":
src_prefix = "/opt/homebrew"
else:
raise RuntimeError("Invalid runtime id")
# Match against non-system libraries
otool_lib_regex = re.compile(fr"({src_prefix}/.*\.dylib)")
# Match against relative paths (web... | Python | 1 |
w: Window,
time: Time,
x: c_int,
y: c_int,
x_root: c_int,
y_root: c_int,
state: c_uint,
button: c_uint,
same_screen: c_int,
}
pub type XButtonPressedEvent = XButtonEvent;
pub type XButtonReleasedEvent = XButtonEvent;
pub struct XMotionEvent {
_type: c_int,
serial: c_ulong,
se... | Rust | 0 |
verflow_y: Some(true),
overflow_x: Some(true),
..BinStyle::default()
});
let _slider = Arc::downgrade(&slider);
slider.slide_back.on_update(Arc::new(move || {
let _slider = match _slider.upgrade() {
Some(some) => some,
None => return,
};
_slider.force_update(None);
}));
let sliding ... | Rust | 0 |
return AsyncAdapt_aiosqlite_connection(
self,
await_only(connection),
)
class SQLiteExecutionContext_aiosqlite(SQLiteExecutionContext):
def create_server_side_cursor(self):
return self._dbapi_connection.cursor(server_side=True)
class SQLiteDialect_a... | Python | 1 |
# This file is public domain, it can be freely copied without restrictions.
# SPDX-License-Identifier: CC0-1.0
def adder_model(a: int, b: int) -> int:
"""measurement of adder"""
return a + b
| Python | 1 |
?,
txmgr,
)?;
// add segment to tx for deletion
seg_cow.make_del(txmgr)
}
// shrink segment by creating a new segment data, return retired chunks
// indices
pub fn shrink(
seg_cow: &mut Cow<Segment>,
store: &Store,
txmgr: &TxMgrRef,
) -> ... | Rust | 0 |
hdr = f"{'Idx':<3} {'Name':<{name_len}} {'Util':>6} {'Mem (MiB)':>15} {'Temp':>5} {'Pwr (W)':>10}"
LOGGER.info(f"\n--- GPU Status ---\n{hdr}\n{'-' * len(hdr)}")
for gpu in stats:
u = f"{gpu['utilization']:>5}%" if gpu["utilization"] >= 0 else " N/A "
m = f"{gpu['memory_used']... | Python | 1 |
(b"*.o\n", "foo.o"));
assert!(!matches_file(b"foo.?\n", "foo"));
assert!(!matches_file(b"foo.?\n", "foo."));
assert!(matches_file(b"foo.?\n", "foo.o"));
}
#[test]
fn test_gitignore_range() {
assert!(!matches_file(b"foo.[az]\n", "foo"));
assert!(matches_file(b"foo.[az... | Rust | 0 |
'cloud drives'.
/// Note the difference from `user_dirs_request`, which returns a set of all user folders, cloud drives or not.
/// Includes Filen "Default" folder.
pub fn user_base_folders_request(
payload: &UserBaseFoldersRequestPayload,
filen_settings: &FilenSettings,
) -> Result<UserBaseFoldersResponsePayl... | Rust | 0 |
PN proposals.
rpn_min_size : int
Minimum height or width in proposal.
iou_loss : bool
Usage of IoU loss.
Returns
-------
out : tvm.te.Tensor
2-D tensor with shape [batch * rpn_post_nms_top_n, 5]. The last dimension is in format of
[batch_index, w_start, h_start, w_... | Python | 1 |
egated: NonceIsNegated) {
let secp = Secp256k1::new();
let sk = SecretKey::from_slice(&sk_serialized[..]).expect("failed to parse secret key");
let msg32 = Message::from_slice(&msg[..]).expect("failed to parse message");
let expected_sig = SchnorrSignature::from_default(&... | Rust | 0 |
import time, json, os, sys, importlib, signal, copy, pickle
# To use globals var
from lib.utility.constant import DM, EM, R, MR, LR, CR, T
from lib.utility.common_globals import L, RD, RAC
# To use laddar func
import lib.utility.functions as func
import lib.utility.helper as helper
def signal_handler(sig, frame):
... | Python | 1 |
let testdir = testdir()?.with_config(persistent_test_config()?)?;
let testdir = &testdir;
let mut child = testdir.spawn_child(&["-v", "start"])?;
// Run the program and kill it after a few seconds
std::thread::sleep(LAUNCH_DELAY);
child.kill()?;
let output = child.wait_with_output()?;
// ... | Rust | 0 |
, {
predicate!(test_pred(string, bytes, uint64));
rule!(where_rule: test_pred(("bar"), (vec![2u8,2u8]), x) <= test_pred(("foo"), [_], x), {
let (42) = (42)})
})?;
core.run(holmes.quiesce()).unwrap();
Ok(())
})
}
#[test]
pub fn where_const() {
single(&|holmes: &mut Engine... | Rust | 0 |
usize]))
}
} else {
let map_pos = (p.chr[0] as u16 | (p.chr[1] as u16) << 8) as usize;
// unknown characters are intentionally mapped to out of range length
MAPPING.get(map_pos..map_pos + p.len as usize)
}
} else {
None
}
}
/// Convenienc... | Rust | 0 |
import tkinter as tk
def show_toast(parent: tk.Misc, message: str, title: str = "提示", duration_ms: int = 2000, kind: str = "info") -> None:
"""显示简易 toast 提示(顶部居中、带边框、按类型着色)。
:param parent: 关联父级窗口(用于定位)
:param message: 显示文案
:param title: 标题
:param duration_ms: 显示时长(毫秒)
:param kind: 颜色风格:info/success/warni... | Python | 1 |
.rs
/*
Debug helper
This concept is silly but something I've always wanted to do.
Write a debug helper which outputs morse code, so you don't need a monitor :)
*/
#![allow(dead_code)]
use crate::board::gpio;
use crate::sys::{wait_ms};
use crate::sys::lists::{Stack};
// Configure the gpio pin whi... | Rust | 0 |
🐈', "cat"),
(0x1F409, '🐉', "dragon"),
(0x1F40A, '🐊', "crocodile"),
(0x1F40B, '🐋', "whale"),
(0x1F40C, '🐌', "snail"),
(0x1F40D, '🐍', "snake"),
(0x1F40E, '🐎', "horse"),
(0x1F40F, '🐏', "ram"),
(0x1F410, '🐐', "goat"),
(0x1F411, '🐑', "sheep"),
(0x1F412, '🐒', "monkey"),
... | Rust | 0 |
ge Ratio">
<p>Scatter plot with regression line showing relationship between long-range ratio and saliency.</p>
</div>
<div class="plot-container">
<h3>Correlation Heatmap</h3>
<img src="{prefix}_correlation_heatmap.png" alt="Correlation Heatmap">
... | Python | 1 |
eturn value
let mut ret = VWord::new();
for c in s.chars() {
let (x, y) = VChar::from_char(c);
ret.push(x, y);
}
ret
}
pub fn new_raw(data: Vec<VChar>, upcase: Vec<bool>) -> VWord {
VWord {
data: data,
upcase: upcase,
... | Rust | 0 |
import pytest
from unittest.mock import AsyncMock
from app.application.service.genre_service import GenreService
@pytest.mark.asyncio
async def test_list_all_genre():
# Arrange : on simule des genres
fake_genres = ["Drama", "Comedy", "Sci-Fi"]
mock_repo = AsyncMock()
mock_repo.get_all.return_value = f... | Python | 1 |
map(parse_rearanged_term, Expression::Simple),
))(input)
}
pub fn parse_labeled(input: &str) -> IResult<&str, LabeledExpression> {
map(
pair(
parse_expression,
opt(preceded(
pair(tag("#"), multispace0),
map(
many0(termi... | Rust | 0 |
""" Test functions for linalg module
"""
from numpy.testing import *
import numpy as np
from numpy import linalg, arange, float64, array, dot, transpose
rlevel = 1
class TestRegression(TestCase):
def test_eig_build(self, level = rlevel):
"""Ticket #652"""
rva = array([1.03221168e+02 +0.j,
... | Python | 1 |
}
pub(crate) struct VirtioFsEpollHandler<
AS: 'static + GuestAddressSpace,
Q: QueueStateT,
R: GuestMemoryRegion,
> {
pub(crate) config: Arc<Mutex<VirtioDeviceConfig<AS, Q, R>>>,
server: Arc<Server<Arc<Vfs>>>,
cache_handler: Option<CacheHandler>,
thread_pool: Option<ThreadPool>,
id: Stri... | Rust | 0 |
import sys
def remove_avb(contents):
"""
Remove all occurrences of ",avb" and the following segment until the next comma or newline.
:param contents: The content of the fstab file.
:return: The modified content with ",avb" segments removed.
"""
while "avb" in contents:
start = content... | Python | 1 |
n_ids = torch.cat([position_ids, response_position_ids], dim=-1)
response_attention_mask = get_response_mask(response_id=response,
eos_token=eos_token_id,
dtype=attention_mask.dtype)
attention_mask = ... | Python | 1 |
y distribution.
Args:
center_price: Center price for distribution
width_pct: Width as percentage of center price
total_liquidity: Scaled liquidity value
Returns:
List of (lower_price, upper_price, liquidity) tuples
"""
... | Python | 1 |
# 홍준이는 요즘 주식에 빠져있다. 그는 미래를 내다보는 눈이 뛰어나, 날 별로 주가를 예상하고 언제나 그게 맞아떨어진다. 매일 그는 아래 세 가지 중 한 행동을 한다.
# 주식 하나를 산다.
# 원하는 만큼 가지고 있는 주식을 판다.
# 아무것도 안한다.
# 홍준이는 미래를 예상하는 뛰어난 안목을 가졌지만, 어떻게 해야 자신이 최대 이익을 얻을 수 있는지 모른다. 따라서 당신에게 날 별로 주식의 가격을 알려주었을 때, 최대 이익이 얼마나 되는지 계산을 해달라고 부탁했다.
# 예를 들어 날 수가 3일이고 날 별로 주가가 10, 7, 6일 때, 주가가 계속 감소하므... | Python | 1 |
h {
let vao = Vao::new();
let vcount = positions.len() as i32 / 3;
let icount = indices.len() as i32;
// position
let vbo_pos = Mesh::make_attrib_vbo(Some(positions), MeshAttrib::Position);
// indices
let ibo = Vbo::from_data(indices, VboType::Index);
/... | Rust | 0 |
from django.urls import path
from . import views
urlpatterns = [
path('payment-menu/', views.payment_menu, name='payment-menu'),
path('payment/form/<int:order_id>/', views.payment_form, name='payment_form'),
path('payment/process/<int:payment_order_id>/', views.process_payment, name='process_payment'),
... | Python | 1 |
from collections import namedtuple
# data = ["meisam", "ilka", 32]
# data = ("meisam", "ilka", 32)
# Person = namedtuple("Person", "name family age")
# data = Person(name="meisam", family="ilka", age=32)
# data = {}
# data = dict()
# data = {"name":"meisam", "family":"ilka", "age":32}
# data = {"name": "meisam", ... | Python | 1 |
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
self.mileage = 0
self.fuel_level = 100
def drive(self, distance):
if distance < 0:
print("A megtett távolság nem lehet negatív.")
ret... | Python | 1 |
OCK};
// mocks
// TODO: consider use of #[mockall_double]
#[cfg(test)]
use crate::v2::devices::mocks::mock_libc::setrlimit;
#[cfg(not(test))]
use libc::setrlimit;
// TODO: consider use of #[mockall_double]
#[cfg(test)]
use crate::v2::devices::mocks::mock_libbpf_sys::{
bpf_l... | Rust | 0 |
} else {
let nibble = key[index / 2];
if (index & 1) == 0 {
1 + (nibble >> 4) as usize
} else {
1 + (nibble & 0xf) as usize
}
}
}
fn find_closest_leaf_mut(
root: &mut Node<TK, TV>,
key: &[u8],
) ->... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.