text string | label_name string | labels int64 |
|---|---|---|
int(db)
system_for_NA = """Ты - преподаватель, эксперт по теме 'Графы, алгоритмы и структуры данных.'
Твоя задача - ответить студенту на вопрос только на основе представленных тебе документов, не добавляя ничего от себя."""
def answer_neuro_assist(system_for_NA, topic, search_index):
docs = s... | Python | 1 |
size += size_of::<u64>();
size += size_of::<u32>();
size
}
}
impl ctx::TryFromCtx<'_, Endian> for ImmediateDesc {
type Error = Error;
fn try_from_ctx(source: &[u8], endian: Endian) -> Result<(Self, usize)> {
let offset = &mut 0;
let value = source.gread_with::<u64>... | Rust | 0 |
kdf2,
mhf,
},
#[cfg(feature = "blake3")]
(Ake::X25519, Ristretto255, Blake3, mhf @ Argon2(_)) => Self {
cipher_suite: X25519Ristretto255Blake3Argon2,
mhf,
},
#[cfg(all(feature = "blake3", feature = "pbkdf2"))]
(Ake::X25519, Ristretto255, Blake3, mhf @ Pbkdf2(_)) => Self {
cipher_suite:... | Rust | 0 |
f"Tab {tab_number if tab_number else 'Single'} => {page_current_url}: File name should not be empty"
)
except Exception as e:
print(f"Error processing Tab {tab_number if tab_number else 'Single'}: {e}")
logging.error(f"Error processing Tab {tab_number if tab_number else 'Single'}: ... | Python | 1 |
self.z3_ast, &mut tmp) {
Some(tmp)
} else {
context::check_error(self.ctx);
None
}
}
}
pub fn as_u64(&self) -> Option<u64> {
unsafe {
let guard = Z3_MUTEX.lock().unwrap();
let mut tmp ... | Rust | 0 |
int,
pub Height: c_int,
/// `ovrTextureFlags`
pub MiscFlags: c_uint,
}
#[doc(hidden)]
pub enum ovrTextureSwapChainData {}
pub type ovrTextureSwapChain = *mut ovrTextureSwapChainData;
#[doc(hidden)]
pub enum ovrMirrorTextureData {}
pub type ovrMirrorTexture = *mut ovrMirrorTextureData;
//-------------------... | Rust | 0 |
Type::NEW_LINE {
v.push(t.clone());
}
}
return v;
}
fn join_string_literals(tokens: Vec<Token>) -> Vec<Token> {
let mut v: Vec<Token> = Vec::new();
let ts = tokens;
for t in ts.iter() {
if v.len() > 0 && v.last().unwrap().ty == TokenType::STR && t.ty == TokenType::STR {... | Rust | 0 |
location in screen coordinates
:type location: typing.Optional[typing.Any]
'''
pass
def view_zoom_ratio(
override_context: typing.Optional[
typing.Union[typing.Dict, 'bpy.types.Context']] = None,
execution_context: typing.Optional[typing.Union[str, int]] = None,
undo:... | Python | 1 |
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class IrAttachment(models.Model):
_inherit = "ir.attachment"
# Add index to res_model because filtering on it is a common use case
res_model = fields.Ch... | Python | 1 |
<T> FusionRV<T> for Void where Void: FusionRV2<T> {
#[inline] default fn tyck_info_rv() -> TypeCheckInfo {
<Void as FusionRV2<T>>::tyck_info_rv2()
}
#[inline] default fn tyck_rv(tyck_info: &TypeCheckInfo) -> bool {
<Void as FusionRV2<T>>::tyck_rv2(tyck_info)
}
#[inline] default fn ... | Rust | 0 |
pos += 1,
0x0D => {
if data.len() >= pos + 3 && data[pos + 1] == 0x0A && (data[pos + 2] == 0x20 || data[pos + 2] == 0x09) {
pos += 3;
} else {
break;
}
},
_ => break,
}
}
pos
}
... | Rust | 0 |
for Box<F>
where
F: ActorFuture<A> + Unpin + ?Sized,
A: Actor,
{
type Output = F::Output;
fn poll(
mut self: Pin<&mut Self>,
srv: &mut A,
ctx: &mut A::Context,
task: &mut Context<'_>,
) -> Poll<Self::Output> {
Pin::new(&mut **self.as_mut()).poll(srv, ctx, ta... | Rust | 0 |
impl<'a> AsRef<ir::Contract> for Storage<'_> {
fn as_ref(&self) -> &ir::Contract {
self.contract
}
}
impl GenerateCode for Storage<'_> {
fn generate_code(&self) -> TokenStream2 {
let storage_span = self.contract.module().storage().span();
let access_env_impls = self.generate_acces... | Rust | 0 |
_buffer() {
let mut allocated_mem: Vec<f32> = vec![Default::default(); utils::get_input_buffer_size()];
let model_data = menoh::ModelData::new(constant::MODEL_PATH).unwrap();
let model = utils::create_model_mock(&model_data, &mut allocated_mem);
assert_matches!(
model
.get_internal_b... | Rust | 0 |
BLOCKS: usize = ROWS * COLS;
}<filename>src/lib.rs
//! A library to interface with Qemu. For more information about Qemu see
//! [qemu](http://www.qemu.org)
//!
extern crate bytes;
#[macro_use]
extern crate json;
#[macro_use]
extern crate log;
extern crate mio;
extern crate rustc_serialize;
extern crate simple_logger... | Rust | 0 |
[0,0,0], [0,3,3]], dtype=np.uint8), \
np.array([[0,2,3], [0,1,3], [0,0,0], [0,3,3], [3,3,3]], dtype=np.uint8) ]
>>> vxl_mask_list = [np.array([1,0,1,1,1], dtype=np.bool), \
np.array([1,1,0,1,1], dtype=np.bool), \
np.array([0,0,0,0], dtype=np.... | Python | 1 |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Pos... | Python | 1 |
Self::new()
}
}
impl<T> ::std::clone::Clone for __BindgenUnionField<T> {
#[inline]
fn clone(&self) -> Self {
Self::new()
}
}
impl<T> ::std::marker::Copy for __BindgenUnionField<T> {}
impl<T> ::std::fmt::Debug for __BindgenUnionField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -... | Rust | 0 |
s) if news_lines else "-"
sys = (
"You are a stock analyst. Based on the provided technical metrics and headlines, output STRICT JSON only.\n\n"
"Schema:\n"
"{\n"
' "date": "YYYY-MM-DD",\n'
' "tickers": [\n'
" {\n"
' "ticker": "TSLA",\n'
' ... | Python | 1 |
f not self.current_frequencies:
self.current_frequencies = self.get_initial_frequencies()
return self.current_frequencies.copy()
def get_filtered_frequencies(self, linucb_model=None) -> List[int]:
"""获取经过修剪过滤的当前频率列表"""
current_freqs = self.get_current_frequencies()
... | Python | 1 |
bool {
self.0 != UNKNOWN
}
pub fn is_true(&self) -> bool {
self.0 == TRUE
}
pub fn new_unknown() -> Self {
LookupEntry(UNKNOWN)
}
pub fn from_bool(b: bool) -> Self {
LookupEntry(if b { TRUE } else { FALSE })
}
}
fn solve_1(data: &InputData) -> usize {
c... | Rust | 0 |
fn half() -> NUM;
fn one() -> NUM;
fn two() -> NUM;
fn to_radians(deg: NUM) -> NUM;
fn to_degrees(rad: NUM) -> NUM;
fn neg(a: NUM) -> NUM;
fn cos(a: NUM) -> NUM;
fn sin(a: NUM) -> NUM;
fn tan(a: NUM) -> NUM;
}
#[macro_export]
macro_rules! charmath_numeric {
($NUM:ident, $CLOSEST... | Rust | 0 |
u32 = 99; // PRICE
const FIELD_EXDESTINATION : u32 = 100; // EXCHANGE
const FIELD_CXLREJREASON : u32 = 102; // INT
#[derive(PartialEq,Debug,Serialize,Deserialize,Clone,Copy)]
pub enum FieldCxlRejReasonEnum {
TooLateToCancel, // = "0"
UnknownOrder, // = "1"
BrokerOption, // = "2"
OrderAlreadyInPen... | Rust | 0 |
bout ODBC
//!
//! ODBC is an open standard which allows you to connect to various data sources. Mostly these data
//! sources are databases, but ODBC drivers are also available for various file types like Excel or
//! CSV.
//!
//! Your application does not link against a driver, but will link against an ODBC driver man... | Rust | 0 |
from pyrigi._utils.union_find import UnionFind
def test_union_find_initialization():
uf = UnionFind()
assert uf._data == {}
def test_union_find_find_new_element():
uf = UnionFind()
root_a = uf.find("a")
assert root_a == "a"
assert uf._data == {"a": "a"}
def test_union_find_join_different_s... | Python | 1 |
(
"Choose a path to save files (Path must be absolute, folder must exist):",
)
.with_default("~/")
.prompt()
.unwrap();
// append slash
if !(path.ends_with("/") || path.ends_with("\\")) {
path.push_str("/");
}
// check if path exi... | Rust | 0 |
category=Anomaly.ERROR_500,
level=Anomaly.HIGH_LEVEL,
request=mutated_request,
info=anom_msg,
parameter=parameter
)
self.log_orange... | Python | 1 |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.0.0
import enum
import winrt.system
from winrt._winrt_windows_media import (
MediaTimeRange,
AudioBuffer,
AudioFrame,
AutoRepeatModeChangeRequestedEventArgs,
ImageDisplayProperties,
MediaControl,
MediaExtensionMana... | Python | 1 |
pc {
/// Alias doesn't use the namespace so not duplicated.
#[method(name = "getTemp", aliases = ["getTemp"])]
async fn async_method(&self, param_a: u8, param_b: String) -> RpcResult<u16>;
#[subscription(name = "getFood", item = String, aliases = ["getFood"], unsubscribe_aliases = ["unsubscribegetFood"])]
fn sub(... | Rust | 0 |
mean = np.mean(x, 0)
x_std = np.std(x, 0)
W = pca.components_
x_mu = W @ pca.mean_ # pca.mean_ is y_mean
y_hat = x @ W + pca.mean_
y_err = y_hat - y
y_rel_err = y_err / np.maximum(0.5 * (np.abs(y) + np.abs(y_hat)), np.finfo('float').eps)
plt.figure(figsize=(15, 7))
plt.subplot(2, 3, ... | Python | 1 |
ers/demos.rs
use crate::models::models::*;
use anyhow::Result;
use sqlx::postgres::PgRow;
use sqlx::{PgPool, Row};
impl Demos {
/// Gets Demo information for a given demo_id
pub async fn get_demo(pool: &PgPool, demo_id: i64) -> Result<Option<Demos>> {
let res = sqlx::query_as::<_, Demos>(r#"SELECT * FR... | Rust | 0 |
or::Error;
/// Raw codec.
pub struct RawCodec;
impl Codec for RawCodec {
const CODE: IpldCodec = IpldCodec::Raw;
type Error = RawError;
}
/// Error returned by the `RawCodec`.
#[derive(Debug, Error)]
pub enum RawError {
/// Io error.
#[error("{0}")]
Io(#[from] std::io::Error),
/// Type error... | Rust | 0 |
ys)]
pub fn sav_p_pul(&self) -> SAV_P_PUL_R {
SAV_P_PUL_R::new((self.bits & 0x0fff) as u16)
}
}
<reponame>TimLikesTacos/Blackjack
//! The standard deck has 52 cards in each. One of each demonination and suit.
//! However, decks can be made from multiple decks, containing identical cards.
use crate::... | Rust | 0 |
"description": "Пользователь успешно создан",
"content": {
"application/json": {
"example": {
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
... | Python | 1 |
.-]*",
// Other license-specific (APACHE-2.0.txt, etc.)
"AGPL-*[0-9]*",
"APACHE-*[0-9]*",
"BSD-*[0-9]*",
"CC-BY-*",
"GFDL-*[0-9]*",
"GNU-*[0-9]*",
"GPL-*[0-9]*",
"LGPL-*[0-9]*",
"MIT-*[0-9]*",
"MPL-*[0-9]*",
"OFL-*[0-9]*",
... | Rust | 0 |
mod fill;
pub mod path;
pub mod polynomial;
pub mod renderer;
pub mod safe_float;
mod stroke;
#[cfg(feature = "text")]
pub mod text;
pub mod utils;
mod vertex;
use log::{error};
pub fn encode(data: &shared::ClientCommand) -> Vec<u8> {
let binary = bincode::serialize::<shared::ClientCommand>(data);
if let Ok(b... | Rust | 0 |
o_val(structure: &Structure) -> i64 {
match structure {
Structure::Road(road) => (HIGHER_NUM
+ ((1. - road.hits() as f64 / road.hits_max() as f64) * 100.))
.round() as i64,
Structure::Container(container) => (HIGHER_NUM
+ ((1. - container.hits() as f64 / container... | Rust | 0 |
len()),
};
let mut direction = Down;
let mut letters = String::new();
let mut steps = 1;
while let Ok(pos) = position.go(direction) {
steps += 1;
position.current = pos;
match map[pos.0][pos.1] {
'|' | '-' => {}
' ' => panic!(format!(
"... | Rust | 0 |
N<u8> { $($field),+ });
impl_scalar_ops!($VectorN<u16> { $($field),+ });
impl_scalar_ops!($VectorN<u32> { $($field),+ });
impl_scalar_ops!($VectorN<u64> { $($field),+ });
impl_scalar_ops!($VectorN<isize> { $($field),+ });
impl_scalar_ops!($VectorN<i8> { $($field),+ });
im... | Rust | 0 |
transmute::<*mut usize, *mut c_void>(data));
} else {
alloc_util::free_stdlib(data, size);
}
}
#[cfg(all(feature="std", not(feature="pass-through-ffi-panics")))]
pub fn catch_panic<F:FnOnce()->i32+panic::UnwindSafe>(f: F) -> thread::Result<i32> {
panic::catch_unwind(f)
}
#[cfg(all(feature="std",... | Rust | 0 |
# -*- coding: utf-8 -*-
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
module_misl_requisition_sale_order = fields.Boolean("Create Requisition from Sales Order")
module_misl_requisition_mo = fields.Boolean("Use Requisition for Manufa... | Python | 1 |
l=[{'año': 2000, 'metros': 100, 'habitaciones': 3, 'garaje': True, 'zona': 'A'},
{'año': 2012, 'metros': 60, 'habitaciones': 2, 'garaje': True, 'zona': 'B'},
{'año': 1980, 'metros': 120, 'habitaciones': 4, 'garaje': False, 'zona': 'A'},
{'año': 2005, 'metros': 75, 'habitaciones': 3, 'garaje': True, 'zona': 'B'},
{'año'... | Python | 1 |
trigger log compacting, default 1MB.
/// The struct of Key-Value DataBase implemented with
/// [HashMap](https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html).
///
/// The key can be up to 256B and the value can be up to 4KB.
#[derive(Clone)]
pub struct KvStore {
index: Arc<Mutex<HashMap<String,... | Rust | 0 |
}
}
pub fn initial_delay(mut self, initial_delay: Duration) -> Self {
self.initial_delay = Some(initial_delay);
self
}
pub fn max_count(mut self, max_count: u32) -> Self {
self.max_count = Some(max_count);
self
}
pub fn random_factor(mut self, random_factor: f32)... | Rust | 0 |
ESULT,
fn GetFolder(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT,
fn GetCurrentSelection(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT,
fn SetFileName(&mut self, pszName: ::LPCWSTR) -> ::HRESULT,
fn GetFileName(&mut self, pszName: *mut ::LPWSTR) -> ::HRESULT,
fn SetTitle(&mut self, pszT... | Rust | 0 |
Cargo command invocation",
)
.value_name("id"),
)
.arg_package("Package to display a report for"),
)
}
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
match args.subcommand() {
Some(("future-incompatibilitie... | Rust | 0 |
85.2809854969, 85.2809858322}},
{"8qjtgd1q", Box{34.7727584839, 34.7729301453, -160.860099792, -160.85975647}},
{"60dppvw", Box{-40.9268188477, -40.9254455566, -86.838684082, -86.837310791}},
{"tygxz83s2", Box{39.3331575394, 39.3332004547, 84.0035247803, 84.0035676956}},
{"e0qwrc", Box{2.51037597656, 2.51586914062... | Rust | 0 |
n main() {
pretty_env_logger::init();
let args = std::env::args().collect::<Vec<String>>();
if args.len() != 2 {
eprintln!("Usage: vm <binary file>");
return;
}
#[rustfmt::skip]
let mut instrs = Vec::new();
let mut file = std::fs::File::open(&args[1]).unwrap();
file.rea... | Rust | 0 |
import requests
import ipaddress
import logging
import subprocess
import json
# Logging einrichten
def setup_logging():
logging.basicConfig(
filename="blocklist.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
# Blocklist herunterladen
def download_blockl... | Python | 1 |
Ok(TypedefClause::CreatedBy(Box::new(person)))
}
Rule::CreationDateTag => {
let date = IsoDateTime::from_pair_unchecked(inner.next().unwrap())?;
Ok(TypedefClause::CreationDate(Box::new(date)))
}
Rule::ExpandAssertionToTag => {
... | Rust | 0 |
import numpy as np
from detectron2.utils.visualizer import Visualizer
class TextVisualizer(Visualizer):
def draw_instance_predictions(self, predictions):
beziers = predictions.beziers.numpy()
scores = predictions.scores.tolist()
recs = predictions.recs
self.overlay_instances(bezi... | Python | 1 |
/ "coordinates": [
/// 2.0,
/// 3.1
/// ]
/// },
/// "properties": {
/// "foo": 2
/// },
/// "when": {
/// "start": "1970-01-01T00:00:00+00:00",
/// "end": "1970-01-01T00:00:00.001+00:00",
/// "type": "Interval"
/// }
/// ... | Rust | 0 |
}
}
fn main() {
let a = A { child: B };
let mut v = V;
a.accept(&mut v);
}
<reponame>eltorocorp/h3ron<gh_stars>0
use pyo3::{prelude::*, wrap_pyfunction, PyNativeType, Python};
use crate::raster::init_raster_submodule;
use crate::vector::init_vector_submodule;
use crate::{collections::H3CompactedVec, pol... | Rust | 0 |
as i32)), // salt_len
Regular(Instruction::Call(0)),
Regular(Instruction::I32Eqz),
Regular(Instruction::If(BlockType::NoResult)),
Regular(Instruction::Nop),
Regular(Instruction::Else),
Regular(Instruction::Unreachable),
Regular(Instruction::End),
])),
.. Default::default()
});
let... | Rust | 0 |
)))?,
))
}
}
impl Serialize for ProposerPriority {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.to_string().serialize(serializer)
}
}
/// Updates to the validator set
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Update {
/// Valida... | Rust | 0 |
import requests
from pystarport import ports
from .utils import (
derive_new_account,
send_transaction,
sign_transaction,
wait_for_new_blocks,
)
def test_trace_blk(evmos_cluster):
w3 = evmos_cluster.w3
cli = evmos_cluster.cosmos_cli()
acc = derive_new_account(3)
sender = acc.address
... | Python | 1 |
#Test Name: SquareShelfStressHOHigherOrder
from model import *
from socket import gethostname
from triangle import *
from setmask import *
from parameterize import *
from setflowequation import *
from solve import *
from ContourToMesh import *
md = triangle(model(), '../Exp/Square.exp', 150000.)
md = setmask(md, 'all... | Python | 1 |
}
pub fn create_solid_fill<Conn>(conn: &Conn, picture: Picture, color: Color) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = CreateSolidFillRequest {
picture,
color,
};
request0.send(conn)
}
/// Opcode for the CreateLinearGradie... | Rust | 0 |
(0, 255, 255)) # Yellow color
for i, landmark in enumerate(user_hand_landmarks):
try:
# Find target x, y for the user's hand landmarks from the CSV
target_x = float(target_data[headers.index(f"{time_seconds:02d}_{fram... | Python | 1 |
# Generated by Django 2.2.4 on 2019-12-04 14:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quests', '0022_auto_20191115_2215'),
]
operations = [
migrations.AlterField(
model_name='quest',
name='background',
... | Python | 1 |
n = int(input('enter a number: '))
for i in range(n):
if i == 0:
print('*'*(n*2-1))
elif i == n-1:
print(' '*(n-1) + '*')
else:
print(' '*i + '*' + ' '*(2*(n-1-i)-1) + '*') | Python | 1 |
import telebot
# Вставьте свой API
bot = telebot.TeleBot("")
@bot.message_handler(content_types=['text'])
def handle_message(message):
"""
Обрабатывает текстовое сообщение от пользователя.
Создает опрос из сообщения, если количество строк соответствует требованиям.
"""
# Получаем количество перево... | Python | 1 |
bedding[-5:], dim=0, out=None)
hyp_embedding_max, _ = torch.max(hyp_embedding[-5:], dim=0, out=None)
ref_embedding_min, _ = torch.min(ref_embedding[-5:], dim=0, out=None)
hyp_embedding_min, _ = torch.min(hyp_embedding[-5:], dim=0, out=None)
ref_embedding_avg = ref_embedding[-5:].mean(0... | Python | 1 |
lf):
"""Crea los widgets de la aplicación principal"""
frame = ctk.CTkFrame(self)
frame.pack(expand=True, fill="both", padx=20, pady=20)
titulo = ctk.CTkLabel(frame, text="Aplicación Principal",
font=ctk.CTkFont(size=18, weight="bold"))
titu... | Python | 1 |
te(f"R{rel_id_counter:06d}\t20241201\t1\t900000000\t"
f"{relationship['source_id']}\t{relationship['target_id']}\t0\t"
f"{relationship['relationship_type']}\t900000000\t900000000\n")
rel_id_counter += 1
print(f"RF2格式文件已导出到: {output_dir}")
... | Python | 1 |
#!/usr/bin/env python3
"""
Test script to verify the Gemini provider is working with real API calls.
"""
import os
import sys
from pathlib import Path
# Add the backend directory to the path
sys.path.append(str(Path(__file__).parent / 'backend'))
from services.llm_providers.gemini_provider import gemini_text_respons... | Python | 1 |
okens(tokens);
tokens.append(",");
}
tokens.append("]");
}
}
impl<T: ToTokens> ToTokens for Vec<T> {
fn to_tokens(&self, tokens: &mut Tokens) {
self[..].to_tokens(tokens)
}
}
macro_rules! array_impls {
($($N:expr)+) => {
$(
impl<T: ToTokens> ToTo... | Rust | 0 |
ike or None, default None
Dates to exclude from the set of valid business days, passed to
``numpy.busdaycalendar``, only used when custom frequency strings
are passed.
inclusive : {"both", "neither", "left", "right"}, default "both"
Include boundaries; Whether to set each bound as cl... | Python | 1 |
ctStatusCode: int
"""
self._Switch = None
self._RedirectType = None
self._RedirectStatusCode = None
@property
def Switch(self):
return self._Switch
@Switch.setter
def Switch(self, Switch):
self._Switch = Switch
@property
def RedirectType(self):
... | Python | 1 |
),
link_name = "rustsecp256k1_v0_3_1_xonly_pubkey_tweak_add"
)]
pub fn secp256k1_xonly_pubkey_tweak_add(
cx: *const Context,
output_pubkey: *mut PublicKey,
internal_pubkey: *const XOnlyPublicKey,
tweak32: *const c_uchar,
) -> c_int;
#[cfg_attr(
not(rust_s... | Rust | 0 |
-> Option<LocalHandle<'a, T>> {
if let Some(object_ptr) = self.get_object_ptr() {
if object_ptr.is_type(T::TYPE_ID) {
let ptr = TraceableObject::try_downcast::<T>(object_ptr);
if ptr.is_some() {
return Some(LocalHandle {
sc... | Rust | 0 |
self, message_data: MessageData<S::MessageFee>) -> MessageNonce {
let mut data = self.storage.data();
let nonce = data.latest_generated_nonce + 1;
data.latest_generated_nonce = nonce;
self.storage.save_message(nonce, message_data);
self.storage.set_data(data);
nonce
}
/// Confirm messages delivery.
/... | Rust | 0 |
Ok(())
}
<filename>src/gpio.rs
#![allow(dead_code)]
extern crate lpc1347;
use lpc1347::Peripherals;
use lpc1347::Interrupt::{PIN_INT0, PIN_INT1, PIN_INT2, PIN_INT3, PIN_INT4, PIN_INT5, PIN_INT6,
PIN_INT7};
/// Writes to a register using value and bitpos
macro_rules! write_reg {
($fie... | Rust | 0 |
""" This module retrieves the system response in various languages if the user
triggers content filtering.
"""
import os
from azure.ai.translation.text import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
from dotenv import load_dotenv
from util.language import translate_text
CONTENT_F... | Python | 1 |
rofile error."""
file_name = "Config rounding.zip"
row_mtf_50 = 0.96
col_mtf_50 = 0.96
phantom_roll = 0
slice_thickness = 4.2
slice1_shift = 1.5
slice11_shift = 1.95
psg = 0.3
class ACRMRIUnfilled(ACRMRMixin, TestCase):
# a phantom with significant air bubbles and also a rotation
... | Python | 1 |
_round_arithmetic(z, sum, k[0], k[1]));
z = z.wrapping_add(tc_tea_single_round_arithmetic(y, sum, k[2], k[3]));
}
block.write_u32_be(0, y);
block.write_u32_be(4, z);
}
<reponame>PLSysSec/rlbox_wasmtime_sandbox<filename>src/memory.rs
use crate::types::WasmtimeSandboxInstance;
use std::ffi::c_void;
... | Rust | 0 |
ialize_bytes["&[u8]", Ok, $err_func](v: &[u8])}
};
(none $err_func:ident) => {
return_error_method!{serialize_none["none", Ok, $err_func]()}
};
(some $err_func:ident) => {
return_error_method_with_generics!{serialize_some["some", Ok, $err_func](value: &T)}
};
(unit $err_func:iden... | Rust | 0 |
;
use rand::Rng;
use crate::note::note::{LeafHasher, NoteGenerator, OpStatusCode};
pub struct PoseidonNoteGeneratorCurve25519 {
pub hasher: Poseidon,
}
impl LeafHasher for PoseidonNoteGeneratorCurve25519 {
type HasherOptions = ();
const SECRET_LENGTH: usize = 128;
fn hash(&self, input: &[u8], _: Self::HasherOp... | Rust | 0 |
TABLE_SIZE) {
if self.table[i] != NULL_ENTRY {
print!("{:?}\n", self.table[i]);
}
}
}
}
#[derive(Eq, PartialEq, Copy)]
pub struct Bound(u8);
pub const ALPHA_BOUND : Bound = Bound(0);
pub const BETA_BOUND : Bound = Bound(1);
pub const EXACT_BOUND : Bound = Bound(2);
... | Rust | 0 |
rime_bans_and_style(power: str, theme: str) -> str:
fam = _infer_family_soft(power)
# start with a real list BEFORE extending it
bans: List[str] = []
# also ban the literal power words so the crimes don't repeat it
name_only = (power or "").split("—")[0].split(":")[0].strip()
power_words = re.... | Python | 1 |
recv = stream.try_clone().expect("spawn");
// 受信スレッド
std::thread::spawn(move || {
Server::reciever_worker(
reader,
reciever_ch,
recviever_to_server_tx,
(stream_recv, sockaddr),
);
... | Rust | 0 |
else:
st.warning("⚠️ No se pudieron obtener los datos históricos para realizar la predicción.")
def obtener_precio_dolar(tipo):
"""Obtiene el precio del dólar desde la API con manejo de errores y caché."""
try:
conn = http.client.HTTPSConnection("dolarapi.com")
conn.request("GET", f"/v... | Python | 1 |
import typer
from typing import Optional, List
from phi.assistant import Assistant, AssistantMemory
from phi.memory.db.postgres import PgMemoryDb
from phi.storage.assistant.postgres import PgAssistantStorage
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.pgvector import PgVector2
cli_app = typer.T... | Python | 1 |
"""
"""
from .host import HostConverter, Host
from .network import Network, CIDR, IPAddress, NetworkConverter
from .router import Router, RouterConverter
from .deployment import Deployment
| Python | 1 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import argparse
import yaml
from azureml.core import Workspace
from azureml.core.compute import AmlCompute, ComputeTarget
parser = argparse.ArgumentParser("Get compute")
parser.add_argument("-f", type=str, help="A... | Python | 1 |
# Sometimes you’ll want to store multiple dictionaries in a list, or a list of items as a value in a dictionary.
# This is called nesting. You can nest dictionaries inside a list, a list of items inside a dictionary,
# or even a dictionary inside another dictionary.
# Nesting is a powerful feature, as the following ... | Python | 1 |
# Imports.
from .utils import load_data, generate_color_map, update_plot_layout, get_plotly_colors, display_palette_as_gradient
from .donut_plot import donut_plot
from .heatmap_plot import heatmap_plot
from .scatter_plot import scatter_plot
from .treemap_plot import treemap_plot
__all__ = ["load_data",
"gen... | Python | 1 |
Self {
endianness: std::marker::PhantomData,
}
}
}
impl<'a> parcel::Parser<'a, &'a [u8], Machine> for MachineParser<LittleEndian> {
fn parse(&self, input: &'a [u8]) -> parcel::ParseResult<'a, &'a [u8], Machine> {
use std::convert::TryInto;
let preparse_input = input;
... | Rust | 0 |
return (table[(table[wc>>8] as usize)*32+((wc&255)>>3)]>>(wc&7))&1;
}
if wc < 0x2fffe {
return 1;
}
return 0;
}
const table: [c_uchar; 3904] = [
18,17,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,17,34,35,36,17,37,38,39,40,
41,42,43,44,17,45,46,47,16,16,48,16,16,16,16,16,16,16,49,50,... | Rust | 0 |
uery we are trying to run *before* we panic.
if config.verbosity >= 2 {
print_record(config, &record);
}
let outcome = state
.run_record(&record)
.await
.map_err(|err| format!("In {}:\n{}", source, err))
.unwrap();
// Print fa... | Rust | 0 |
# TODO: remove, let the user import it if they really want it
from .fi import fi_business_id, fi_ssn # noqa
__all__ = ('fi_business_id', 'fi_ssn')
| Python | 1 |
param[in] response HTTP 响应实例
/// @param[in] ip_addr 服务器 IP 地址
#[no_mangle]
pub extern "C" fn qiniu_ng_http_response_set_server_ip_v6(response: qiniu_ng_http_response_t, ip_addr: in6_addr) {
let response: &mut Response = response.into();
*response.server_ip_mut() = Some(IpAddr::V6(from_in6_addr_to_ipv6_addr(ip_a... | Rust | 0 |
mut_ptr: *mut msghdr_mut, flags_c: c_int) -> Result<isize> {
info!(
"recvmsg: fd: {}, msg: {:?}, flags: 0x{:x}",
fd, msg_mut_ptr, flags_c
);
let current_ref = process::get_current();
let mut proc = current_ref.lock().unwrap();
let file_ref = proc.get_files().lock().unwrap().get(fd as... | Rust | 0 |
apoints.
let real_x = 1000u32;
let real_y = data_points * 60u32;
evcxr_figure((real_x, real_y), |root| {
let duration_percent = |p: usize| ((max_duration as f64) * (p as f64) / 100f64) as u32;
let bar = |y: u32, w: u32, style| Rectangle::new([(0, y + 1), (w, y + 8)], style);
let labe... | Rust | 0 |
2015-08-05 0.083
2015-09-16 0.033
2015-10-28 0.060
2015-12-09 0.000
2016-01-20 0.202
2016-03-02 0.280
2016-04-13 0.016
2016-05-25 0.060
... | Python | 1 |
e;
use ibc_relayer::foreign_client::ForeignClient;
use crate::types::id::{TaggedChainId, TaggedClientIdRef};
use crate::types::tagged::*;
/**
An extension trait for providing methods for getting tagged identifiers
out of a [`ForeignClient`].
*/
pub trait TaggedForeignClientExt<DstChain: ChainHandle, SrcChain: C... | Rust | 0 |
while True:
print('Menu: ')
print('Menu: ') | Python | 1 |
MergedGraph { nodes, edges })
}
}
impl From<MergedGraph> for MergedGraphProto {
fn from(merged_graph: MergedGraph) -> Self {
let mut nodes = HashMap::with_capacity(merged_graph.nodes.len());
for (key, merged_node) in merged_graph.nodes {
nodes.insert(key, MergedNodeProto::from(merge... | Rust | 0 |
::<OroManifest>(&data[..]).to_internal()?)
}
pub fn update_file<F: AsRef<Path>>(&self, file: F) -> Result<()> {
let file = file.as_ref();
let manifest = serde_json::to_value(&self).to_internal()?;
let data = fs::read(file).to_internal()?;
let mut pkg_json = serde_json::from_slic... | Rust | 0 |
ining an empty list
tasks = []
# defining frames using the tk.Frame() widget
header_frame = tk.Frame(guiWindow, bg="#FAEBD7")
functions_frame = tk.Frame(guiWindow, bg="#FAEBD7")
listbox_frame = tk.Frame(guiWindow, bg="#FAEBD7")
# using the pack() method to place the frames in the application
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.