text string | label_name string | labels int64 |
|---|---|---|
import numpy as np
# Constants for the reference white point (D65 illuminant)
REF_X = 95.047
REF_Y = 100.000
REF_Z = 108.883
def hex_to_rgb(hex_color):
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4))
def rgb_to_hex(rgb_color):
return '#{:02x}{:02x}{:02x}'.... | Python | 1 |
nwrap/ gt_unwrap))#thresh[batchsize,1,512,640]
a1 = (thresh < 1.25).to(torch.float32).mean()#a1 #[batchsize,1,512,640]#
a2 = (thresh < 1.25 ** 2).to(torch.float32).mean()
a3 = (thresh < 1.25 ** 3).to(torch.float32).mean()
a1_ave_val_unwrap.update(a1.item(),output_val_unw... | Python | 1 |
)])
assert asruleset(["[hello=world]"]) == Ruleset([Rule([Cond("hello", "world")])])
def test_random_split_set_shuffled_split_are_same():
ssp1, ssp2 = set_shuffled_split(range(len(FULL_DF)), 0.66, random_state=42)
rs1, rs2 = random_split(range(len(FULL_DF)), 0.66, res_type=list, random_state=42)
asser... | Python | 1 |
oftmax_smoothing, length_penalty, eos_penalty
)
elapsed = time.time() - start_time
rtf = elapsed / total_dur if total_dur > 0 else 0.0
# 统一把最终 hyps -> 文本(保持老返回结构)
results: List[List[Dict[str, Any]]] = []
for uttid, wav, hyps_per_sample in zip... | Python | 1 |
, value) => filter_scalar(&view, arr, value, op),
}
}
macro_rules! filter_cols {
($lhs:ident, $rhs:ident, $op:ident, $( [$dt:path, $ty:ty] ),*) => {
match ($lhs.data_type(), $rhs.data_type(), $op) {
$( ($dt, $dt, op) => {
cmp_arrays(
as_array!($lhs, Primi... | Rust | 0 |
def min_connecting_path_cost_opt(R, C, M):
# Initialize the first row (inlined cost computation).
prev = [((0 * C + c) % M) + 1 for c in range(C)]
for r in range(1, R):
curr = [0] * C
base = r * C # Compute once per row.
for c in range(C):
# Inline tile cost calcula... | Python | 1 |
import StringIO
import struct
u8 = lambda x: struct.unpack("<B", x)[0]
u16 = lambda x: struct.unpack("<H", x)[0]
v_code = StringIO.StringIO(open("code.txt", "rb").read())
def read_bitstream(code):
v = 0
while True:
c = u8(code.read(1))
if c == 0x9:
v = (v << 1) | 1
elif c ... | Python | 1 |
translate("Form", "4"))
item = self.tableWidget.verticalHeaderItem(4)
# item.setText(_translate("Form", "5"))
# item = self.tableWidget.verticalHeaderItem(5)
# item.setText(_translate("Form", "6"))
for i in range(8):
item = self.tableWidget.horizontalHeaderItem(i)
... | Python | 1 |
_attr(feature = "trace_verbose", tracing::instrument(level = "trace"))]
pub(crate) fn input_ln(
globals_view: TeXGlobalsIoView<'_>,
f: &mut alpha_file,
bypass_eoln: boolean,
) -> boolean {
// var last_nonblank:0..buf_size; {|last| with trailing blanks removed}
/// `last` with trailing blanks removed... | Rust | 0 |
import pyautogui
import keyboard
# Define a termination function
def key_pos():
global keep_running
keep_running = False
keep_running = True
# Add hotkey to terminate the loop (e.g., when 'shift' is pressed)
keyboard.add_hotkey('shift', key_pos)
while True:
if not keep_running:
print(pyautogui.p... | Python | 1 |
}
let req = serde_json::from_slice::<MyReq>(&request).c(d!())?;
let addr_set = {
let lk = ENV_MAP.read();
let res = req
.msg
.env_set
.iter()
.filter_map(|env_id| lk.get(env_id))
.flatten()
.copied()
.collect::... | Rust | 0 |
in TOOLS:
tool = TOOLS[tool_name]
if asyncio.iscoroutinefunction(tool):
resp = await tool({"id": id, "payload": payload})
else:
resp = tool({"id": id, "payload": payload})
else:
resp = {"type": "response... | Python | 1 |
import base64
import json
def encode_image_to_json(image_path: str, json_output_path: str):
"""
Encodes an image file to Base64 and saves it as a JSON file suitable for Swagger.
:param image_path: Path to the image file to encode.
:param json_output_path: Path to the JSON file to save the encoded imag... | Python | 1 |
lientError::InvalidRequest { status_code, message } => {
let detail_clause = match message {
Some(m) => format!(": error was {}", m),
None => "".to_owned(),
};
match status_code {
&reqwest::StatusCode::BAD_REQUEST =>
... | Rust | 0 |
]))
.expect("send response");
}
}
}
})
.detach();
}
}
}
})
.detach(... | Rust | 0 |
, vec![vec![0; 2]; 2]);
}
#[test]
fn test_matrix_resize() {
let mut m = SquareMatrix::new(2);
m.resize(3);
assert_eq!(m.dim, 3);
assert_eq!(m.values, vec![vec![0; 3]; 3]);
}
#[test]
fn test_matrix_resize_with_values() {
let mut m = SquareMatrix::new(2);... | Rust | 0 |
ttan_distance = lambda x, y: np.abs(x - y)
for i in range(preds.shape[0]):
x = preds[i].reshape(-1,1)
y = trues[i].reshape(-1,1)
if i % 100 == 0:
print("calculating dtw iter:", i)
d, _, _, _ = accelerated_dtw(x, y, dist=manh... | Python | 1 |
data.custom_id.split(':').collect();
let comp_type: &str = match ids_split.get(0) {
Some(str_type) => *str_type,
None => "none",
};
// TODO possibly avoid another split here by using this split again, but for now I dont want to edit the signiture
match comp_type {
"HelpButton" =>... | Rust | 0 |
from enum import Enum
from source.constants import PROJECT_ROOT
# RTDETR configuration
CFG_TEMPLATES = PROJECT_ROOT / 'source' / 'cfg_templates'
RTDETR_PATH = PROJECT_ROOT / 'third_party' / 'rtdetr_pytorch'
RTDETR_SRC_PATH = RTDETR_PATH / 'src'
# Metrics evaluation
DEFAULT_IMG_SIZE = (640, 640)
VISUALIZATIONS_TO_TRA... | Python | 1 |
utils::assert::*;
use crate::{actionset, principal};
#[test]
fn test_statement_is_allowed() -> anyhow::Result<()> {
let statement1 = Statement {
sid: "".to_string(),
effect: ALLOW,
principal: principal!("*".to_string()),
actions: actionset!(GET_BUCKET... | Rust | 0 |
grr.bind_image_views(0, &[env_cubemap_view]);
grr.bind_samplers(0, &[env_cubemap_sampler]);
grr.bind_draw_framebuffer(env_prefilter_fbo);
grr.set_color_attachments(env_prefilter_fbo, &[0]);
let mut level_dim = env_prefiltered_size;
grr.bind_uniform_constants(
env_p... | Rust | 0 |
if (d3 < d2) && (d3 < d1) {
edge_v1 = 3;
edge_v2 = 1;
*d = d3;
}
if edge_v1 == 1 && edge_v2 == 2 {
*n = 1;
return self.perps[j as usize][0];
}
if edge_v1 == 2 && edge_v2 == 3 {
*n = 2;
return self.... | Rust | 0 |
0.145 0.909 -0.8291 0.275 0.471 0.150 0.383 -0.031 -0.220 -0.0060 0.06 6.4 0.3 3
0.60 2.85 -0.087 0.909 -0.7896 0.275 0.416 0.150 0.345 -0.022 -0.220 -0.0068 0.06 6.4 0.3 3
0.75 2.50 -0.344 0.909 -0.7488 0.275 0.348 0.150 0.299 -0.010 -0.220 -0.0083 0.06 6.4 0.3 3
0.85 2.5... | Python | 1 |
_manifest: PackageManifest = product
.base
.iter()
.find_map(|p| {
if let Ok(m) = pkg_manifest_from_path(p) {
if m.name().as_ref() == "pkgfs" {
return Some(m);
}
}
return N... | Rust | 0 |
l property target value.
Condition: "#prop == bootfs"
-
Id: value_cachefile
Key: value
Label: Value
DisplayModeLabel: value
LabelCss: action16
Mandatory: Yes
Type: string
Help: The zpool property target value.
Condition: "#prop == cachefile"
-
Id: value_dedupditto
Key... | Python | 1 |
let tt = match tt {
tt::TokenTree::Leaf(leaf) => leaf,
tt::TokenTree::Subtree(_) => return Err(ParseError::InvalidRepeat),
};
let has_sep = match &separator {
Separator::Puncts(puncts) => !puncts.is_empty(),
_ => true,
};
match tt {... | Rust | 0 |
::ForwardsUOffset<UncleBlock<'b >>>>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Block::VT_UNCLES, uncles);
}
#[inline]
pub fn add_transactions(&mut self, transactions: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Transaction<'b >>>>) {
self.fbb_.push_slot_al... | Rust | 0 |
row['exchange'] = 'NYSE'
row['symbol'] = stocks[j]
row['adj_open'] = 10
row['adj_close'] = 20
row['adj_high'] = 22
row['adj_low'] = 7
row['close'] = 20
row['volume'] = 200
row['timestamp'] = ... | Python | 1 |
or `NEG_INFINITY`
/// - `NAN` if the number is `NAN`
///
/// # Examples
///
/// ```
/// let f = 3.5_f32;
///
/// assert_eq!(f.signum(), 1.0);
/// assert_eq!(f32::NEG_INFINITY.signum(), -1.0);
///
/// assert!(f32::NAN.signum().is_nan());
/// ```
#[must_use = "method r... | Rust | 0 |
const R4: u8>(
vector: &mut [N; 16],
a: usize,
b: usize,
c: usize,
d: usize,
x: N,
y: N,
) {
vector[a] = vector[a].wrapping_add(&vector[b]).wrapping_add(&x);
vector[d] = (vector[d] ^ vector[a]).rotate_right(R1.try_into().unwrap());
vector[c] = vector[c].wrapping_add(&vector[d]);... | Rust | 0 |
import operations
def perform_operation_with_two_nums(num1, num2, operation):
"""
Performs mathematical operations with two numbes
:param num1: float
:param num2: float
:param operation: string
"""
if operation == "addition":
return operations.addition(num1, num2)
elif operati... | Python | 1 |
response = self.llm.invoke(prompt)
decision = response.content.strip().lower()
# 유효하지 않은 응답 처리
if decision not in ["fetch_news", "fetch_report", "fetch_price", "end"]:
logger.warning(f"Invalid decision: {decision}, defaulting to 'fetch_news'")
... | Python | 1 |
as u64
}
fn get_chunk_info(&self, idx: usize) -> Result<Arc<dyn BlobChunkInfo>> {
let state = self.state.load();
let unit_size = size_of::<RafsV5ChunkInfo>();
let offset = state.meta.chunk_table_offset as usize + idx * unit_size;
if offset + unit_size
> (state.meta... | Rust | 0 |
od, adjust=False).mean()
# Replace talib.MACD with manual calculation
def calculate_macd(series, fastperiod=12, slowperiod=26, signalperiod=9):
ema_fast = calculate_ema(series, fastperiod)
ema_slow = calculate_ema(series, slowperiod)
macd = ema_fast - ema_slow
signal = macd.ewm(span=signalperiod, adjus... | Python | 1 |
def skjkasdkd(lst):
"""You are given a list of integers.
You need to find the largest prime value and return the sum of its digits.
Examples:
For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10
For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should ... | Python | 1 |
self.
pub fn bit_range(&self) -> Range<usize> {
self.class.bit_range(self)
}
/// Returns the attribute value.
pub fn try_get(&self, layer: &Layer) -> Result<Variant> {
self.class.try_get(self, layer)
}
}
impl Into<Fixed<Attr>> for Attr {
fn into(self) -> Fixed<Attr> {
... | Rust | 0 |
{
let mut max = 0;
let mut len = 0;
for num in nums {
if num == 1 {
len += 1;
max = len.max(max);
} else {
len = 0;
}
}
max
}
///力扣(485. 最大连续1的个数)
pub fn find_max_consecutive_ones_v2(nums: Vec<i32>) -> i32 {
let ones_group = nums.as_s... | Rust | 0 |
ytes.len());
if read_ptr == data_bytes.len() {
break;
}
match reader.read(&mut data_bytes[read_ptr ..]) {
Err(e) => panic!("failed to deserialize: read error: {:?}", e),
Ok(count) => {
if count == 0 {
break;
}
read_p... | Rust | 0 |
import pyMeow as pm
import pydirectinput as pdir
import time
import psutil
def get_process_pid(process_name): #function to get pid using process name
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == process_name:
return proc.info['pid']
return None
class InitP... | Python | 1 |
)
})
}
async fn apply_patch(cfg: &GitHubConfig, patch: GitHubPatch) -> Result<(), String> {
let https = HttpsConnector::new();
let client = Client::builder().build::<_, hyper::Body>(https);
let url = github_issues_url(&cfg.owner, &cfg.repo);
// Create
println!("creating {} issues", p... | Rust | 0 |
import math
import numpy as np
from scipy import interpolate
from collections import OrderedDict
def wrap_angle(angle):
return (angle + ( 2.0 * np.pi * np.floor( ( np.pi - angle ) / ( 2.0 * np.pi ) ) ) )
def distance_to_goal( goal,current): #distance between the current pose and the goal pose
return m... | Python | 1 |
ripwireHook {
props: {},
get_id: 604,
from_id(_id): 604 => {},
block: true,
},
Terracotta {
props: {},
get_id: 389,
from_id(_id): 389 => {},
block: true,
},
ColoredTerracotta {
props: {
color: BlockColorVariant
}... | Rust | 0 |
relude::*;
#[test]
fn mv_simple() -> Result<(), Box<dyn Error>> {
let temp = assert_fs::TempDir::new()?;
temp.child("test-001").touch()?;
let mut cmd = Command::cargo_bin("mrf")?;
cmd.current_dir(temp.path())
.arg("mv")
.arg("-y")
.arg("test-001")
.arg("{}{=_}{}");
... | Rust | 0 |
= result {
eprintln!("{}", e);
ok = false;
break;
}
}
let elapsed = start.elapsed();
println!("{:.1} fps", 360.0 / elapsed.as_secs_f32());
}
}
#[tokio::test]
async fn harness() {
assert_eq!(true, true);
}
<reponame>zaharidichev... | Rust | 0 |
ExecExpressionWithValue(
0x0008,
0x08,
(
(Expr.PushLong, 0x1),
Expr.Nop,
Expr.Return,
),
)
Jump('loc_61D1')
def _loc_61C7(): pass
label('loc_61C7')
ExecExpressionWithValue(
0x0008,
0x08,
(
... | Python | 1 |
from PIL import Image
# вырезаем кошку с изображения
def crop_image(input_image_path, savepicture, crop_area):
with Image.open(input_image_path) as img:
cropped_img = img.crop(crop_area)
cropped_img.save(savepicture)
picture = "kosh.jpg"
savepicture = "cropped_kosh.jpg"
crop_area = (2000, 1600, ... | Python | 1 |
def find_blank(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == '_':
return (i, j)
def is_valid_move(board, i, j):
return 0 <= i < len(board) and 0 <= j < len(board[0])
def swap(board, i1, j1, i2, j2):
board[i1][j1], board[i2][j2] = ... | Python | 1 |
ize to the current position.
The current stream position isn't changed.
Return the new file size.
"""
return self._file.truncate(size)
def writable(self) -> bool:
"""Return False."""
return False
def __enter__(self) -> LazyZipOverHTTP:
self._file.__ente... | Python | 1 |
# Knights of Cygnus - Tutorial Skipper
def skip_tutorial():
MAPLE_ADMINISTRATOR = 2007
quests_to_complete = [
20820, # The City of Ereve
20821, # Knight's Orientation
20822, # The Path of Bravery
20823, # Question and Answer
20824, # Knight's Cavalier
20825, # Well-Behaved Student
20826, # Lesson 1 - E... | Python | 1 |
V#010F是啊,明天还有比赛……\n',
' ',
TxtCtl.Enter,
TxtCtl.Clear,
'#0020101646V整理完行李就休息吧。',
TxtCtl.Enter,
),
)
CloseMessageWindow()
OP_20(0x000005DC)
FadeOut(1500, 0, -1)
OP_0D()
PlaySE(13, 0x00, 0x64)
Sleep(3000)
MapSetFlags(0x0... | Python | 1 |
div" class="android.widget.ImageView" alt="除" clickable="true"> </img>
<img id="com.miui.calculator:id/op_mul" class="android.widget.ImageView" alt="乘" clickable="true"> </img>
<img id="com.miui.calculator:id/op_sub" class="android.widget.ImageView" alt="减" clickable="true"> </img>
<img id="com.miui.calculator:id/op... | Python | 1 |
.
Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the doc string with tests to be debugged.
c s g | ]}|j kr|qS r, r* )r rB r* r, r- r ,
r ztestsource.<locals... | Python | 1 |
| XBAR1_INOUT09 | FLEXIO1_FLEXIO07 | GPIO4_IO07 | --- | --- | --- | --- |
//!
//! References:
//! - [Teensy Schematics](https://www.pjrc.com/teensy/schematic.html)
//! - i.MX RT 1060 Processor Reference Manual, Rev. 2, 12/2019
use ... | Rust | 0 |
ET_R::new(((self.bits >> 16) & 0x7f) as u8)
}
#[doc = "Bits 24:30 - Scan Mode Gain Calibration Value"]
#[inline(always)]
pub fn scangain(&self) -> SCANGAIN_R {
SCANGAIN_R::new(((self.bits >> 24) & 0x7f) as u8)
}
}
impl W {
#[doc = "Bits 0:6 - Single Mode Offset Calibration Value"]
#[... | Rust | 0 |
"""This sample shows how some time can be saved by accessing the image buffer
without copying its contents. Keep in mind that while a zero-copy array has a
reference to the image buffer, this buffer cannot be released and cannot be
reused for grabbing.
"""
import numpy
import time
from pypylon import pylon
cam = pylon... | Python | 1 |
() as usize > GATEWAY_OFFSET {
let gateway_nla_buf = NlaBuffer::new_checked(buf.gateway_nla())
.context("cannot parse RTA_GATEWAY attribute in next-hop")?;
if gateway_nla_buf.kind() != RTA_GATEWAY {
return Err(format!("invalid RTA_GATEWAY attribute in next-hop: ex... | Rust | 0 |
"""particle swarm optimization functions"""
import numpy as np
def PSO_MOVEMENT(OF_FUNCTION, V_T0I, X_T0I, C_1, C_2, P_BEST, G_BEST, D, X_L, X_U, V_MIN, V_MAX, INERTIA, NULL_DIC):
"""
PSO velocity update.
"""
# Start internal variables
V_T1I = []
X_T1I = []
# Update velocity
for I_CO... | Python | 1 |
# LeetCode 409. Longest Palindrome
class Solution:
def longestPalindrome(self, s: str) -> int:
pal = {}
for letter in s:
pal[letter] = pal.get(letter, 0) + 1
ans = 0
has_odd = False
for num in pal.values():
if num % 2 == 1:
has_odd = ... | Python | 1 |
: clear command queue
println!("error: {}", error);
let mut text = String::new();
writeln!(text, "\nerror: {}", error).unwrap();
self.console_lines.push_back(text);
}
}
}
Some(Event::ConsoleUpd... | Rust | 0 |
all columns in the CSV"""
if not self.rows and not self.header:
return []
num_columns = len(self.header) if self.header else len(self.rows[0])
all_rows = [self.header] + self.rows if self.header else self.rows
return [Column(i, all_rows) for i in range(num_columns)]
def... | Python | 1 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut b = f.debug_struct("ReadHandle");
// Just print the fd number; don't try to print the path or any
// information about it, because this information is otherwise
// unavailable to safe Rust code.
b.field("raw_fd",... | Rust | 0 |
uniforms::Uniforms>() as wgpu::BufferAddress,
)
}
}
// Check that we report an error if an upcast box is moved twice.
fn consume(_: Box<[i32]>) {
}
fn foo(b: Box<[i32;5]>) {
consume(b);
consume(b); //~ ERROR use of moved value
}
fn main() {
}
#![allow(deprecated)]
#[cfg(feature = "serde")]
use s... | Rust | 0 |
n = 10
while num <= n:
cont = cont
print(f'Olha o {num}') | Python | 1 |
bounds.top_left,
bottom_right.component_max(bounds.top_left),
);
}
ProcessedEvent::NextHorizontal => {
textbox_style.alignment = match textbox_style.alignment {
HorizontalAlignment::Left => Horizontal... | Rust | 0 |
ool = False):
r"""Make a scatter plot of predicted versus actual targets. Not for k-splits.
Args:
y_predict (np.ndarray): Numpy array of shape `(N_samples, n_targets)` or `(N_samples, )`.
y_true (np.ndarray): Numpy array of shape `(N_samples, n_targets)` or `(N_samples, )`.
data_unit (l... | Python | 1 |
GUE 😛
#[doc(inline)]
pub use crate::grouped::smileys_and_emotion::face_tongue::FACE_WITH_TONGUE;
// MONEY_MOUTH_FACE 🤑
#[doc(inline)]
pub use crate::grouped::smileys_and_emotion::face_tongue::MONEY_MOUTH_FACE;
// SQUINTING_FACE_WITH_TONGUE 😝
#[doc(inline)]
pub use crate::grouped::smileys_and_em... | Rust | 0 |
= -torch.mean(minval)
minval = torch.min(-scores_fake - 1, get_zero_tensor(scores_fake))
loss_fake = -torch.mean(minval)
return loss_real + loss_fake
def gradient_penalty(x_real, x_fake, f, gamma=1.0):
N = x_real.size(0)
device, dtype = x_real.device, x_real.dtype
eps = torch.randn(N, 1, 1, 1,... | Python | 1 |
arsedText):
TREE_SITTER_LANG_NAME = "tcl"
class Test(UnparsedText):
TREE_SITTER_LANG_NAME = "test"
class Thrift(UnparsedText):
TREE_SITTER_LANG_NAME = "thrift"
class Tsv(UnparsedText):
TREE_SITTER_LANG_NAME = "tsv"
class Twig(UnparsedText):
TREE_SITTER_LANG_NAME = "twig"
class Typst(Unpars... | Python | 1 |
// println!("ret \t {:?}", ret);
}
1 => {
// println!("buf[2] \t {:0>8b}", buf[2]);
// println!("buf[3] \t {:0>8b}", buf[3]);
ret.push((buf[2] << 3) | (buf[3] >> 2));
// println!("ret \t {:?}", ret);
}
... | Rust | 0 |
req_fsub':
# if await authoUser(query, query.from_user.id, owner_only=True) :
await query.answer("♻️ Qᴜᴇʀʏ Pʀᴏᴄᴇssɪɴɢ....")
try:
on = off = ""
if await db.get_request_forcesub():
on = "🟢"
texting = on_txt
else:
... | Python | 1 |
-> [B, Q, T*H*W] -> [B, h, Q, T*H*W] -> [B*h, Q, T*HW]
attn_mask = F.interpolate(outputs_mask.flatten(0, 1), size=attn_mask_target_size, mode="bilinear", align_corners=False).view(
b, q, t, attn_mask_target_size[0], attn_mask_target_size[1])
# must use bool type
# If a BoolTensor is... | Python | 1 |
: Q) {
for (src_glob, dest_part) in detail {
let dest_dir = dest_dir.as_ref().join(dest_part);
if dest_dir.exists() {
fs::remove_dir_all(&dest_dir).unwrap();
}
for file_path in glob(src_dir.as_ref().join(src_glob).to_str().unwrap()).unwrap() {
let file_path ... | Rust | 0 |
from twoai import Agent, TWOAI, AgentDetails
import unittest
class TestTwoAI(unittest.TestCase):
def test_create_agent(self):
agent = Agent(name="Zerkus", objective="Debate the chicken or the egg with the other AI")
self.assertEqual(agent['name'], "Zerkus")
self.assertEqual(agent['objecti... | Python | 1 |
let t_a3_3 = vmulq_f32(self.twiddle2re, x3p4);
let t_b1_1 = vmulq_f32(self.twiddle1im, x1m6);
let t_b1_2 = vmulq_f32(self.twiddle2im, x2m5);
let t_b1_3 = vmulq_f32(self.twiddle3im, x3m4);
let t_b2_1 = vmulq_f32(self.twiddle2im, x1m6);
let t_b2_2 = vmulq_f32(self.twiddle3im, x2m... | Rust | 0 |
>,
#[doc = "0x28 - DPLL Prescaler"]
pub dpllpresc: crate::Reg<dpllpresc::DPLLPRESC_SPEC>,
_reserved15: [u8; 0x03],
#[doc = "0x2c - DPLL Synchronization Busy"]
pub dpllsyncbusy: crate::Reg<dpllsyncbusy::DPLLSYNCBUSY_SPEC>,
_reserved16: [u8; 0x03],
#[doc = "0x30 - DPLL Status"]
pub... | Rust | 0 |
write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ch14_ctrl](ch14_ctrl) module"]
pub type CH14_CTRL = crate::Reg<u32, _CH14_CTRL>;
#[allow(missing_docs)]... | Rust | 0 |
()).freeze();
let gpioa = dp.GPIOA.split();
let (tx, _rx) = Serial::new(
dp.USART2,
(
gpioa.pa2.into_alternate(),
gpioa.pa3.into_alternate(),
),
clocks,
Config {
baud_rate: 9600.Bps(),
... | Rust | 0 |
import pytest
import networkx as nx
import networkx.algorithms.regular as reg
import networkx.generators as gen
class TestKFactor:
def test_k_factor_trivial(self):
g = gen.cycle_graph(4)
f = reg.k_factor(g, 2)
assert g.edges == f.edges
def test_k_factor1(self):
g = gen.grid_2... | Python | 1 |
VERSION", "GL_SC_VERSION"].iter() {
let mut out = Vec::new();
for feature in self.features.iter().filter(|f| f.name.starts_with(api_prefix)) {
if *api_prefix == "GL_VERSION" && feature.name.starts_with("GL_VERSION_ES_CM") {
continue;
}
out.extend(feature.commands_added.iter... | Rust | 0 |
ss.bit_width() - 4, 0));
let ram64_7 = RAM64::new("RAM64_7", m);
ram64_7.in_.drive(in_);
ram64_7.load.drive(dmux8way.h);
ram64_7.address.drive(address.bits(address.bit_width() - 4, 0));
let mux8way16 = Mux8Way16::new("mux8way16", m);
mux8way16.sel.drive(address.bits(add... | Rust | 0 |
um TopLevelErrorKind {
InvalidRequest,
MaxElementsExceeded,
OverQueryLimit,
RequestDenied,
UnknownError,
}
impl TopLevelErrorKind {
fn as_str(&self) -> &'static str {
match *self {
TopLevelErrorKind::InvalidRequest => "Invalid request",
TopLevelErrorKind::MaxElem... | Rust | 0 |
path.push(&dependency.name);
package_manifest_path.push("Cargo.toml");
package_manifest_path
};
if manifest_path.exists() {
visited.insert(dependency.name);
get_targets_recursive(Some(&manifest_path), &mut targets, visited)?;
... | Rust | 0 |
always)]
pub fn div6(self) -> &'a mut W {
self.variant(PLLDIVR_A::DIV6)
}
#[doc = "PLLSAIDIVQ = /7"]
#[inline(always)]
pub fn div7(self) -> &'a mut W {
self.variant(PLLDIVR_A::DIV7)
}
#[doc = "PLLSAIDIVQ = /8"]
#[inline(always)]
pub fn div8(self) -> &'a mut W {
... | Rust | 0 |
from django.urls import path
from . import views
urlpatterns=[
path('',views.home,name='home'),
path('add', views.add, name='add'),
path('dashboard/', views.dashboard, name='dashboard'),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/',views.customer, name='c... | Python | 1 |
&self.relations_storage[*relation_idx]))
}
/// Iterator over (model_a_id, relation)
#[allow(dead_code)] // not used _yet_
pub(super) fn relations_to_model(
&self,
model_b_id: ast::ModelId,
) -> impl Iterator<Item = (ast::ModelId, &Relation<'ast>)> {
self.back
.r... | Rust | 0 |
!(128_u8.to_float_sample(), 0.0);
/// }
/// ```
fn to_float_sample(self) -> Self::Float {
self.to_sample()
}
/// Adds (or "offsets") the amplitude of the `Sample` by the given signed amplitude.
///
/// `Self` will be converted to `Self::Signed`, the addition will occur and then the ... | Rust | 0 |
does not contain test process PID.");
assert_eq!(values.get("SYSLOG_IDENTIFIER").unwrap(), "journal_logger_test", "Wrong SYSLOG_IDENTIFIER field.");
}use clap::{App, Arg, crate_version, crate_description, crate_authors};
pub fn app() -> App<'static, 'static> {
App::new("deltae")
.version(crate_version!()... | Rust | 0 |
ove |input: &[u8]| {
if encoded_value == 0b0000_1111 {
map_res(
alt((
map(uint8, |value| value as u64),
map(uint16, |value| value as u64),
map(uint32, |value| value as u64),
map(sint64, |value| value as u... | Rust | 0 |
import sys
import dlib
from skimage import io
# You can download the required pre-trained face detection model here:
# http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
predictor_model = "./models/dlib/shape_predictor_68_face_landmarks.dat"
# Take the image file name from the command line
file_name = sy... | Python | 1 |
_signal_fence();
_safepoint_load;
}
#[allow(path_statements)]
pub unsafe fn jl_sigint_safepoint(ptls: jl_ptls_t) {
jl_signal_fence();
let _safepoint_load = *(*ptls).safepoint.offset(-1);
jl_signal_fence();
_safepoint_load;
}
/* #ifndef JULIA_ENABLE_THREADING
pub unsafe fn jl_get_ptls_states() -> ... | Rust | 0 |
import pytest
from scrapy_webarchive.cdxj.models import CdxjRecord
def test_cdxj_record_valid():
# Sample valid CDXJ line
valid_cdxj_line = "com,example)/index 20241003000000 {\"url\": \"http://example.com/index\", \"status\": \"200\"}"
# Create a CdxjRecord object
record = CdxjRecord.from_cdxli... | Python | 1 |
assert_eq!(input_run, expected_run);
}
)*
}
}
context_tests! {
test_bool_and: ("( TRUE FALSE BOOLAND )", "( FALSE )"),
test_bool_define: ("( KMu7 TRUE BOOLDEFINE KMu7 )", "( TRUE )"),
test_bool_dup: ("( TRUE BOOLDUP )", "( TRUE TRUE )"),
... | Rust | 0 |
applicationid: *const u16, extendederror: *mut *mut MI_Instance, application: *mut MI_Application) -> MI_Result;
}
#[doc = "*Required features: 'Win32_System_Wmi'*"]
pub type CIMTYPE_ENUMERATION = i32;
#[doc = "*Required features: 'Win32_System_Wmi'*"]
pub const CIM_ILLEGAL: CIMTYPE_ENUMERATION = 4095i32;
#[doc = "*Re... | Rust | 0 |
erU8(v) => write!(f, "one-byte marker {}", v),
}
}
}
#[derive(Debug, Clone)]
pub struct InvalidValue {
pub record_offset: u64,
pub record_tag: Tag,
pub field_offset: u32,
pub field_tag: Tag,
pub value_offset: u32,
pub value: Invalid,
}
impl Display for InvalidValue {
fn fmt(&se... | Rust | 0 |
.001),
moe_router_load_balancing_type="seq_aux_loss",
moe_shared_expert_overlap=True,
# moe_permute_fusion=True, # need TE 2.1+
moe_grouped_gemm=True,
moe_router_score_function="sigmoid",
moe_router_pre_softmax=True,
moe_router_topk_scaling_factor=hf_config.routed... | Python | 1 |
isinstance(self.state, Active)
assert self.callback.mock_calls == [call.on_active()]
case Active():
assert self.state is prev
assert self.callback.mock_calls == [call.flush_in_active()]
case _:
assert self.state is prev
... | Python | 1 |
# Program to demonstrate Linear Regression
# Importing necessary libraries
import numpy as np
import matplotlib.pyplot as plt
# Generating random data
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
# Plotting the data
plt.scatter(X, y)
plt.xlabel('X')
plt.ylabel('y')
plt.tit... | Python | 1 |
t Some(var) = which_var {
syntax.push(Term::Var(var));
goal = bitvec_xor(&goal, &valuation[&var]);
} else {
for (idx, dep) in goal.iter().enumerate() {
if *dep {
syntax.push(Term::Cst(idx));
}
}
break... | Rust | 0 |
print("\n" + "="*70)
print("📚 Documentation: README.md")
print("❓ Issues: https://github.com/sanjuz-cas/SURF/issues")
print("="*70 + "\n")
def main():
"""Main setup function."""
print_banner()
# Check Python version
if not check_python_version():
sys.exit(1)
# Creat... | Python | 1 |
erde
use std::{convert::TryFrom, result::Result};
use serde::{ser, Serialize, Serializer};
use crate::oid::ObjectId;
pub use bson_datetime_as_iso_string::{
deserialize as deserialize_bson_datetime_from_iso_string,
serialize as serialize_bson_datetime_as_iso_string,
};
pub use chrono_datetime_as_bson_datetim... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.