text string | label_name string | labels int64 |
|---|---|---|
let usart_div = clk_freq / (16f32 * 9600f32);
let mut int_div = usart_div as i32; //note that trunc(), fract(), rount() are not implemented in core...
let mut fra_div = round(16.0 * (usart_div - int_div as f32)) as i32;
if fra_div == 16 {
int_div += 1;
fra_div = 0;
... | Rust | 0 |
_size(ARRAY_SIZE)
.set_wait_event(&y_write_event)
.enqueue_nd_range(&queue)?;
let mut events: Vec<cl_event> = Vec::default();
events.push(kernel_event.get());
// Create a results array to hold the results from the OpenCL device
// and enqueue a read command to read the device buffer in... | Rust | 0 |
#!/usr/bin/env python
#
# CookieClassifier.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WA... | Python | 1 |
uf;
use std::process::Command;
use std::str;
const INPUT_DATE_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";
const LOG_DATE_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
const START_END_FORMAT: &str = "%b-%d %H:%M";
const FORMAT_CMD: [&str; 7] = [
"jobid",
"jobname%30",
"alloccpus",
"elapsed",
"start",
"end",
"... | Rust | 0 |
crc.get_crc()
});
to_js_buffer_2(&mut cx, crc)
}
$cx.export_function(stringify!($f), $f)?;
};
($cx:expr; $($f:ident),+ $(,)* ) => {
$(
crc_functions_2!(@inner $cx, $f);
)+
};
}
macro_rules! crc_functions_3 {
(@inner $cx:expr... | Rust | 0 |
.height,
x_step: self.x_step,
y_step: self.y_step,
re: self.start.re,
im: self.start.im,
};
free_chunk.set_processing(node_id);
debug!("preparing chunk {} for node {}", i, node_id);
Ok(NCJobStatus::Unfinishe... | Rust | 0 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from time import sleep
import undetected_chromedriver as uc
from selenium.webdriver.support.ui import WebDriverWait
from fake_useragent import UserAgent
from selenium.webdriver.support import expec... | Python | 1 |
#Viết chương trình kiểm tra xem một chuỗi có phải là palindrome hay không
def kiemTraPalindrome(list):
if list == list[::-1]:
return True
return False
list = input("Nhập chuỗi cần kiểm tra: ")
if kiemTraPalindrome(list):
print(f"{list} là chuỗi palindrome")
else:
print(f"{list} không là chuỗi pa... | Python | 1 |
.eq(&pub_key)
.and(role::end_commit_num.eq(MAX_COMMIT_NUM)),
);
if let Some(service_id) = service_id {
query = query.filter(role::service_id.eq(service_id));
} else {
query ... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
class TrainBreakException(Exception):
pass
class TrainContinueException(Exception):
pass
class TrainReturnException(Exception):
pass
| Python | 1 |
parser.add_argument(dest="fru", help="FRU Name")
parser.add_argument(
dest="sensor_num", nargs="?", type=auto_int, help="Sensor Num", default=None
)
parser.add_argument(
"--from",
dest="from_time",
type=auto_date,
help="From date, YYYY-MM-YY:HH:MM:SS Ex: 2023-11-10:13... | Python | 1 |
ef_color.g as f32 / 255.0, ref_color.b as f32 / 255.0).into();
// // Convert the current pixel's colour to the l*a*b colour space
// let r_val: f32 = px.data[0] as f32 / 255.0;
// let g_val: f32 = px.data[1] as f32 / 255.0;
// let b_val: f32 = px.data[2] as f32 / 2... | Rust | 0 |
from btpg.envs.robothow.exec_lib._base.rh_action import RHAction
# from btpg.envs.robothow.exec_lib._base.VHTAction_small import VHTAction_small
class PlugOut(RHAction):
can_be_expanded = True
num_args = 1
valid_args = RHAction.HAS_PLUG
# valid_args_small = VHTAction_small.HAS_PLUG
def __init__(s... | Python | 1 |
Self {
volumes: value
.volumes
.into_iter()
.map(|volume_spec| volume_spec.into())
.collect(),
pools: value
.pools
.into_iter()
.map(|pool_spec| pool_spec.into())
... | Rust | 0 |
pub const WSTIBETANMASTIFF_NUMERICS_ID: &'static [u8; 15usize] = b"tibetanmastiff\0";
pub const WSTIBETANMASTIFF_CSHORT: i32 = 226;
pub const WSTIBETANMASTIFF_CINT: i32 = 228;
pub const WSTIBETANMASTIFF_CLONG: i32 = 230;
pub const WSTIBETANMASTIFF_CINT64: i32 = 230;
pub const WSTIBETANMASTIFF_CSIZE_T: i32 = 230;
pub co... | Rust | 0 |
00,
'ref_horizon': 5}
# simulation settings
self.sim.dt = 1/120
self.sim.disable_contact_processing = True
self.sim.physics_material = self.scene.terrain.physics_material
# update sensor update periods
# we tick all the sensors based ... | Python | 1 |
##
# 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, software
# distributed under the... | Python | 1 |
of(id: u32) -> Result<TxReadProof> {
let mut retval: i32 = 0;
let mut proof_len: usize = 0;
let sgx_ret =
unsafe { ocall_get_read_proof_len(&mut retval as *mut _, id, &mut proof_len as *mut _) };
ensure!(
sgx_ret == sgx_status_t::SGX_SUCCESS,
"Failed to get read proof len. Reaso... | Rust | 0 |
16>().is_none());
assert!(1i32.as_any().downcast_ref::<u32>().is_none());
assert!(1i64.as_any().downcast_ref::<u64>().is_none());
assert!(1i128.as_any().downcast_ref::<u128>().is_none());
assert!(s!("str").as_any().downcast_ref::<&str>().is_none());
}
}
<filename>linux/fork/src/zombi... | Rust | 0 |
b.reg(r#"en adelante"#)?,
|datetime, _| Ok(datetime.value().clone().mark_after_start())
);
b.rule_2("from <datetime>",
b.reg(r#"(?:a partir|despu[eéè]s) del?|desde"#)?,
datetime_check!(excluding_form!(Form::TimeOfDay(_))),
|_, datetime| Ok(datetime.value().clo... | Rust | 0 |
from typing import List
from unittest import TestCase, main
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
return self.solveWithHashableKey(strs)
"""
Runtime: 88 ms (Beats 65.68%)
Time Complexity:
- strs의 길이 n 만큼 조회에 O(n)
- string을 key로 변환하는데 str... | Python | 1 |
done
// for i in 1 2 3 4; do for j in babe; do subkey --sr25519 inspect "$SECRET//$i//$j"; done; done
// for i in 1 2 3 4; do for j in im_online; do subkey --sr25519 inspect "$SECRET//$i//$j"; done; done
let initial_authorities: Vec<(
AccountId,
AccountId,
BabeId,
ImOnlineId,
)> = vec![(
// <KEY>
hex![... | Rust | 0 |
fn infix_fn(token: &Token) -> Option<InfixFn> {
match token {
Token::Plus
| Token::Minus
| Token::Multiply
| Token::Divide
| Token::Equal
| Token::NotEqual
| Token::LessThan
| Token::GreaterThan => Some(Parser::par... | Rust | 0 |
"""
Add trust_enabled to repository.
Revision ID: ed01e313d3cb
Revises: c3d4b7ebcdf7
Create Date: 2017-04-14 17:38:03.319695
"""
# revision identifiers, used by Alembic.
revision = "ed01e313d3cb"
down_revision = "c3d4b7ebcdf7"
import sqlalchemy as sa
def upgrade(op, tables, tester):
### commands auto generated... | Python | 1 |
List {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for comserv in &self.list {
write!(f, "{} - **{}** hour(s)", comserv.community_service_type, comserv.points)?;
}
Ok(())
}
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Course {
#[serde(... | Rust | 0 |
traceln!("app_task: Setting disabled...");
assert_eq!(driver.set_active(false).await, Ok(()));
traceln!("app_task: Did disable!");
traceln!("app_task: Checking device state... (Should be Ready)");
assert_eq!(
device_state_stream.try_next().a... | Rust | 0 |
# -*- coding: utf-8 -*-
"""Cisco Catalyst Center StartWirelessRogueAPContainmentV1 data model.
Copyright (c) 2024 Cisco Systems.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restrictio... | Python | 1 |
cursor_y, font_size as u16);
}
count += 1;
cursor_y += char_height as f32;
}
self.draw_data_count(data);
self.frame.render();
}
}
// Main function
raster_tools::sync_main!(run());
use raster_tools::{utils::*, *};
use rasters::prelude::*;
fn run() -> R... | Rust | 0 |
Some(target)) ^ (chars.get(*max - 1) == Some(target)) {
matching += 1
}
}
println!("{}", matching)
}
<reponame>rst0git/criu-image-streamer<filename>src/ord_by.rs
// Copyright 2020 Two Sigma Investments, LP.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may... | Rust | 0 |
turn False
return len(a) == len(b)
def cluster_expected(cluster):
for exp in expected_clusters:
if line_seg_groups_equal(exp, cluster):
expected_clusters.remove(exp)
return True
r... | Python | 1 |
lection" is volatile, but in bittorrent, a torrent
is non-volatile (and can be identified by a hash).
I suppose each "folder collection" (FC) should have its own asymmetric-key-pair (AKP)
(which may be the same as a user's AKP if they are the sole owner). All the meta
data about the data in the FC will be signed by th... | Rust | 0 |
from enum import Enum
class HardwareType(Enum):
COMPUTER = 'computer'
MOBILE = 'mobile'
class OperatingSystem(Enum):
ANDROID = 'android'
IOS = 'ios'
LINUX = 'linux'
WINDOWS = 'windows'
class SoftwareName(Enum):
CHROME = 'chrome'
| Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 14:50:38 2019
@author: zixing.mei
"""
def Num(feature,mth):
df=data.loc[:,feature +'1': feature +str(mth)]
auto_value=np.where(df>0,1,0).sum(axis=1)
return feature +'_num'+str(mth),auto_value
def Avg(feature, mth):
df=data.loc[:,feature +'1'... | Python | 1 |
"""
Team work Assignment:
This program will calculate the volume and surface area of a built in list of cans,
and list the information in a defined format.
"""
import math
#The main function that runs all of the code
def main():
# Variable listing NAME, RADIUS, HEIGHT, COST
can_names = ["#1 Picnic", 6.83, 10.16... | Python | 1 |
pub startup_grace_period: T::BlockNumber,
}
impl<T: Trait> Default for RoleParameters<T> {
fn default() -> Self {
Self {
max_actors: 10,
reward_period: T::BlockNumber::default(),
unbonding_period: T::BlockNumber::default(),
// not currently used
min_actors: 5,
bonding_period: T::BlockN... | Rust | 0 |
bout a user."""
if user == None:
user: disnake.Member = inter.author
e = disnake.Embed(description="")
roles = [
role.name.replace("@", "@\u200b")
for role in getattr(user, "roles", [])
if not role.id == inter.guild.default_role.id
]
... | Python | 1 |
image_edges<F: ForegroundColor>(
img: &mut image::DynamicImage,
method: MarkingMethod,
iterations: Option<u32>,
) -> Result<u32, SkeletonizeError> {
let mut pixels_to_remove = Vec::new();
let mut phase_one = true;
let iterations = iterations.unwrap_or(u32::MAX);
for iters in 0..iterations {... | Rust | 0 |
class InterfaceBase():
def message_user(self, message):
"""Overwrite this function to change how the user is messaged"""
print(message)
def get_user_input(self):
"""Overwrite this function to change how the user is messaged"""
# Get the input from the user
return input(... | Python | 1 |
law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use futures::StreamExt;
use st... | Rust | 0 |
a = real::Real::new(2.0);
let b = imagi::ImagI::new(3.0);
let c = a * &b;
assert_eq!(format!("{}", c), "+6i");
}
{
let a = real::Real::new(2.0);
let b = imagi::ImagI::new(3.0);
let c = &a * b;
assert_eq!(format!("{}", c... | Rust | 0 |
size, "nerbors mismatch with model setting"
# 1) 局部 FMT → coarse feature map [B, D, Hc, Wc]
k = int(self.FMT_focus_area)
row_starts = self._tiling_starts(int(X), k)
col_starts = self._tiling_starts(int(Y), k)
Hc, Wc = len(row_starts), len(col_starts)
feat_coarse = lowRe... | Python | 1 |
from .tools import (RTMO, YOLOX, Body, Hand, PoseTracker, RTMDet, RTMPose,
Wholebody, BodyWithFeet, Custom)
from .visualization.draw import draw_bbox, draw_skeleton
__all__ = [
'RTMDet', 'RTMPose', 'YOLOX', 'Wholebody', 'Body', 'draw_skeleton',
'draw_bbox', 'PoseTracker', 'Hand', 'RTMO', 'B... | Python | 1 |
g và $a_{ij} = 1$ nếu $i=j$ và $a_{ij} = 0$ nếu $i \neq j$.
* Ma trận đường chéo: Là ma trận có các phần tử trên đường chéo chính khác 0 và các phần tử còn lại bằng 0. Ví dụ về ma trận đường chéo:
$$\begin{split}\mathbf{A}=
\begin{bmatrix}
1 & 0 & 0 \\
0 & 2 & 0 \\
0 & 0 & 3
\end{bmatrix}
\end{split}$$
* Ma tr... | Python | 1 |
from django.contrib import admin
from .models import Currency, CurrencyPair, PriceData, EconomicIndicator, EconomicData
@admin.register(Currency)
class CurrencyAdmin(admin.ModelAdmin):
list_display = ('code', 'name', 'is_active')
search_fields = ('code', 'name')
list_filter = ('is_active',)
@admin.registe... | Python | 1 |
r the wedges.
""")
fill_props = Include(FillProps, use_prefix=False, help="""
The %s values for the wedges.
""")
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-------------------... | Python | 1 |
on)?;
let archive_path = root_directory.join("archive");
openfare_lib::common::fs::archive::download(&url, &archive_path)?;
let crate_directory = root_directory.join("crate");
let crate_directory =
openfare_lib::common::fs::archive::extract_tar_gz(&archive_path, &crate_directory)?;
Ok(crate... | Rust | 0 |
des[1].gettransaction(cert_1, False, include_immature_bts)['details']
assert_equal(2, len(details),
"gettransaction: inchain cert BT Mature outputs expected to be added.")
for detail in details:
assert_equal("receive", detail["category"], "gettransaction: different categ... | Python | 1 |
&mut R) -> PackResult<Self>
where
R: io::Read,
{
let format = u8::unpack(read)?;
let format = if let Some(format) = NonZeroU8::new(format) {
format
} else {
return Ok(Self(vec![]));
};
let len = A::len(format)?.get();
let mut buf ... | Rust | 0 |
aneuraOu
engine.input("setoption name NetWorkDelay2 value 0");
}
for engine in self.engines.iter_mut() {
engine.input("isready");
}
for engine in self.engines.iter_mut() {
engine.output("readyok");
}
while self.current_match_num.fetch... | Rust | 0 |
T'])
@jwt_required()
def admin_implicit_feedbacks():
if not admin_required():
return jsonify({'message': 'Forbidden'}), 403
try:
page = int(request.args.get('page', 1))
limit = int(request.args.get('limit', 25))
skip = (page - 1) * limit
filters = {}
if request.ar... | Python | 1 |
Events.Commit):
dependencies.search_cache.clear()
db.execute("insert into fts(fts) values ('optimize');")
db.commit()
faiss.write_index(index, str(config.index_path))
elif isinstance(event, Events.DeleteNotVisited):
inverse_pat... | Python | 1 |
$nested:tt)* } $dup:tt $($rest:tt)*) => {
impl_web_clean_nested!(($($outer)*) ($($done)*) { $($nested)* } { $($nested)* } $($rest)*);
};
(($($outer:tt)*) ($($done:tt)*) { #[patch $($attr:tt)*] $($nested:tt)* } $dup:tt $($rest:tt)*) => {
impl_web_clean_nested!(($($outer)*) ($($done)*) { $($nested... | Rust | 0 |
from hera.workflows import (
Artifact,
Container,
NoneArchiveStrategy,
Step,
Steps,
Workflow,
)
with Workflow(generate_name="artifact-passing-subpath-", entrypoint="artifact-example") as w:
hello_world_to_file = Container(
name="hello-world-to-file",
image="busybox",
... | Python | 1 |
8cw\xa5r\xc6\x1eNi\
\x19\x03\x0cR\x91\xfb\xcc\xf3\xff\x00\xb2\xd1\xb7\x9c\xf6\xa4\
\xb4\x02\xbbZ\x879#\xa5I\x1c`c\x03\xa5H\x5c\
/Ej\x01\xc0\x19\xe3\xd6\x9d\xf4\x10\xbbi\xa7\xa1\xa7\
2\x86\xc6\x0b\x8a\x5cqR\x16ec\xf2\x92\x07\x15%\
\xb4~d\x80v=\xe9%\x1c\xd4\xd6\xc4+\x0ex\xae\
LV\x90\x1aZ\x9d\x0e\x8bm\xb0\xe4\x0e\xd5\xb0\... | Python | 1 |
import pytraj as pt
from pytraj.testing import aa_eq, cpptraj_test_dir
from utils import fn
import pytest
import numpy as np
def aa_eq_abs(arr0, arr1):
aa_eq(np.abs(arr0), np.abs(arr1))
def test_analyze_modes():
for mask in ['@CA', '@N,CA', '@CA,H']:
command = '''
matrix mwcovar name tz2 {}
... | Python | 1 |
ened, concat_input])
final_output_focal = Dense(1, activation='sigmoid', name='output_focal')(phi_concat)
model = Model(input=[image_input,concat_input], output= final_output_focal)
learning_rate = 10 ** -5
adam = optimizers.Adam(lr=learning_rate)
model.compile(loss='logcosh',
op... | Python | 1 |
from typing import TypeVar, Type, Any, Callable
T = TypeVar("T")
class classproperty:
def __init__(self, func: Callable[[Type[T]], Any]) -> None:
self.fget = func
def __get__(self, instance: T, owner: Type[T]) -> Any:
return self.fget(owner)
| Python | 1 |
print("BMI kalkulátor")
magassagcmben = int(input("Testmagasságod (cm)[100;200]: "))
sulykgban = int(input("Testtömeg (cm)[40;150]: "))
bmi = sulykgban / (magassagcmben / 100) ** 2
print(f"Az Ön BMI-je:{bmi:.2f}") | Python | 1 |
all {
#[doc(hidden)] fn td_name(&self) -> &'static str { "notificationTypeNewCall" }
#[doc(hidden)] fn extra(&self) -> Option<String> { self.extra.clone() }
fn to_json(&self) -> RTDResult<String> { Ok(serde_json::to_string(self)?) }
}
impl TDNotificationType for NotificationTypeNewCall {}
impl NotificationTy... | Rust | 0 |
t i2 = Cplx::from(-1.0);
assert!(compare_z(i, Cplx::new(0.0, -1.0).conj()));
assert!(compare_z(i2.sqrt(), i));
assert!(compare_z(sqrt(i2), i));
}
}
<filename>src/tools/clippy/tests/missing-test-files.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]... | Rust | 0 |
data_type_lookup.lock().unwrap().insert(kept_posit.appearance_set().roles(), V::DATA_TYPE.to_string());
self.appearance_set_to_posit_thing_lookup
.lock()
.unwrap()
.insert(kept_posit.appearance_set(), kept_posit.posit());
}
(kept_posit, previou... | Rust | 0 |
72.mhz()) //72 works
.pclk1(24.mhz()) // 24 works
.freeze(&mut flash.acr);
let delay_source = p_hal::delay::Delay::new(cp.SYST, clocks);
let mut gpiob = dp.GPIOB.split(&mut rcc.ahb);
let mut gpioc = dp.GPIOC.split(&mut rcc.ahb);
//stm32f334discovery:
// let mut user_led1 = gpiob.p... | Rust | 0 |
import asyncio
import os.path
import PIL
import shared
from modules.api.call_internal import get_request_with_status
from PIL import Image
from io import BytesIO
import base64
import json
from typing import *
from modules.image_util import ImageUtil
class _ImageProgressAPI:
@staticmethod
def resize_eta(eta... | Python | 1 |
has_variable_info: true,
has_trace_info: false,
};
let argument = dlt::Argument {
type_info,
name: Some("temperature".to_string()),
unit: Some("celcius".to_string()),
fixed_point: None,
value: dlt::Value::I32(-23),
... | Rust | 0 |
eKGE):
'''Embedding with trigonometric functions. We represent all entities and relations in the complex number space as:
f(x) = \sum_{k=0}^{k=d-1}wk e^{kix}. and use the three differents scoring function as in the paper to evaluate the score'''
def __init__(self,args):
super().__init__(arg... | Python | 1 |
.clone(), x.1.clone(), STASH, StakerStatus::Validator))
.collect(),
invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(),
slash_reward_fraction: Perbill::from_percent(10),
..Default::default()
}),
}
}
/// Staging testnet config.
pub fn staging_testnet_config() -> ChainSpec {
fn sta... | Rust | 0 |
-> Result<Self, Self::Err> {
let low = s.to_ascii_lowercase();
match low.as_str() {
"yes" | "y" => Ok(Answer::Yes),
"no" | "n" => Ok(Answer::No),
_ => Ok(Answer::Retry),
}
}
}
fn is_full_word(s: &str) -> bool {
["yes", "no"].contains(&s.to_ascii_lowe... | Rust | 0 |
slice_() {
Ok(x) => ElementsRepr::Slice(x.into_iter()),
Err(self_) => ElementsRepr::Counted(self_.into_elements_base()),
}
}
}
}
#[derive(Clone)]
pub enum ElementsRepr<S, C> {
Slice(S),
Counted(C),
}
/// An iterator over the elements of an array.
///
///... | Rust | 0 |
let options = [
Self::Md5,
Self::Sha224,
Self::Sha256,
Self::Sha384,
Self::Sha512,
Self::Blake2s,
Self::Blake2b,
Self::Blake3,
]
... | Rust | 0 |
(&self.ev_buf_sync);
loop {
let ev_buf = if self.ev_buf_is_primary {
&mut self.ev_buf_primary
} else {
&mut self.ev_buf_secondary
};
if *lock || !ev_buf.push_many(events) {
*lock = true; // "the condvar should be pin... | Rust | 0 |
# 53. Maximum Subarray
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum, cur = nums[0], 0
for n in nums:
cur = n + max(cur, 0)
max_sum = max(cur, max_sum)
return max_sum
| Python | 1 |
# pip install flair==0.4.5
from typing import Iterable, List
from danlp.models import load_flair_ner_model, load_flair_pos_model
from flair.data import Sentence, Token
from spacy.lang.da import Danish
from spacy.tokens import Doc
from spacy.training import Example
tagger_ner = load_flair_ner_model()
tagger_pos = loa... | Python | 1 |
{
match err {
Error::OutOfBound(v) => raw_cbor::Error::CustomError(format!("coin ({}) out of bound, max: {}", v, MAX_COIN))
}
})
}
}
impl ops::Add for Coin {
type Output = Result<Coin>;
fn add(self, other: Coin) -> Self::Output {
Coin::new(self.0 + ot... | Rust | 0 |
# Get response with structured format
response_format = DocumentSourceResponse.model_json_schema()
# For models that use thinking step
if self.uses_thinking_step:
# First get thinking
thinking_messages = initial_messages.copy()
... | Python | 1 |
lf.conversation_history.append({
"role": "assistant",
"content": final_message
})
return final_message
else:
# 9. Fonksiyon bulunamazsa hata döndür
return f"Üzgünüm, {function_... | Python | 1 |
device") == "auto"
def test_profile_onprem_gpu_bf16_flash_maps_expected_fields() -> None:
kw = resolve_profile_engine_kwargs("onprem_gpu_bf16_flash")
assert kw.get("tensor_parallel_size") == 1
assert kw.get("enable_mixed_precision") is True
assert kw.get("mixed_precision_dtype") == "bf16"
assert k... | Python | 1 |
) -> Option<&Self::CursorType> {
self.response_metadata
.as_ref()
.and_then(|rm| rm.next_cursor.as_ref())
}
fn scrollable_items<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Self::ResponseItemType> + 'a> {
Box::new(self.channels.iter())
}
}
#[skip_serializing_none]
#... | Rust | 0 |
s=["path", "bytes", "str"]
)
@pytest.mark.parametrize(
"importer,file",
[
(import_svg, Path(__file__).parent / "svg_import_test.svg"),
(import_svg_as_buildline_code, Path(__file__).parent / "svg_import_test.svg"),
(import_stl, Path(__file__).parent / "cyl_w_rect_hole.stl"),
],
id... | Python | 1 |
, srange) tuple
for rt in cur_t {
t.push(rt);
s.push(Ranges::<u64>::new_unchecked(cur_s.clone()));
cur_s.clear();
}
// Propagate invalid Coverage FITS errors.
if t.len() != s.len() {
return Err("Number of time ranges and
spatial coverages do not match.");
... | Rust | 0 |
from ..errors import NoKeyToReleaseError
from ..compiled_ducky import CompiledDucky
from ..pre_line import PreLine
from ..environments.environment import Environment
from .bases.doc_command import ArgReqType
from .bases.simple_command import ArgLine, SimpleCommand
held_var_sys_key = "$HELD_KEY"
desc = f"""
Hold/Rele... | Python | 1 |
rd, We)
analogy('man', 'woman', 'husband', 'wife', word2idx, idx2word, We)
analogy('man', 'woman', 'actor', 'actress', word2idx, idx2word, We)
analogy('man', 'woman', 'father', 'mother', word2idx, idx2word, We)
analogy('heir', 'heiress', 'prince', 'princess', word2idx, idx2word, We)
analogy('nephew'... | Python | 1 |
tream] = _parse_results(item, results, verbose_logging)
if sorted_streams and (verbose_logging and settings_manager.settings.log_level):
top_results: List[Stream] = list(sorted_streams.values())[:10]
logger.debug(f"Displaying top {len(top_results)} results for {item.log_string}")
... | Python | 1 |
#%%
import gc
import torch
from diffusers import StableDiffusionPipeline
from sd_embed.embedding_funcs import get_weighted_text_embeddings_sd15
model_path = "/home/andrewzhu/storage_1t_1/sd15_models/deliberate_v2"
# model_path = "Lykon/dreamshaper-xl-1-0"
pipe = StableDiffusionPipeline.from_pretrained(
model_path,... | Python | 1 |
) -> Value {
Value::String(Arc::new(v.into_bytes()))
}
}
impl convert::From<Vec<u8>> for Value {
fn from(v: Vec<u8>) -> Value {
Value::String(Arc::new(v))
}
}
impl convert::From<&[u8]> for Value {
fn from(v: &[u8]) -> Value {
Value::String(Arc::new(v.to_vec()))
}
}
value_f... | Rust | 0 |
Button>("chooseRepositoryFolderButton")
}
pub fn findRepositoryPathLabel(gui: &TestGui) -> gtk::Label
{
gui.findWidget::<gtk::Label>("repositoryPathLabel")
}
pub fn findCommitLogView(gui: &TestGui) -> gtk::TreeView
{
gui.findWidget::<gtk::TreeView>("commitLogView")
}
pub fn findChooseOutputFolderButton(gui: ... | Rust | 0 |
()
time_difference = (comp_end_time - comp_start_time).total_seconds()/60
print('Time at end of computation: ', comp_end_time)
print("Execution time of program is: ", time_difference, "minutes")
# Find the minimum value in the cost_values array
min_cost = np.min(cost_values)
# Find the indices... | Python | 1 |
> {
OwnedConst::Integer(self)
}
fn to_owned(&self) -> OwnedConst<'t> {
OwnedConst::Integer(self.clone())
}
fn cast(&self, ty: &'t Type) -> Result<Cow<Const2<'t> + 't>, ConstError> {
if self.ty.as_type() == ty {
return Ok(Cow::Borrowed(self));
}
unimp... | Rust | 0 |
9999999")
# Realizar compra
self._realizar_compra_teste()
# Verificar se SMS foi enviado
# Em ambiente real, isso seria verificado através de um serviço de SMS
self.assertTrue(True) # Simulação
def _adicionar_produto_ao_carrinho(self):
self... | Python | 1 |
.out_file.clone())
.expect("Failed to save image.");
}
}
}
progress_bar.finish_with_message("done!");
println!("Time to render: {}", time.elapsed().as_millis());
tmp_image
.save(options.out_file)
.expect("Failed to save image.");
}
pub mod agent;
... | Rust | 0 |
printer::to_string(&ir);
match chkr.explain(&output, filecheck::NO_VARIABLES) {
Ok((success, report)) if !success => {
tracing::error!("--- FILECHECK FAILED FOR {}", path.display());
tracing::error!("{report}");
panic!()
}
Err(... | Rust | 0 |
nictwo": wydawnictwo,
"gatunek": gatunek,
"ilosc_sztuk": ilosc_sztuk,
"ilosc_dostepnych_sztuk": ilosc_sztuk
})
manager.budzet_ksiegarni = manager.budzet_ksiegarni - (ilosc_sztuk * cena_jednostkowa)
else:
print(f"Niestety, nie st... | Python | 1 |
import os
import torch
from fairseq import checkpoint_utils
from transformers import HubertModel
# use python < 3.11 https://github.com/facebookresearch/fairseq/issues/5012
class ContentvecExtractor(torch.nn.Module):
def __init__(self, cfg):
super(ContentvecExtractor, self).__init__()
self.model_pa... | Python | 1 |
0, February 12, 2004 with"]
#[doc = " June 12, 2009 markup."]
#[doc = ""]
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
pub struct acpi_table_spmi {
pub Header: ACPI_TABLE_HEADER,
pub InterfaceType: UINT8,
pub Reserved: UINT8,
pub SpecRevision: UINT16,
pub InterruptType: UINT8,
pub GpeNumber:... | Rust | 0 |
nnels=128,
kernel_size=5,
padding="same",
),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
)
# cls. head fc block: 128 from dec and 2 from map, * 2 due to max and avg pool
self.cls_fc = nn.Linear(in_features=128 * 2 + 2, out_feat... | Python | 1 |
Some(&String::from("workstation,core")),
);
assert_eq!(expected.sort(), results.sort());
expected = vec![];
results = get_target_sets(Some(&String::from("x64,arm64")), None);
assert_eq!(expected, results);
}
}
use crate::*;
use std::os::raw::c_char;
pub fn vk_to_strin... | Rust | 0 |
all_results[category] = category_results
except Exception as e:
print(f"❌ {category} 类别搜索失败: {e}")
all_results[category] = []
# 额外的Google深度搜索
await self.google_deep_search()
return all_results
async def google_deep_search(self):
... | Python | 1 |
(addr).map(|html| parse(&html))
}
#[cfg(test)]
mod tests {
use {crate::*, hyper::Server, tokio::runtime::Runtime};
#[test]
fn test_request() {
static HTML: &'static str = r#"<html>
<head><title>FooBar</title></head>
<body>Hello, world!</body>
</html>"#;
let (called_sender, called_receiver... | Rust | 0 |
np.array(pilImage, 'uint8')
Id = int(os.path.split(imagePath)[-1].split(".")[1])
faces.append(imageNp)
Ids.append(Id)
return faces, Ids
def TrackImages():
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("TrainingImageLabel\Trainner.yml")
harcascadePath = "haa... | Python | 1 |
.set_present(true);
entry.update();
let data = page_table.get_page_slice_mut(addr);
self.swapper.swap_in(token, data).map_err(|_| SwapError::IOError)?;
let pttoken = unsafe{
(*pt).token()
};
let frame = Frame::new(pt as usize, addr, pttoken);
;
self.sw... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import product_label_report
from . import product_pricelist_report
| Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.