text string | label_name string | labels int64 |
|---|---|---|
, ReadWrite>: Sync, Send);
}
#[test]
fn test_register_no_clone_copy() {
assert_not_impl_all!(RegisterWindow<u8, ReadWrite>: Clone, Copy);
assert_not_impl_all!(RegisterWindow<u16, ReadWrite>: Clone, Copy);
assert_not_impl_all!(RegisterWindow<u32, ReadWrite>: Clone, Copy);
ass... | Rust | 0 |
e::src::jerror::JWRN_TOO_MUCH_DATA;
pub use crate::src::wrbmp::cmyk_h::cmyk_to_rgb;
pub use crate::src::wrbmp::jmorecfg_h::rgb_blue;
pub use crate::src::wrbmp::jmorecfg_h::rgb_green;
pub use crate::src::wrbmp::jmorecfg_h::rgb_pixelsize;
pub use crate::src::wrbmp::jmorecfg_h::rgb_red;
use crate::stdlib::ferror;
use crat... | Rust | 0 |
str.replace("Bearer ", "").clone(),
Err(_) => String::from(""),
},
None => String::from(""),
}
}
pub(crate) async fn verify(req: &Request<Body>) -> String {
match verify_online(req).await {
Ok(t) => t,
_ => String::from(""),
}
}
async fn verify_online(req: &Requ... | Rust | 0 |
import random
import datetime
import mysql.connector
# Ustawienia połączenia z bazą danych
db_config = {
'user': 'team11',
'password': 'te@mzaii',
'host': 'giniewicz.it',
'database': 'team11',
'port': 3306
}
# Zbiór wykluczanych świąt
EXCLUDED_DATES = {(12, 31), (1, 1), (1, 6), (3, 31), (4, 1), (5... | Python | 1 |
import requests, csv
from bs4 import BeautifulSoup
from urllib3.filepost import writer
head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36 Edg/89.0.774.77",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,im... | Python | 1 |
match diff.0 {
Some(val) => Ok(val),
None => Ok(Self::default()),
}
}
#[inline(always)]
fn into_diff(self) -> crate::Result<Self::Type> {
Ok($diff(Some(self)))
}
... | Rust | 0 |
= rewards[i] + self._discount * prev_value * (1 - dones[i]) - values[i]
# ref: https://arxiv.org/pdf/1506.02438.pdf (generalization advantage estimate)
advantages[i] = deltas[i] + self._discount * self._gae * prev_advantage * (1 - dones[i])
prev_return = returns[i]
prev... | Python | 1 |
net::{Ipv4Addr, SocketAddr},
path::PathBuf,
sync::Arc,
};
use substrate_test_client::{
BlockchainEventsExt, RpcHandlersExt, RpcTransactionError, RpcTransactionOutput,
};
/// Declare an instance of the native executor named `ElexeumTestExecutorDispatch`. Include the wasm binary as the
/// equivalent wasm code.
pub... | Rust | 0 |
funcs_t) -> hb_bool_t;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct hb_font_extents_t {
pub ascender: hb_position_t,
pub descender: hb_position_t,
pub line_gap: hb_position_t,
pub reserved9: hb_position_t,
pub reserved8: hb_position_t,
pub reserved7: hb_position_t,
pub reserved6: hb... | Rust | 0 |
aker_clone(_this: *const ()) -> RawWaker {
panic!("unimplemented");
}
fn raw_waker_wake(_this: *const ()) {
panic!("unimplemented");
}
fn raw_waker_wake_by_ref(_this: *const ()) {
panic!("unimplemented");
}
fn raw_waker_drop(_this: *const ()) {}
static RAW_WAKER: RawWakerVTable = RawWakerVTable::new(
r... | Rust | 0 |
ndex>,
SPqPtr: Option<Eindex>,
GPqPtr: Option<Eindex>,
}
<gh_stars>0
use crate::ast::Exp;
use std::fmt::{self, Display};
impl Display for Exp {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Exp::Var(.., name) => write!(fmt, "{}", name),
Exp::Abs(.., n... | Rust | 0 |
!objtype::issubclass(cls, &vm.ctx.list_type()) {
return Err(vm.new_type_error(format!("{:?} is not a subtype of list", cls)));
}
let elements = if let Some(iterable) = iterable {
vm.extract_elements(iterable)?
} else {
vec![]
};
Ok(PyObject::new(
PyObjectPayload::S... | Rust | 0 |
doc = "Configuration"]
pub mod conf;
#[doc = "FTM Fault Input Polarity\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API]... | Rust | 0 |
/// Fixed Dimension 3
pub struct Fixed3;
/// Dynamically sized dimension
pub struct Dynamic;
pub trait SizeIdentifier {
const IDENT: MatrixSizeType;
}
impl SizeIdentifier for Fixed1 {
const IDENT: MatrixSizeType = MatrixSizeType::ONE;
}
impl SizeIdentifier for Fixed2 {
const IDENT: MatrixSizeType = Matri... | Rust | 0 |
()
.map(|var| var.parse().expect("bad cloud endpoint provided"))
.unwrap_or_else(|| cloud_endpoint.clone());
Ok(Authentication {
access_key_id,
secret_access_key,
account,
project,
cloud_endpoint,
api_endpoint,
})
}
pub fn main() {
let spawn_... | Rust | 0 |
ie]].reset_index(drop=True)
# flop5 = df_stats[categorie].tail(5)[['Objet', categorie]].reset_index(drop=True)
# top5.columns = [f'Top 5 {categorie}', f'Top {categorie}']
# flop5.columns = [f'Flop 5 {categorie}', f'Flop {categorie}']
# else:
# top5 = df_stats[cate... | Python | 1 |
1, 44, 240, 166, 159, 162, 107, 58,
126, 190, 11, 22, 56, 17, 96, 27, 179, 173, 9
]
.into(),
[
87, 69, 133, 181, 55, 135, 65, 98, 105, 71, 175, 166, 169, 105, 11, 82, 66, 250,
166, 198, 232, 223, 130, 20, 236, 2, 0, 207, 179, 65, 151, 7... | Rust | 0 |
R18, R17, R16, R15, R14, R13, R12, R11, R10, R9, R8, R7, R5, R4, R3, R2, R1);
impl_range!(R30, 30,
X00 = 0x00,
X01 = 0x01,
X02 = 0x02,
X03 = 0x03,
X04 = 0x04,
X05 = 0x05,
X06 = 0x06,
X07 = 0x07,
X08 = 0x08,
X09 = 0x09,
X0a = 0x0a,
X0b = 0x0b,
X0c = 0x0c,
X0d = 0x... | Rust | 0 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more i... | Python | 1 |
ANGE_TYPE,
pub pApplication: *mut PEER_APPLICATION,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Networking_WinSock"))]
impl ::core::marker::Copy for PEER_EVENT_APPLICATION_CHANGED_DATA {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Networking_WinSock"))]
impl ::core::clone::Clone for PEE... | Rust | 0 |
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroSerializer
from confluent_kafka.serialization import StringSerializer
class AvroSerializationManager:
def __init__(self, schema_registry_url, auth_user_info, topic, to_dict):
"""
In... | Python | 1 |
ring::aead;
use std::mem;
use std::sync::{Arc, Mutex};
use std::time;
/// The timebase for expiring and rolling tickets and ticketing
/// keys. This is UNIX wall time in seconds.
pub fn timebase() -> u64 {
time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_secs()
}
/... | Rust | 0 |
} else {
self.status_message.draw_text("Miss! ", &self.tile_set,17 + s.len() as u32 + 2,0,Self::HIBLU,TRANSPARENT);
}
}
if self.status == Status::PlayerBomb {
self.status_message.draw_text("Player", &self.tile_set,0,0,Self::HIB... | Rust | 0 |
from django.core.management.base import BaseCommand
from django.db import models
from tournaments.models import Tournament, Team
from tournaments.logic import generate_single_elimination_matches, generate_double_elimination_matches
class Command(BaseCommand):
help = '測試淘汰賽演算法'
def add_arguments(self, parser)... | Python | 1 |
/ This macro accepts a single expression with type `&mut Vec<T>` where `T`
/// is any numeric types followed by `=>` then the Brain-Flak code. After the
/// macro invocation, the passed value is then left with the active stack as if
/// it is the output.
///
/// # Brain-Flak reference table
///
/// | Nilad | Return val... | Rust | 0 |
ue
0x2AAA58: 0x3C2C0200,
0x2AAA5C: 0x3F2C0500,
0x2AAA74: 0x2110A200,
0x2AAB74: 0x3C2C0200,
0x2AAB78: 0x3F2C0500,
0x2AAB90: 0x2118A200,
# eflSifRpc::flSifRpcInit mismatched __LINE__'s in assert
0x310EE0: 0x2D280000,
0x310FA8: 0x2D280000,
0x311070: 0x2D280000,
# cse::cseCheck... | Python | 1 |
for imgs, labels in mnist_trainloader:
imgs = imgs.to(device)
labels = labels.to(device)
logits = model(imgs)
loss = F.cross_entropy(logits, labels)
loss.backward()
optimizer.step()
optimizer.zero_grad()
loss_list.append(loss.item()) # .item() converts single-elem tensor to scalar
# %%
if M... | Python | 1 |
from nonebot import on_keyword, on_fullmatch
from nonebot.adapters.onebot.v11 import MessageSegment, event, Bot, GroupMessageEvent, Message
import requests
ph = on_fullmatch({"段位排行","段位数据"})
#单链表
class Node:
#数据
data = {
"rank_elo":None,
"name":None,
"elo":None,
"primaryFaction... | Python | 1 |
td::cmp::Ordering;
use std::iter::empty;
use std::mem::swap;
use std::ops::{Index, IndexMut};
use crate::tree::bst::{BinarySearchTree, BstDirection, OrderedTree};
use crate::tree::traversal::{BinaryInOrder, BinaryInOrderIndices, Traversable};
use crate::tree::WeightedTree;
use crate::types::{DefaultWeightType, Keys, Ke... | Rust | 0 |
DirectoryManager},
run_test_suite_lib::diagnostics,
std::fs::File,
std::io::{stdout, Write},
std::path::PathBuf,
};
const RUN_BUILDER_SELECTOR: &str = "core/test_manager:expose:fuchsia.test.manager.RunBuilder";
struct RunBuilderConnector {
remote_control: fremotecontrol::RemoteControlProxy,
}
#[... | Rust | 0 |
data_loader(i, input_x, input_y):
return input_x[i * batch_size : (i + 1) * batch_size], input_y[i * batch_size : (i + 1) * batch_size]
engine = Engine(lambda e, i: data_loader(i, x, y))
m = HSIC(sigma_x=sigma_x, sigma_y=sigma_y, device=metric_device)
m.attach(engi... | Python | 1 |
::COMMA) {
return Box::new(ast::ZeroValueExpression {});
}
Box::new(hash)
}
fn parse_infix_expr(parser: &mut Parser, left: Box<dyn ast::Expression>) -> Box<dyn ast::Expression> {
let mut expr = ast::InfixExpression{
token: parser.current_token.clone(),
operator: parser.current_toke... | Rust | 0 |
pixels` does not contain enough data for
/// at least `width * height * depth` pixels.
///
/// # Example
///
/// ```rust
/// use web_glitz::image::LayeredImageSource;
///
/// let data: Vec<[u8; 3]> = vec![[255, 0, 0]; 256 * 256 * 256];
/// let image_source = LayeredImageSource::from_... | Rust | 0 |
fn to_real_freq_mat(self) -> Self::Output {
to_mat_3xn(self, |v| v.to_real_freq_vec())
}
}
impl<T, S> ToRealFreqMatrix<RealFreqVec<S, T>, T> for [S; 4]
where
T: RealNumber,
S: ToRealVector<T> + ToSlice<T>,
{
type Output = Matrix4xN<RealFreqVec<S, T>, S, T>;
fn to_real_freq_mat(self) -> Sel... | Rust | 0 |
s.is_set(AllEndpointInterrupt::OUT0);
let inter_ep0_in = pending_interrupts.is_set(AllEndpointInterrupt::IN0);
let inter_ep1_out = pending_interrupts.is_set(AllEndpointInterrupt::OUT1);
let inter_ep1_in = pending_interrupts.is_set(AllEndpointInterrupt::IN1);
... | Rust | 0 |
tar.gz",
"-C",
"/runner",
],
&options,
)?)?;
options.cwd = String::from("/runner");
let mut labels = String::from("octoling");
labels.push(',');
labels.push_str(label);
// https://docs.github.com/en/rest/reference/actions#create-a-registration-token-for... | Rust | 0 |
ine(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
impl R {
#[doc = "Bits 8:31 - 31:8\\] This register is 8 bits in a 32-bit address space."]
#[inline(always)]
pub fn reserved32(&self) -> RESERVED3... | Rust | 0 |
from polars.io.cloud.credential_provider._providers import (
CredentialProvider,
CredentialProviderAWS,
CredentialProviderAzure,
CredentialProviderFunction,
CredentialProviderFunctionReturn,
CredentialProviderGCP,
)
__all__ = [
"CredentialProvider",
"CredentialProviderAWS",
"Credent... | Python | 1 |
> entry.key(),
Vacant(ref entry) => entry.key(),
}
}
/// Provides in-place mutable access to an occupied entry before any
/// potential inserts into the map.
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut C::Value),
{
match self {
O... | Rust | 0 |
ream,
N: event::Stream,
{
fn next_event(&mut self) -> event::StreamResult {
self.stream.next_event()
}
}
/// Prepends another stream to the contents of the current element.
pub struct PrependContent<S, N>
where
S: event::ElementStream,
N: event::Stream,
{
stream: modifier::select::Selec... | Rust | 0 |
Location.Costal_Process_Left,
Location.Costal_Process_Right,
Location.Superior_Articular_Left,
Location.Superior_Articular_Right,
Location.Inferior_Articular_Left,
Location.Inferior_Articular_Right,
Location.Vertebra_Corpus,
]
if with_border:
label... | Python | 1 |
# Write a program to check if a word is a palindrome.
word = input("Enter a word: ")
reversed_word = word[::-1]
if word == reversed_word:
print(word, "is a palindrome.")
else:
print(word, "is not a palindrome.")
| Python | 1 |
_types::*;
///
/// assert_eq!(ROk::<u32, u32>(10).ok(), RSome(10));
/// assert_eq!(RErr::<u32, u32>(5).ok(), RNone);
///
/// ```
#[inline]
pub fn ok(self) -> ROption<T> {
match self {
ROk(t) => RSome(t),
RErr(_) => RNone,
}
}
/// Converts from... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors
# Generate sample data
amplitude = 10
num_points = 100
X = amplitude * np.random.rand(num_points, 1) - 0.5 * amplitude
# Compute target and add noise
y = np.sinc(X).ravel()
y += 0.2 * (0.5 - np.random.rand(y.size))
# Plot input data
pl... | Python | 1 |
return Some(" ".repeat(space));
} else if txt.len() == 1 {
return left(txt[0], space);
}
// Work out total space needed between the columns
let left_over = space - len;
let pad_places = txt.len().saturating_sub(1); // Number of places where padding is required
let each = left_over / pad_... | Rust | 0 |
sher.finalize().to_vec();
let prk = hkdf_extract(&salt, ikm_with_postfix.as_bytes());
let okm = &hkdf_expand(prk, &info, MOD_R_L);
output = mod_r(okm.as_bytes());
}
output
}
/// Interprets `bytes` as a big-endian integer and returns that integer modulo the order of the
/// BLS-381 cur... | Rust | 0 |
pub fn is_sp4_1(&self) -> bool {
**self == SP4_A::SP4_1
}
}
impl core::ops::Deref for SP4_R {
type Target = crate::FieldReader<bool, SP4_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SP4` writer - Supervisor Protect"]
pub struct SP4_W<'a> {
... | Rust | 0 |
e];
sealer(&key, &nonce, input, default_aad, &mut dst_out_ct).unwrap();
let mut dst_out_pt = input.to_vec();
assert!(opener(&key, &nonce, &dst_out_ct, Some(b"BAD AAD"), &mut dst_out_pt).is_err());
}
#[cfg(feature = "safe_api")]
/// Using None or Some with empty slice should produce the exact same result.
fn none_o... | Rust | 0 |
i/rest/reference/online-store/asset#show-2020-04
*
* **Parameters:**
*
* * `theme_id: &str` -- storefront_access_token_id.
* * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names.
* * `asset_key: &str` -- storefront_access_token_id.
*/
pub async... | Rust | 0 |
e:
'''
calculate lap time for first lap based on position after turn 1
idx is the position (zero indexed) of the participant after turn 1
'''
random_time_loss = self.randomiser.random_lap1_time_loss()
self.laptime = self.track_model.base_laptime + turn1_time + (idx * LAP1_TIME_LOSS_PER_POSITION) + random_ti... | Python | 1 |
os.environ['MASTER_PORT'] = '12355'
return local_rank
if __name__ == "__main__":
# Example usage
from model.config import ModelConfig, TrainingConfig
from transformers import GPT2TokenizerFast
# Setup
local_rank = setup_distributed_training()
model_config = ModelCon... | Python | 1 |
Box_<dyn Fn(&Widget, &glib::Variant) -> bool + 'static>>> =
Box_::new(callback);
unsafe extern "C" fn callback_func(
widget: *mut gtk_sys::GtkWidget,
args: *mut glib_sys::GVariant,
user_data: glib_sys::gpointer,
) -> glib_sys::gboolean {
let wi... | Rust | 0 |
dyn Value>>>,
pub block: Option<Box<dyn Value>>,
pub kind: Option<Box<dyn Value>>,
pub name: Box<dyn Value>,
pub scope: Option<TScope>,
}
impl Default for Function {
fn default() -> Self {
Function::new(vec![], void!(), void!(), void!(), None)
}
}
impl fmt::Display for Function {
fn fmt(&self, f: &m... | Rust | 0 |
# coding=utf-8
# Copyright 2024 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Python | 1 |
import datetime
import threading
import time
import wbi as API
import ws as WebsocketTools
import gui
def __recv_msg(msg: WebsocketTools.Message):
print(msg)
content = (
datetime.datetime.fromtimestamp(int(time.time())).strftime("%H:%M:%S"),
msg.from_nickname,
msg.content
)
tre... | Python | 1 |
\n}\
\n"
);
}
<gh_stars>10-100
// This file is part of HydraDX.
// Copyright (C) 2020-2021 Intergalactic, Limited (GIB).
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
/... | Rust | 0 |
.append({
"id": cap.lower().replace(" ", "_"),
"name": cap,
"description": f"Ability to {cap.lower()}",
"confidence": 0.8
})
else:
processed_capabilities.append(cap)
return await ... | Python | 1 |
all(&buf[..])?;
self.writer.flush()?;
Ok(())
}
}
<reponame>3cL1p5e7/ic
//! Canonical State traversal using lazy trees, i.e. a tree with nodes that are
//! lazily initialized if and when traversed.
//!
//! Lazy trees allow e.g. comparing 2 Canonical States without materializing
//! them; certified i... | Rust | 0 |
sult, 0);
debug!("successfully read drandom={}", drandom);
Ok::<_, anyhow::Error>(drandom)
})
.await?;
let full_path = smol::unblock(|| fs::canonicalize(mount_point)).await?;
let cstr_path = full_path.to_str().context(format!(
"failed to convert full mount path={:?} to string",
... | Rust | 0 |
&select_query::Select::Only(ref fields) => {
let defs: Vec<String> = fields.iter().map(|f| f.expression_as_sql().to_sql(ctx)).collect();
defs.join(", ")
},
&select_query::Select::All => "*".to_string()
}
}
}
impl<T: fmt::Debug, L: fmt::Debug, M:... | Rust | 0 |
self.gicd_base, crate::GICD_TYPER)) }
}
fn gicd_read_ctlr(&self) -> GicdCtlrS {
unsafe { read_volatile(to_ptr(self.gicd_base, crate::GICD_CTLR)) }
}
// ------------------------------------------------------------------------
// GICD write
/// Accessor to write the GIC Distributor IGRO... | Rust | 0 |
lista = [0, 1, 24, 3, 4]
indice1 = 1
indice2 = 3
if indice1 < 0 or indice2 < 0:
print("Error, el índice no puede ser menor que 0")
elif indice1 > len(lista) or indice2 > len(lista):
print("Error, el índice no puede ser mayor a la longitud de la lista")
else:
num1 = lista[indice1]
num2 = lista[indice2] ... | Python | 1 |
)]
pub struct CacheService{
pub cache: Arc<Mutex<Cache>>,
pub pool : Box<CpuPool>
}
impl Service for CacheService {
// These types must match the corresponding protocol types:
type Request = String;
type Response = String;
// For non-streaming protocols, service errors are always io::Error
... | Rust | 0 |
"""
elif key_exchange_method == "pgp_email":
if not user_request['pgp_public_key']:
return templates.TemplateResponse(
"secure_register.html",
{
"request": request,
"error": ... | Python | 1 |
# 終了命令
raise ke
except SizingException as se:
logger.error("VPD読み込み処理が処理できないデータで終了しました。\n\n%s", se.message, decoration=MLogger.DECORATION_BOX)
return se
except Exception as e:
import traceback
logger.critical("VPD読み込み処理が意図せぬエラーで終了しました。\n\n%s... | Python | 1 |
End;
type BtoAVideo<N> = <AtoBVideo<N> as Session>::Dual;
type CtoBClose = <BtoCClose as Session>::Dual;
type CtoAClose = <AtoCClose as Session>::Dual;
type CtoAVideo<N> = <AtoCVideo<N> as Session>::Dual;
/// Stacks
type StackAEnd = RoleEnd;
type StackAEndDual = <StackAEnd as Role>::Dual;
type StackAVideo = RoleC<Ro... | Rust | 0 |
game_protector: Rc<RefCell<GoGameEngine>>) -> Result<WebSocket, JsValue> {
let ws = WebSocket::new("ws://127.0.0.1:8088")?;
{
let socket = ws.clone();
let go_game_protector = go_game_protector.clone();
let onmessage_callback = Closure::wrap(Box::new(move |e: MessageEvent| {
... | Rust | 0 |
u64x2(0x7f2e2b88f8443e09u64.to_be(), 0x8dda7cbbf34b9290u64.to_be()),
u64x2(0xec614b851425758cu64.to_be(), 0x99ff09376ab49ba7u64.to_be()),
u64x2(0x217517873550620bu64.to_be(), 0xacaf6b3cc61bf09bu64.to_be()),
u64x2(0x0ef903333ba96138u64.to_be(), 0x97060a04511dfa9fu64.to_be()),
u64x... | Rust | 0 |
}
l_src_ptr_0 = l_src_ptr_0.offset(l_stride as isize);
j = j.wrapping_add(1)
}
} else {
j = 0 as libc::c_int as OPJ_UINT32;
while j < l_height {
k = 0 as libc::c_int as OPJ_UINT32;
while k < l_width {
let fresh6 = ... | Rust | 0 |
=> self.pause_game(),
State::GamePaused => (),
}
}
fn resumed(&mut self) {
self.gfx.set_window(Some(&self.window));
}
fn mouse_click(&mut self, state: &ElementState) {
match self.state {
State::GameInProgress => match state {
ElementStat... | Rust | 0 |
def distill_loss_cw(self, s_feats, t_feats, temperature=1):
N, C, H, W = s_feats[0].shape
loss_cw = F.kl_div(F.log_softmax(s_feats[0].view(N, C, H * W) /
temperature, dim=2), F.log_softmax(t_feats[0].view(N, C, H * W).
detach() / temperature, dim=2), reduction='sum', log_target=True) * (
... | Python | 1 |
?;
let resp =
if args[4].map_size()? > 0 {
let write_opts = decode_write_options(env, args[2])?;
db.put_cf_opt(cf, key.as_bytes(), val.as_slice(), &write_opts)
} else {
db.put_cf(cf, key.as_bytes(), val.as_slice())
};
handle_error!(env, resp);
... | Rust | 0 |
"""Base TestCase class for testing Exporters"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from tests.base import TestsBase
all_raw_mimetypes = {
"text/x-python",
"text/markdown",
"text/html",
"text/restructuredtext",
"text/late... | Python | 1 |
EncryptedData {
version: u32,
content_info: EncryptedContentInfo,
}
impl BERDecodable for EncryptedData {
fn decode_ber(reader: BERReader) -> ASN1Result<Self> {
reader.read_sequence(|reader| {
let version = reader.next().read_u32()?;
let content_info = read_struct::<Encrypt... | Rust | 0 |
SITIONER_V6_ANCHOR_TOP as libc::c_int as libc::c_uint
{
sx = (rect.x + rect.width) / 2i32;
sy = rect.y
} else if anchor as libc::c_uint ==
ZXDG_POSITIONER_V6_ANCHOR_BOTTOM as libc::c_int as
libc::c_uint {
sx = (rect.x + rect.width) / 2i32;
... | Rust | 0 |
())
}
}
use std::collections::HashSet;
use ocl::{
self,
builders::KernelBuilder,
};
use clay_core::{
Context,
pack::*,
class::*,
shape::*,
object::*,
buffer::InstanceBuffer,
Background,
};
use clay_core::{Push, Scene};
struct TargetData<T: Target> {
object_index: usize,
... | Rust | 0 |
from src.world import WWorld
from unaiverse.networking.node.node import Node
# World
world = WWorld()
# Node hosting world
node = Node(node_name="ChatRoom", hosted=world, hidden=True, clock_delta=1. / 10.,
world_masters_node_names=["Broadcaster"])
# Running node
node.run()
| Python | 1 |
aks below 0 with ``height=(None, 0)`` or use arrays matching
`x` in size to reflect a changing condition for different parts of the
signal.
>>> border = np.sin(np.linspace(0, 3 * np.pi, x.size))
>>> peaks, _ = find_peaks(x, height=(-border, border))
>>> plt.plot(x)
>>> plt.plot(-border, "--", color="gray")
>>> plt.plo... | Python | 1 |
gtypes = []
GetConsoleWindow_Fn.restype = ctypes.wintypes.HANDLE
return GetConsoleWindow_Fn()
def ShowWindow(hWnd, nCmdShow):
ShowWindow_Fn = ctypes.windll.user32.ShowWindow
ShowWindow_Fn.argtypes = [
ctypes.wintypes.HANDLE,
DWORD]
ShowWindow_Fn.restype = ctypes.wintypes.B... | Python | 1 |
def train_epoch(model, train_loader, optimizer, epoch, writer, dryrun=False):
model.train()
total_loss = []
for data, target in tqdm(train_loader):
if torch.cuda.is_available():
data = data.cuda()
target = target.cuda()
optimizer.zero_grad()
prediction = model... | Python | 1 |
// opcode: 144
"bs_put_utf8", // opcode: 145
"bs_utf16_size", // opcode: 146
"bs_put_utf16", // opcode: 147
"bs_put_utf32", // opcode: 148
"on_load", // opcode: 149
"recv_mark", // opcode: 150
"recv_set", // opcode: 151
"gc_bif3", // opcode: 152
"line", // opcode: 153
"put_map_a... | Rust | 0 |
onst ERROR_DS_SCHEMA_NOT_LOADED: ::DWORD = 8414;
pub const ERROR_DS_SCHEMA_ALLOC_FAILED: ::DWORD = 8415;
pub const ERROR_DS_ATT_SCHEMA_REQ_SYNTAX: ::DWORD = 8416;
pub const ERROR_DS_GCVERIFY_ERROR: ::DWORD = 8417;
pub const ERROR_DS_DRA_SCHEMA_MISMATCH: ::DWORD = 8418;
pub const ERROR_DS_CANT_FIND_DSA_OBJ: ::DWORD = 84... | Rust | 0 |
import numpy as np
import re
import matplotlib.pyplot as plt
from model_dsnn_config import decrease_rate,batch_size,learning_rate,weight_decay
from model_dsnn_config import L,r,decrease_over,K
import pickle
from pathlib import Path
import pandas as pd
#this script plots std_loss/abs(avg)
inPath="./compare_layer_neur... | Python | 1 |
from typing import List, Any
def filter_integers(values: List[Any]) -> List[int]:
""" Filter given list of any python values only for integers
>>> filter_integers(['a', 3.14, 5])
[5]
>>> filter_integers([1, 2, 3, 'abc', {}, []])
[1, 2, 3]
"""
return [value for value in values if isinstance... | Python | 1 |
import numpy as np
import pybullet as p
from .agent import Agent
class Robot(Agent):
def __init__(self, controllable_joints, right_arm_joint_indices, right_end_effector, right_gripper_indices):
self.controllable_joints = controllable_joints
self.right_arm_joint_indices = right_arm_joint_indices # ... | Python | 1 |
s played. It may have one of the following values:
///
/// * `none`: Indicates that the video should not be preloaded.
/// * `metadata`: Indicates that only video metadata (e.g. length) is fetched.
/// * `auto`: Indicates that the whole video file can be downloaded, even if the user is n... | Rust | 0 |
9!");
assert_eq!("3628800", FACTORIAL[10].to_string(), "10!");
assert_eq!("39916800", FACTORIAL[11].to_string(), "11!");
assert_eq!("479001600", FACTORIAL[12].to_string(), "12!");
assert_eq!("6227020800", FACTORIAL[13].to_string(), "13!");
assert_eq!("87178291200", FACTORIAL[14].... | Rust | 0 |
# Copyright (c) Alibaba, Inc. and its affiliates.
import os
import gradio as gr
from swift.ui.llm_train.runtime import Runtime
from swift.utils import get_logger
logger = get_logger()
class RLHFRuntime(Runtime):
group = 'llm_rlhf'
locale_dict = {
'runtime_tab': {
'label': {
... | Python | 1 |
n\nFor information about avaliable fields see [invalidate](invalidate) module"]
pub type INVALIDATE = crate::Reg<u32, _INVALIDATE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INVALIDATE;
#[doc = "`write(|w| ..)` method takes [invalidate::W](invalidate::W) writer structure"]
impl crate::Writable for INVALIDATE {}... | Rust | 0 |
:
print("FastAPI应用不可用,生成基础文档结构...")
# 生成基础文档结构
basic_modules = [
"base",
"users",
"role",
"menu",
"files",
"dept",
"api",
"auditlog",
]
for module in basic_modules:
file_... | Python | 1 |
T: NativeArithmetics + Add<Output = T>,
{
let rhs = *rhs;
unary(lhs, |a| a + rhs, lhs.data_type().clone())
}
/// Wrapping addition of a scalar T to a [`PrimitiveArray`] of type T.
/// It do nothing if the result overflows.
///
/// # Examples
/// ```
/// use arrow2::compute::arithmetics::basic::wrapping_add_sca... | Rust | 0 |
# src/genomic_mating/relationship_matrix/__init__.py
"""Module for calculating relationship matrices."""
from .grm import calculate_grm_vanraden1
from .pedigree import calculate_a_matrix
__all__ = ["calculate_grm_vanraden1", "calculate_a_matrix"]
| Python | 1 |
///
/// `386+`
///
/// `16/32/64-bit`
Retfd = 418,
/// `RETF`
///
/// `o64 CB`
///
/// `X64`
///
/// `64-bit`
Retfq = 419,
/// `INT3`
///
/// `CC`
///
/// `8086+`
///
/// `16/32/64-bit`
Int3 = 420,
/// `INT imm8`
///
/// `CD ib`
///
/// `8086+`
///
/// `16/32/64-bit`
Int_imm8 = 421,
/// `... | Rust | 0 |
Handle shutdown signals"""
logger.info(f"Received signal {signum}, shutting down...")
sys.exit(0)
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description="APB Farm - Arch Package Builder Farm")
parser.add_argument("--host", default=DEFAULT_HOST, help="Host to bind to")
... | Python | 1 |
ass(AutoNitrogenFiller,classtype)
from cfegconditioner import ColdFegFlasher
noderegistry.registerNodeClass(ColdFegFlasher,classtype)
from phaseplatealigner import PhasePlateAligner
noderegistry.registerNodeClass(PhasePlateAligner,classtype)
from screencurrentlogger import ScreenCurrentLogger
noderegistry.registerNo... | Python | 1 |
# MenuTitle: Set Y position of components in selected glyphs
import vanilla
def process_glyph(glyph, value, process_all_layers, selected_layers):
if process_all_layers:
layers = glyph.layers
else:
layers = [layer for layer in glyph.layers if layer.layerId in selected_layers]
for layer ... | Python | 1 |
_lazy");
self.state.absorb_block(buf);
}
}
}
}
macro_rules! sha3_impl {
($state:ident, $output_size:ident, $rate:ident, $padding:ty) => {
impl_state!($state, $rate, $padding);
impl BlockInput for $state {
type BlockSize = $rate;
}
... | Rust | 0 |
rn a; } // Vertex region early out
// Compute parametric position u for projection P’ of P on BC,
// P’ = B + u*BC, u = unom/(unom+udenom)
let unom = (p - b).dot(bc);
let udenom = (p - c).dot(b - c);
if sdenom <= 0.0 && unom <= 0.0 { return b; } // Vertex region early out
if tdenom <= 0.0 ... | Rust | 0 |
!("{}", ai_shape)).into())
}
}
}
}
// Make sure all arguments are up to that shape, if not broadcast them accordingly
for a in args.iter_mut() {
if shape != graph.get_node(*a).unwrap().shape {
let br: Vec<Option<usize>> ... | Rust | 0 |
ecimal::Decimal>,
/// flag indicating if the apevent covers a raise60sec AP
pub raise60secapflag: Option<rust_decimal::Decimal>,
/// flag indicating if the apevent covers a raise5min AP
pub raise5minapflag: Option<rust_decimal::Decimal>,
/// flag indicating if the apevent covers a raisereg AP
pu... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.