text string | label_name string | labels int64 |
|---|---|---|
ostartItem::create_item_map().into_iter().filter(|(key, item)| AutostartUtils::is_k_module(item.file())).collect();
if let Some(current_model) = self.model {
let current_items: HashMap<String, AutostartItem> = current_model.items().into_iter().filter(|(key, item)| AutostartUtils::is_k_module(item.fi... | Rust | 0 |
if re.fullmatch(r"[\W_¿?¡!.\-\"'()\s]+", s or ""):
return True
if s.count("?") >= max(3, len(s) // 2):
return True
return False
# ======================
# Horarios
# ======================
DOW_MAP_ES = {
"L": 0, "LUN": 0, "LUNES": 0, "M": 1, "MAR": 1, "MARTES": 1, "X": 2, "MIE": 2,
"M... | Python | 1 |
.4415, I=np.diag([3, 3, 1])):
B = magnitometr_direct()
kstate1, kq1, komega1 = RS(state, q, omega, mu, I)
kstate2, kq2, komega2 = RS(state+kstate1*dt/2, q+dt/2 * kq1, omega + komega1*dt/2, mu, I)
kstate3, kq3, komega3 = RS(state+kstate2*dt/2, q+dt/2 * kq2, omega + komega2*dt/2, mu, I)
kstate4, kq4,... | Python | 1 |
y
//! [`dml()`]: ../struct.Connection.html#method.dml
//! [`exec()`]: ../struct.Connection.html#method.exec
//! [`ConnectParams`]: ../struct.ConnectParams.html
//! [`HdbValue`]: ../enum.HdbValue.html
//! [`HdbResponse`]: ../struct.HdbResponse.html
//! [`NCLob`]: types/struct.NCLob.html
//! [`Row`]: ../struct.Row.html
/... | Rust | 0 |
impl crate::Writable for FIFOWR {}
#[doc = "FIFO write data."]
pub mod fifowr;
#[doc = "FIFO write data for upper data bits. May only be used if the I2S is configured for 2x 24-bit data and not using DMA.\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with... | Rust | 0 |
# -*- coding: utf-8 -*-
"""`sphinx_rtd_theme` lives on `Github`_.
.. _github: https://www.github.com/snide/sphinx_rtd_theme
"""
from setuptools import setup
from sphinx_rtd_theme import __version__
setup(
name='sphinx_rtd_theme',
version=__version__,
url='https://github.com/snide/sphinx_rtd_theme/',
... | Python | 1 |
#constants
JOURNEY_IN_DAYS = 11
COST_FOOD_HUMAN_COPPER_PER_DAY = 4
COST_FOOD_HORSE_COPPER_PER_DAY = 3
#data
mainCharacter = {
'name' : 'Eias',
'ownsHorse' : True,
'adventuring' : True,
'cash' : {
'platinum' : 0,
'gold' : 1,
'silver' : 7,
'copper' : 5
}
}
friends = [... | Python | 1 |
fstr = attr
# here we can't use the thing_dict since formatter string might refer to properties
# TODO maybe use freezer instead?... or dump to dict with properties
res = fstr.format(**{f: getattr(thing, f) for f in fields})
for f in fields:
thing... | Python | 1 |
import numba as nb
import numpy as np
import pytest
import scipy.stats as sc
from numpy.testing import assert_allclose
from numba_stats import norm
def test_pdf_one():
x = 1
got = norm.pdf(x, 1, 2)
expected = sc.norm.pdf(x, 1, 2)
assert_allclose(got, expected)
def test_pdf():
x = np.linspace(-5... | Python | 1 |
# gui.Universal_Tools.Google_search
import os
import requests
from typing import Tuple, Union
from modules.Providers.OpenAI.openai_api import OpenAIAPI
from modules.logging.logger import setup_logger
logger = setup_logger('google_search.py')
SERPAPI_KEY = os.getenv("SERPAPI_KEY")
class GoogleSearch:
def __init_... | Python | 1 |
#!/usr/bin/python3
"""
This module contains a script that fetches tasks for all employees using
the JSONPlaceholder API and exports them to a
JSON file formatted by employee ID.
"""
import json
import requests
def export_all_tasks():
"""
Exports tasks for all employees to a JSON file.
"""
users_url =... | Python | 1 |
speaker_order = [p["id"] for p in participants_to_speak]
logger.info(f"輪次 {round_num} 實際剩餘發言順序: {speaker_order}")
# 更新上下文 (包含主席和可能的第一位發言者)
context_messages = conference["messages"][-15:]
context = "\\n".join([f"{msg['speakerName']} ({msg['speakerTitle']}): {msg['te... | Python | 1 |
key=lambda x: x[1])[1]
return best_individual_all, best_fitness_all, execution_time
# -------------------------------------------------------------------------
# Parameters for genetic algorithm
# -------------------------------------------------------------------------
population_size = 50
lower_bound = [data_... | Python | 1 |
import re,logging
import xml.etree.ElementTree as ET
from Utilities.Utils import ErrorlessRegex,REGEX_ERROR_MSG
class BaseSysParser:
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
self.re = ErrorlessRegex()
with open("specs/system.txt") as f:
self.s... | Python | 1 |
type CURLformoption = ::std::os::raw::c_uint;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct curl_forms {
pub option: CURLformoption,
pub value: *const ::std::os::raw::c_char,
}
pub const CURLFORMcode_CURL_FORMADD_OK: CURLFORMcode = 0;
pub const CURLFORMcode_CURL_FORMADD_MEMORY: CURLFORMcode = 1;
pub cons... | Rust | 0 |
#! /usr/bin/env python3
# Copyright (c) 2015 ARM Limited
# All rights reserved
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementati... | Python | 1 |
f;
use protos::master::Game;
use screen::Interfaceable;
use std::path::Path;
#[allow(unused_mut)]
pub fn load<I: Interfaceable>(
src: &mut I,
mut game: Game,
) -> Result<Game, MaeveError> {
src.print("I see you've been a guest with us before.");
src.print(&format!("Welcome back {}.", game.name));
r... | Rust | 0 |
elf) -> String {
self.get_eval()
}
}
<gh_stars>1-10
//! Provides mappings from symbols to their bit representation on a 7-segment display.
/// Shows which segment has which bit.
#[repr(u8)]
pub enum SegmentBits {
SegA = 0b00000001,
SegB = 0b00000010,
SegC = 0b00000100,
SegD = 0b00001000,
... | Rust | 0 |
# A one time script that updates the package.json file to use the "workspace:*" value for local packages.
# Except for @coral-xyz/anchor that doesn't live in this workspace.
import json
import glob
from collections import OrderedDict
def process_file(file_path):
try:
with open(file_path, 'r') as file:
... | Python | 1 |
import pyttsx3
import speech_recognition as sr
import datetime
import webbrowser
import os
import pyjokes
def listen():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
t... | Python | 1 |
find_sources_in_cwd failed");
let temp_dir = temp_dir.path();
let source_dir = temp_dir.join("foo");
fs::mkdir_recursive(&source_dir, io::UserRWX);
writeFile(&source_dir.join("main.rs"),
r#"#[crate_id="foo"]; fn main() { let _x = (); }"#);
command_line_test([~"install", ~"foo"], &sourc... | Rust | 0 |
idx].data),
None => None,
}
}
#[test]
fn test_kth_to_last() {
let test_cases = [
(vec![10, 20, 30, 40, 50], 1, 50),
(vec![10, 20, 30, 40, 50], 5, 10),
];
for case in test_cases {
let mut list = List::from(case.0.as_slice());
let kth = kth_to_last(&mut list, case.... | Rust | 0 |
# not all cases will be error
o = 'REQUIRED'
config_entries[finalname][setting] = Setting(setting, v, o, None)
# pretty please!
results = self._render_settings(config_entries[finalname])
if results:
# avoid heade... | Python | 1 |
name
.to_string()
.replace(config.package.name.as_str(), "")
})
.trim()
.replace(std::path::MAIN_SEPARATOR, "/");
if let Some(sitemap) = sitemap.get_sitemap_by_id(doc_id.as_str()) {
return doc.from_json(&sitemap, section);
... | Rust | 0 |
8
&sam4l::gpio::PC[25]], // Dummy Pin (regular GPIO)
8 * 4
);
let gpio = static_init!(
capsules::gpio::GPIO<'static, sam4l::gpio::GPIOPin>,
capsules::gpio::GPIO::new(gpio_pins),
224/8);
for pin in gpio_pins.iter() {
pin.set_client(gpio);
}
// # LEDs... | Rust | 0 |
DtvStat {
/// That QoS measure is not available. That could indicate
/// a temporary or a permanent condition.
FE_SCALE_NOT_AVAILABLE(NoScale),
/// The scale is measured in 0.001 dB steps, typically used on signal measures.
FE_SCALE_DECIBEL(ScaleDecibel),
/// The scale is a relative percentual m... | Rust | 0 |
_init() };
let in_out_len = in_out.len() - TAG_LEN - in_prefix_len;
match &asm_key.variant {
AES_128 => {
extern "C" {
fn aes128gcmsiv_dec(
input: *const u8,
output: *mut u8,
calculated_tag: *mut CalculatedTag,
... | Rust | 0 |
justed(expr).sty;
if let ty::TySlice(..) = ty.ty.sty;
if let ExprAddrOf(_, ref addressee) = expr.node;
if let Some(vec_args) = higher::vec_macro(cx, addressee);
then {
check_vec_macro(cx, &vec_args, expr.span);
}
}
// search fo... | Rust | 0 |
"""Unit test for plural2.py
This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""
__author__ = "Mark Pilgrim (mark@diveintopython.org)"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/03/17 14:34:40 $"
__copyr... | Python | 1 |
if isinstance(f, http.HTTPFlow):
self._change_reverse_host(f)
if 'websocket' in f.metadata:
self.waiting_flows.append(f)
if isinstance(f, websocket.WebSocketFlow):
hfs = [hf for hf in self.waiting_flows if hf.id == f.metadata['websocket_handshake']]
... | Python | 1 |
ports.push(setup_predicate_indicator(*t1)?);
export_list = *t2;
}
if export_list.to_constant() != Some(Constant::EmptyList) {
Err(ParserError::InvalidModuleDecl)
} else {
Ok(ModuleDecl { name, exports })
}
}
fn setup_use_module_decl(mut terms: Vec<Box<Term>>) -> Result<ModuleSo... | Rust | 0 |
e = utils::new_c_string("fail")?;
let vips_op_response = bindings::vips_gifload_buffer(
buffer_in,
buffer.len() as u64,
&mut out_out,
page_in_name.as_ptr(),
page_in,
n_in_name.as_ptr(),
n_in,
flags_in_name.as_ptr(),... | Rust | 0 |
#🔶 PART 1: list — Ordered and Changeable
#🧠 Explanation:
#A list is a collection — like a box — where you can store multiple values.
#These values are kept in order (1st, 2nd, 3rd...) and you can change them any time:
#You can add new values.
#You can remove values.
#You can update values.
#You can even loop t... | Python | 1 |
r("{name} must be nonnegative. Got {num}.")]
NegativeValue { name: &'static str, num: BigInt },
#[error("Unknown value for memory cell at address {addr}.")]
UnknownMemory { addr: MaybeRelocatable },
#[error("Memory is frozen and cannot be changed.")]
MemoryFrozen,
}
impl MemoryDict {
pub fn new... | Rust | 0 |
is not set, skip the calling test by returning early.
#[macro_export]
macro_rules! maybe_skip_kafka_integration {
() => {{
use std::env;
dotenv::dotenv().ok();
match (
env::var("TEST_INTEGRATION").is_ok(),
env::var("KAFKA_CONNECT").ok(),
) {
(true... | Rust | 0 |
(meme);
// useful for data transformation
{
let area = area_of(width, height);
println!("Area is {}", area);
// area's scope ends here
}
println!("Volume is {}", volume(width, height, depth));
// the ! is a macro, which is the only way you can call with variadic args
}
// ... | Rust | 0 |
ror> {
// Get user ID from cookie.
let viewer = auth.get_user_id_or_error().await?;
// Query API for auth object.
return AuthorizationFor::get(Some(viewer)).await;
}
/// Get meeting data and error if the authenticated user cannot edit the meeting.
async fn meeting_data_checked(
auth: &Authenticati... | Rust | 0 |
ase_addr + wc_sz * i as u64) as *mut ib_wc;
let wc = unsafe { *(wc_p) };
// start address of Header
let va = wc.get_wr_id() as u64 + UD_HEADER_SZ as u64;
// post back
let va_ptr = va as *mut i8;
let ... | Rust | 0 |
53)",
"Text",
],
),
(
"Real",
Value::float(f32::MIN),
&["DoublePrecision", "VarChar(53)", "VarChar", "Char(53)", "Text"],
),
(
"DoublePrecision",
Value::Double(Some(f64::MIN)),
&["DoublePr... | Rust | 0 |
heet for &ScrollableStyles {
fn active(&self) -> scrollable::Scrollbar {
scrollable::Scrollbar {
background: Some(Background::Color(self.background.into())),
border_radius: self.border_radius,
border_width: self.border_width,
border_color: self.border_color.in... | Rust | 0 |
"""
Copyright (C) 2022 LAAS-CNRS, INRIA
"""
import numpy as np
import proxsuite_nlp
from proxsuite_nlp.manifolds import EuclideanSpace
from proxsuite_nlp.autodiff import FiniteDifferenceHelper, FiniteDifferenceHelperC2
def test_fd_one_dim():
class MyFunction(proxsuite_nlp.BaseFunction):
def __init__(sel... | Python | 1 |
print(' Pspoof = {:8.5f} (Prior probability of spoofing attack)'.format(cost_model['Pspoof']))
print(' Cfa_asv = {:8.5f} (Cost of ASV falsely accepting a nontarget)'.format(cost_model['Cfa_asv']))
print(' Cmiss_asv = {:8.5f} (Cost of ASV falsely rejecting target speaker)'.format... | Python | 1 |
let mut sample = Vec::with_capacity(len);
for _j in 0..len{
let chs = letters.choose(&mut gen).unwrap();
sample.push(*chs);
}
let sample_s = String::from_utf8(sample).unwrap();
test_one(&sample_s);
... | Rust | 0 |
(&sk_path).expect(&format!("Failed to read from {}", &sk_path));
let aes_modes = vec!["aes-128-cbc", "aes-192-cbc", "aes-256-cbc"];
for aes_mode in &aes_modes {
for prf in prfs {
let algid_path = format!("./tests/examples/pbes2_{}_{}_algid.der", aes_mode, prf);
let algid_bytes ... | Rust | 0 |
n HTML document. There can be
/// only one `<body>` element in a document.
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body
<body>
categories {
Sectioning
}
children {
categories {
Flow
}
}
}
macro_rules! body_events {
... | Rust | 0 |
ize
return count, size
# test above functions performance
if __name__ == '__main__':
path = r'C:\Windows'
r1 = 'nothing'
t1 = time.time()
for i in range(10):
r1 = get_dir_size(path, return_list= True)
t2 = time.time()
print('get_dir_size + fList', t2-t1, len(r1[1]), r1[0], sep='\t')
t1 = time.time()
for... | Python | 1 |
}", s))?;
let mut game_state = initialize_state(cli_options, canvas, &ttf_context)?;
// runs every step
'main: loop {
for event in user_input_events.poll_iter() {
if handle_event(event, &mut game_state)? {
break 'main;
}
}
draw_canvas(&mut g... | Rust | 0 |
"""Билдеры сообщений.
# TODO @iamlostshe: Додель поддержку английского языка
Врядли ботом будет пользоваться не говорящий
по русски человек. Эта функция нужна больше
для эстетики, ибо у меня, думаю как и у многих
тг на английском и было бы приятнее получать
ответы на английском)
"""
from __future__ import annotation... | Python | 1 |
cat,
"%.03f +- %.03f" % (top1_original_mean, top1_original_sem),
"%.03f +- %.03f" % (top1_blurred_mean, top1_blurred_sem),
"%.03f" % (top1_original_mean - top1_blurred_mean),
"%.03f +- %.03f" % (top5_original_mean, top5_original_sem),
"%.03f +- %.03f" % (top5... | Python | 1 |
;
write!(output, "50={}\u{01}", val )?; // FIELD_SENDERSUBID
}
if header.sender_location_id.is_some() {
let val = header.sender_location_id.as_ref().unwrap();
write!(output, "142={}\u{01}", val )?; // FIELD_SENDERLOCATIONID
}
if header.target_sub_id.is_some() {
let val = ... | Rust | 0 |
ocation_inside_macro");
}
}<reponame>corinnewo/ji-cloud<filename>frontend/apps/crates/entry/module/drag-drop/edit/src/base/main/drag/state.rs
use crate::base::state::*;
use dominator_helpers::signals::{DefaultSignal, OptionSignal};
use shared::domain::jig::module::body::{Transform, _groups::design::Sticker as RawSt... | Rust | 0 |
().bold(),
"Clear Board".white().bold()
);
println!(
"{}{}",
"play".pad_to_width(20).white().bold(),
"Play Game".white().bold()
);
println!(
"{}{}",
"fill".pad_to_width(20).white().bold(),
"Fill Cell [x y num]".white().bold()
);
println!(
... | Rust | 0 |
# Atividade 03:
# Tabuada de um Número:
# Faça um programa que solicite um número ao usuário e use
# um laço while para exibir a tabuada desse número (de 1 a 10).
cont = 0
n =
while cont <= 9:
cont += 1
print(f'{cont} x ') | Python | 1 |
.replace(['', None], 'today').fillna('today')
all_jobs_df = devise_date_from_human_readable(all_jobs_df, 'posted_at', 'date_posted')
all_jobs_df = filter_jobs_by_date(all_jobs_df, day_interval, 'date_posted')
if not all_jobs_df.empty:
all_jobs_df = rename_serpapi_columns(all_jobs_df)... | Python | 1 |
hreads: u16,
/// number of concurrent HTTP connections to allow
#[serde(default = "default_concurrent_requests_max")]
pub concurrent_requests_max: usize,
/// address -- IP plus port -- to bind to
pub binding_addr: SocketAddr,
/// address -- IP plus port -- for prometheus exporting to bind to
... | Rust | 0 |
ce_count()
else:
print('Not using distributed mode')
args.distributed = False
return
args.distributed = True
torch.cuda.set_device(args.gpu)
args.dist_backend = 'nccl'
print('| distributed init (rank {}): {}'.format(
args.rank, args.dist_url), flush=True)
torch.... | Python | 1 |
def soma_imposto(taxa, custo):
soma = custo + (custo * taxa)
return soma
taxa = 0.2
custo = 1000
preco_final = soma_imposto(taxa, custo)
print(f"Preço final = {preco_final}") | Python | 1 |
ision-recall scores
"""
# dummy model
dummy = classification.dummy_classification()
# Get predicted probabilities for ROC-AUC
dummy_probs = dummy.predict_proba(classification.train_test['X_test'])[:, 1] # Probabilities for the positive class
# Calculate ROC-AUC score
dummy_roc_auc = roc_au... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
from mmeval.metrics import HmeanIoU
from mmeval.metrics.hmean_iou import compute_hmean
def test_compute_hmean():
with pytest.raises(AssertionError):
compute_hmean(0, 0, 0.0, 0)
with pytest.raises(AssertionError):
... | Python | 1 |
(
buf[i * 4 + 2] as f64 / 255.0,
buf[i * 4 + 1] as f64 / 255.0,
buf[i * 4 + 0] as f64 / 255.0,
buf[i * 4 + 3] as f64 / 255.0));
}
}
Image {
width,
height,
vec
}
}
pub fn combine(video_file_path: &str, audio_file... | Rust | 0 |
able!(),
}
}
// Parses a declaration.
pub fn parse_decl(mut pairs: Pairs<'static, Rule>) -> ast::Decl {
ast::Decl {
ident: pairs.next().unwrap().as_str(),
init: pairs.next().map(|pair| parse_expr(pair.into_inner())),
}
}
// Parses a block.
pub fn parse_block(pairs: Pairs<'static, Rule>) ->... | Rust | 0 |
j) % 2 != 0:
coef = coef * -1
newMatrix = Matrix(lenth=len(this.__list) - 1, weith=len(this.__list) - 1)
skip = 0
for x in range(len(this.__list)):
if x != i:
skip2 = 0
for y in range... | Python | 1 |
b"\x01";
/// # let res = S::parse(input);
/// # assert_eq!(res, Ok((&input[1..],S{a:1})));
/// # }
/// ```
///
/// ## Known problems
///
/// The generated parsers use the [nom] combinators directly, so they must be
/// visible in the current namespace (*i.e* imported in a `use` statement).
///
/// # Deriving parsers f... | Rust | 0 |
_view: Entity,
item: Entity,
(materials, handle_query): SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) {
let handle = handle_query.get(item).unwrap();
let materials = materials.into_inner();
let material = materials.get(handle).unwra... | Rust | 0 |
s.to_owned()
} else {
format!("pulsar://{}", s)
};
let url: url::Url = s.parse()?;
let scheme = match url.scheme() {
"pulsar" => Scheme::Tcp,
"pulsar+ssl" | "pulsar+tls" => Scheme::Tls,
_ => return Err(ParseError::SchemeMisma... | Rust | 0 |
.once()
.with(eq(1))
.return_once(|_| Box::pin(future::ok(())));
vr.expect_write_at()
.with(always(), eq(1), always())
.once()
.return_once(|_, _, _| Box::pin(future::ok(())));
let fsm = FreeSpaceMap::new(vr.zones());
let cluster = Clu... | Rust | 0 |
continue
username = t.get_username()
print('{} Authenticated!'.format(username))
server.shell_event.wait(timeout=event_timeout)
if not server.shell_event.is_set():
print('*** Client never asked for a shell.')
continue
server.exec_event.wait(timeout=... | Python | 1 |
from pyquery import PyQuery as pq
import requests
import psycopg2 as pg
def get_title(element):
return element.cssselect('.media-heading a')[0].text
def get_rating(element):
el = element.cssselect("div[style='color:#F1870A']")[0]
rating = len(el.cssselect('.glyphicon-star'))
if el.text_content()[-1] ... | Python | 1 |
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => Ok(0),
Err(error) => Err(error),
}?;
if count == 0 {
continue;
}
frames.extend_from_slice(&buffer[..count]);
loop {
match table.decode(&frames) {
Ok((frame,... | Rust | 0 |
self.matching, self.keep_original,
self.num_conformers, remove_hs=self.remove_hs, tries=self.matching_tries, skip_matching=self.skip_matching)
except Exception as e:
print(f'Skipping {name} because of the error:')
print(e)
return None
... | Python | 1 |
from copy import deepcopy
import pytest
from pint.models import get_model, get_model_and_toas
from pint.models.chromatic_model import ChromaticCM
from pint.models.timing_model import MissingParameter
from pint.simulation import make_fake_toas_uniform
from pint.fitter import WLSFitter
import astropy.units as u
from io ... | Python | 1 |
f32) -> msresamp_crcf;
}
extern "C" {
pub fn msresamp_crcf_destroy(_q: msresamp_crcf);
}
extern "C" {
pub fn msresamp_crcf_print(_q: msresamp_crcf);
}
extern "C" {
pub fn msresamp_crcf_reset(_q: msresamp_crcf);
}
extern "C" {
pub fn msresamp_crcf_get_delay(_q: msresamp_crcf) -> f32;
}
extern "C" {
... | Rust | 0 |
TableEntry [2]
Fixed(1.0), // track
UInt16(257), // name index
UInt16(56), // offset of the two per-size tracking values
// Size [0]
Fixed(12.0), // points
// Size [1]
Fixed(24.0), // points
// Per-size tracking values.
Int16(-15),
Int16(... | Rust | 0 |
import torch
import torch.nn.functional as F
def dpo_log_probs(model, prompt_ids, resp_ids):
''' Computes de log probabilities for each entry in the batch. Prompt + response.
Assumes dimensions prompt_ids [B, P] and resp_ids [B, R]
'''
device = prompt_ids.device
# Get dimensions
B, P = p... | Python | 1 |
s passing local HMM Viterbi bias filter: 6671 (0.09669); expected (0.15)
Windows passing local HMM Forward filter: 2037 (0.03161); expected (0.003)
Windows passing local HMM Forward bias filter: 1133 (0.01757); expected (0.003)
Windows passing glocal HMM Forward ... | Python | 1 |
,
GamepadAxisType::RightStickX => gamepad_input.right_stick.x = value,
GamepadAxisType::RightStickY => gamepad_input.right_stick.y = value,
_ => {}
}
}
}
}
}
<filename>components/case_macros/src/lib.rs
// Copyright 2021 ... | Rust | 0 |
dir: {}'.format(working_dir))
config_path = os.path.join(working_dir, 'train_config.pt')
train_config = torch.load(config_path)
device_config = set_distribution_train_config()
print(os.environ['MASTER_ADDR'])
print(os.environ['MASTER_PORT'])
world_size = torch.cuda.device_count()
local_ran... | Python | 1 |
from flask import Flask, request
from flask_cors import CORS
import logging
from app_config import configure_logger
from create_bfsi_assistant import create_app_assistant
from run_assistant import create_thread, create_msg, create_run
from run_assistant import get_steps, poll_run, get_msgs
configure_logger()
g_cache ... | Python | 1 |
(literal::TRUE) {
check_lint_err(env, s, literal::TRUE);
Ok(E_::True)
} else {
missing_syntax(&format!("boolean (not: {})", s), expr, env)
}
}
_ => missing_syntax("literal", ex... | Rust | 0 |
testAcc).round(2),
test_loss=np.mean(testLoss).round(2),
),
"log_type": "PID",
"UUID": self.pipeline_id,
}
)
training_metrics["val_loss"].append(float(np.mean(testAcc)))
training_metri... | Python | 1 |
bits from a raw u8 outside of this crate
unreachable!()
}
}
}
pub const fn eight() -> WindowBits {
WindowBits(8)
}
pub const fn nine() -> WindowBits {
WindowBits(9)
}
pub const fn ten() -> WindowBits {
WindowBits(10)
}
pub ... | Rust | 0 |
st G2_GENERATOR_Y: Fq2 = field_new!(Fq2, G2_GENERATOR_Y_C0, G2_GENERATOR_Y_C1);
// Generator:
// (3519382844713541579002133617775236000337302709092053889907196608497211512910083011998063983635946531824025900302318*sqrt7 + 5091479006341624589567896397635435258574014748076809289641574502625108749078943401554928186045022... | Rust | 0 |
ncoding='utf-8') as f:
for num_doc, doc in enumerate(f):
doc = doc.replace('\n', '')
if not doc:
continue
chars, tags = self.space_tag(doc)
for w in range(self.min_window, self.max_window + 1):
for c... | Python | 1 |
gen_cert()?;
let main_ca_dir = format!("{}/CA/root", &config.out_dir);
// let filename = format!("admin-{}", bundle.cert.serial_number().to_bn().unwrap());
// let symlink_path = format!("{}/master/admin", &config.out_dir);
write_bundle_to_file(&bundle, &main_ca_dir, "admin", config.overwrite).unwrap();
... | Rust | 0 |
if last_head == tail {
return Result::Err(());
}
match self.head.compare_exchange(last_head, nlast,
Ordering::Acquire, Ordering::Relaxed) {
Result::Ok(_) => {
// last_head = x;
break;
},
... | Rust | 0 |
import whisperlite
import time
model = whisperlite.load_model("turbo")
start = time.time()
result = model.transcribe("test_v0.mp3")
print(result["text"])
print(f'{time.time() - start:.2f} seconds') | Python | 1 |
_to == '/':
raise ValidationError(_('"URL to" cannot be set to "/". To change the homepage content, use the "Homepage URL" field in the website settings or the page properties on any custom page.'))
if any(
rule for rule in self.env['ir.http'].routing_map().iter_... | Python | 1 |
reAddressInfoKHR.html) · Alias"]
#[doc(alias = "VkDeviceMemoryOpaqueCaptureAddressInfoKHR")]
#[allow(non_camel_case_types)]
pub type DeviceMemoryOpaqueCaptureAddressInfoKHRBuilder<'a> = crate::vk1_2::DeviceMemoryOpaqueCaptureAddressInfoBuilder<'a>;
#[doc = "[Vulkan Manual Page](https://www.khronos.org/registry/vulkan/s... | Rust | 0 |
_exists(self, path_name)
}
pub fn read_block(
&self,
path_name: &str,
data_attrs: &wrapped::DatasetAttributes,
grid_position: Vec<u64>,
) -> Promise {
N5PromiseReader::read_block(self, path_name, data_attrs, grid_position)
}
pub fn list_attributes(&self, pat... | Rust | 0 |
stats_map_py.set_item(k, Z3RStatPy::from(v))?;
}
let equip_map_py = get_equip_map(py, &mut equip_map)?;
let sram_map = PyDict::new(py);
sram_map.set_item("meta", meta_map_py)?;
sram_map.set_item("stats", stats_map_py)?;
sram_map.set_item("equipment", equip_map_py)?;
Ok(sram_map)
}... | Rust | 0 |
er('Đánh giá mô hình')
if 'data' in st.session_state and 'y_pred' in st.session_state:
data = st.session_state['data']
y_pred = st.session_state['y_pred']
# Tính toán metrics
from streamlit_extras.stylable_container import stylable_container
... | Python | 1 |
import re
from django.db.utils import IntegrityError
from rest_framework import serializers
from .models import User, Appeal, CommissionInfo, AdminRequest
from decouple import config
# Загрузка конфигурации из .env
MIN_TXT_LENGTH = int(config('MIN_TXT_LENGTH')) # Минимальная длина текста
MAX_TXT_LENGTH = int(config(... | Python | 1 |
from django.contrib.admin.views.main import PAGE_VAR
from django.template import Library
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.http import urlencode
from django.contrib.admin.templatetags.base import InclusionAdminNode
register = Library()
DOT = '.'... | Python | 1 |
}
}
}
pub fn update_all_deterministic_nodes(&self, gv: &GraphVar<T>) {
for i in 0..self.nodes.len() {
self.update_deterministic_value_of(i, gv);
}
}
pub fn logpost_all(&self, gv: &GraphVar<T>) -> T {
let mut result = zero();
self.update_all_determini... | Rust | 0 |
{Searcher: &crashSearcher{}},
}
q := &query.Substring{Pattern: "hoi"}
opts := &zoekt.SearchOptions{}
if res, err := ss.Search(context.Background(), q, opts); err != nil {
t.Fatalf("Search: %v", err)
} else if res.Stats.Crashes != 1 {
t.Errorf("got stats %#v, want crashes = 1", res.Stats)
}
if res, err := s... | Rust | 0 |
attention kernel using CuteDSL template."""
if not ensure_flash_available():
raise RuntimeError("CUTE flash attention not available")
# Get dimensions
batch_size, num_heads, seq_len_q, head_dim = query.get_size()
v_head_dim = value.get_size()[-1]
device = query.get_device()
dtype = que... | Python | 1 |
#[serde(rename = "2")]
HundredthsOfASecond,
/// milliseconds
#[serde(rename = "3")]
Milliseconds,
/// microseconds
#[serde(rename = "4")]
Microseconds,
/// nanoseconds
#[serde(rename = "5")]
Nanoseconds,
/// minutes
#[serde(rename = "10")]
Minutes,
/// hours
#[serde(rename = "11")]
Hours,
/// days
#[s... | Rust | 0 |
> w,
None => return Err(io::Error::new(io::ErrorKind::InvalidData,
"missing names"))
};
hosts.push(Host{
address: addr,
name: name.to_owned(),
aliases: words.map(|s| s.to_owned()).collect(),
});
}
Ok(HostTable{hosts: hosts... | Rust | 0 |
go to a zone authority (i.e. the server used in the ClientConnection). If
/// the rrset does not exist and must_exist is false, then the RRSet will be deleted.
fn delete_rrset(&self, record: Record, zone_origin: Name) -> ClientResult<DnsResponse> {
let mut reactor = Runtime::new()?;
let (bg, mu... | Rust | 0 |
[doc = "Reader of field `ADLSMP`"]
pub type ADLSMP_R = crate::R<bool, ADLSMP_A>;
impl ADLSMP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ADLSMP_A {
match self.bits {
false => ADLSMP_A::_0,
true => ADLSMP_A::_1,
}
}
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.