text string | label_name string | labels int64 |
|---|---|---|
e, I: Input, Output, C, S, M: Cb, P: Parser<I, Output, C, S, M>>
Parser<I, (Output, O), C, S, M> for GetStringExtend<P, O>
{
#[inline]
fn run(&self, cont: ICont<I, C, S, M>) -> IResult<(Output, O), I, S, M> {
let (mut input, begin) = (cont.ok.input.clone(), cont.ok.input.index());
self.0.run... | Rust | 0 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | Python | 1 |
from picamera2 import Picamera2
from datetime import datetime
from io import BytesIO
picam2 = Picamera2()
camera_config = picam2.create_preview_configuration()
picam2.configure(camera_config)
picam2.start()
print("Camera is ready. Press Enter to capture an image, or type 'exit' to quit.")
while True:
user_input ... | Python | 1 |
TempsInYear(bdd, stade, year):
"""
renvoie une liste des temperatures de l'annee annee du stade stade
"""
bddStade = bdd.cursor()
rep = []
command = "SELECT TEMPERATURE FROM TEMPERATURE WHERE JOUR LIKE ? AND Stade = ?;"
temp = bddStade.execute(command, (str(year) + "%", stade)).fetchall()
... | Python | 1 |
EnsureRootOrTwoThirdsGeneralCouncil;
type MembershipInitialized = TechnicalCommittee;
type MembershipChanged = TechnicalCommittee;
}
type OperatorMembershipInstanceShadow = pallet_membership::Instance5;
impl pallet_membership::Trait<OperatorMembershipInstanceShadow> for Runtime {
type Event = Event;
type AddOrigi... | Rust | 0 |
mask = torch.ones(i, j, device=device).triu_(j - i + 1).bool()
dots.masked_fill_(mask, mask_value)
attn = softmax(dots, dim=-1)
out = torch.einsum("b h i j, b h j d -> b h i d", attn, v)
out = rearrange(out, "b h n d -> b n (h d)")
out = self.to_out(out)
retur... | Python | 1 |
let mut last_tick = Instant::now();
loop {
let timeout = tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or_else(|| Duration::from_secs(0));
if event::poll(timeout).unwrap() {
let new_event: Result<CEvent, crossterm::ErrorKind> ... | Rust | 0 |
/!
//! ```ignore
//! use cortex_m::interrupt;
//! use cortex_m::peripheral::Peripherals;
//! use stm32f30x::Interrupt;
//!
//! let p = Peripherals::take().unwrap();
//! let mut nvic = p.NVIC;
//!
//! nvic.enable(Interrupt::TIM2);
//! nvic.enable(Interrupt::TIM3);
//! ```
//!
//! ## the "rt" feature
//!
//! If the "rt" ... | Rust | 0 |
-> &Self::Target {
&self.0
}
}
impl core::convert::From<crate::R<DATAW_SPEC>> for R {
fn from(reader: crate::R<DATAW_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DATAW[%s]` writer"]
pub struct W(crate::W<DATAW_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DATAW_SPEC>... | Rust | 0 |
QT, S>(id: u64)
where
I: Input,
QT: QemuHelperTuple<I, S>,
{
let helpers = unsafe { get_qemu_helpers::<QT>() };
let emulator = Emulator::new_empty();
for hook in unsafe { &EDGE_HOOKS } {
let func: fn(&Emulator, &mut QT, Option<&mut S>, u64) = unsafe { transmute(*hook) };
(func)(&emu... | Rust | 0 |
ckPacks.ndf
all_donor_packs = donor_data["simple_packs"] + donor_data["transport_packs"]
for donor_namespace in all_donor_packs:
# Parse donor namespace
parts = donor_namespace.split("_")
if len(parts) < 4:
continue
try:
n... | Python | 1 |
import RPi.GPIO as GPIO
import time
from RPLCD.i2c import CharLCD
# Configuración inicial de los pines GPIO
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER = 5
GPIO_ECHO = 6
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
# Configuración del LCD
lcd = CharLCD('PCF8574', 0x27, cols=16, rows=2)
# Constantes
VEL_... | Python | 1 |
import openai
from openai import OpenAI
import os
import time
from functools import cache
from sentence_transformers import SentenceTransformer
class OpenAILLM:
def __init__(self, llm_model_name, embedding_model_name):
self.client = OpenAI()
self.llm_model_name = llm_model_name
self.emb... | Python | 1 |
from . import account_payment
| Python | 1 |
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
win32con.FILE... | Python | 1 |
# Copyright 2021 Tencent
# SPDX-License-Identifier: BSD-3-Clause
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.gn_0 = nn.GroupNorm(num_groups=4, num_channels=12)
self.gn_1 = nn.GroupNorm(nu... | Python | 1 |
source: ValueError::VectorTooLong { max: 2, actual: 3 },
}
);
}
#[test]
fn vector_elements_validated() {
let decl = config_decl! {
ck@ vec![0x50, 0x12, 0x82],
foo: { vector, element: { string, max_size: 5 }, max_count: 2 },
};
le... | Rust | 0 |
*/
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub google_analytics: String,
/**
* The tracking options for the Automation.
*/
#[serde(
default,
deserial... | Rust | 0 |
, sticker, etc.
ChannelPost(ChannelPost),
/// New version of a channel post that is known to the bot and was edited
EditedChannelPost(ChannelPost),
// InlineQuery(InlineQuery),
// ChosenInlineResult(ChosenInlineResult),
CallbackQuery(CallbackQuery),
#[doc(hidden)]
Unknown(RawUpdate),
}
... | Rust | 0 |
import sys
from datetime import datetime
from threading import Thread
import Queue
from boto.utils import RequestHook
from boto.compat import long_type
class RequestLogger(RequestHook):
"""
This class implements a request logger that uses a single thread to
write to a log file.
"""
def __init__(s... | Python | 1 |
subdivisions – Part 2: Country subdivision code"
//! * [ISO 3166-3][5] refers to "Codes for the representation of names of
//! countries and their subdivisions – Part 3: Code for formerly used names
//! of countries".
//!
//! # Crate layout
//! The main purpose of this crate is to establish lightweight country ... | Rust | 0 |
int bok(int);
extern "Python" {int foobar(int, int);int bzrrr(int);}
int baz(int, int);
""")
assert sorted(ffi._parser._declarations) == [
'extern_python bzrrr', 'extern_python foobar',
'function baz', 'function bok']
assert (ffi._parser._declarations['function baz'] ==
... | Python | 1 |
}
extern "C" {
pub fn snd_hctl_elem_get_numid(obj: *const snd_hctl_elem_t) -> ::std::os::raw::c_uint;
}
extern "C" {
pub fn snd_hctl_elem_get_interface(obj: *const snd_hctl_elem_t) -> snd_ctl_elem_iface_t;
}
extern "C" {
pub fn snd_hctl_elem_get_device(obj: *const snd_hctl_elem_t) -> ::std::os::raw::c_uint;... | Rust | 0 |
ge(0., 1.)).floor() as i32,
};
let end = Point {
x: start.x + width - 1,
y: start.y + height - 1,
};
Room {
top_left: start,
bottom_right: end,
doors: Vec::new(),
}
}
fn add_door(&mut self, door: Point) {
... | Rust | 0 |
ry::new)
}
}
impl ::protobuf::Clear for CMsgSteamNetworkingICESessionSummary {
fn clear(&mut self) {
self.failure_reason_code = ::std::option::Option::None;
self.local_candidate_types = ::std::option::Option::None;
self.remote_candidate_types = ::std::option::Option::None;
self.... | Rust | 0 |
.get_name().clone(),
last_seen_command.get_usage().clone(),
);
usage_hashmap.insert(
url_preview_command.get_name().clone(),
url_preview_command.get_usage().clone(),
);
let mut usage_command = UsageCommand::new(&settings.command_prefix, &mut usage_hashmap);
let mut command_di... | Rust | 0 |
X, fusion_proportion, [model1, model2], params)
fused_model = SimpleNet()
state_dict = fused_model.state_dict()
for idx, (key, _) in enumerate(state_dict.items()):
state_dict[key] = fused_weights[idx]
fused_model.load_state_dict(state_dict)
fused_model.to(device)
... | Python | 1 |
import enum
import gzip
class SupportedOrganisms(enum.Enum):
HOMO_SAPIENS = "NCBITaxon:9606"
MUS_MUSCULUS = "NCBITaxon:10090"
SARS_COV_2 = "NCBITaxon:2697049"
ERCC = "NCBITaxon:32630"
class GeneChecker:
"""Handles checking gene ids, retrieves symbols"""
base_prefix = "backend/common/ontolog... | Python | 1 |
p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */
/* [r9 r8 r7 r6 r5 r4 r3 t2 d r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */
self.n[1] = (d & M) as u32; d >>= 26;
debug_assert_bits!(self.n[1], 26);
debug_assert_bits!(d, 27);
debug_assert!(d <= 0x4... | Rust | 0 |
b636ad381432c5c790c26b07051b661a2fec4e607f9644f84993c8335db21ae36b6008bab2883ad7541809bf5f49272295c1c1f1cf8c678553"),
ciphertext: &hex!("e06109680d5fefd345665ec9a5b2e7bf3ece3af1b62841a95c453e7753b5a1d6d8a10b3c6c42df1f23832b74e74871821f1c0b"),
tag: &hex!("953d8d04f70e2af055ac902a455235b2"),
},
Te... | Rust | 0 |
я строка в ciphertext должна иметь длину {n}.")
# Формируем матрицу: каждая строка превращается в список символов
paper = np.array([list(row) for row in ciphertext])
grille = np.array(self.grid, dtype=int).copy()
decrypted_chars = []
if not self.with_trash:
for _ in ... | Python | 1 |
from flask import Flask, request, jsonify, render_template, redirect, url_for
import psycopg2
from psycopg2 import sql
from flask_caching import Cache
from api import api
app = Flask(__name__)
api.init_app(app)
cache = Cache()
app.config['CACHE_TYPE'] = 'simple'
cache.init_app(app)
# Подключение к базе данных Postgr... | Python | 1 |
shape) * x_start +
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
def get_v(self, x, noise, t):
return (
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
extract_into_tensor(self.sqrt_one_minus_alphas_cum... | Python | 1 |
lf.batches.drain(..));
if !self.tail.is_empty() {
target.push(mem::replace(&mut self.tail, Vec::new()));
}
}
#[inline(always)]
pub fn finish(&mut self) -> Vec<Vec<T>> {
if !self.tail.is_empty() {
self.batches.push(mem::replace(&mut self.tail, Vec::new()));
... | Rust | 0 |
nly_i32"))]
#[cfg(not(feature = "only_i64"))]
gen_array_functions!(numbers => i8, u8, i16, u16, i32, i64, u32, u64);
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
#[cfg(not(target_arch = "wasm32"))]
gen_array_functions!(num_128 => i128, u128);
#[cfg(not(feature = "no_float"))]
gen_array_function... | Rust | 0 |
rn 0;
/// }
/// "#;
/// let lsp_range = Range {
/// start: Position { line: 1, character: 3 },
/// end: Position { line: 2, character: 4 },
///};
/// let ts_range = lsp_range_to_ts_range(&lsp_range, text.as_bytes());
pub fn lsp_range_to_ts_range(range: &lsp_types::Range, input: &[u... | Rust | 0 |
", 5.0)):
explanations.append(exp)
# Renormalise
total_w = sum(eff_w.values()) or 1.0
for src in eff_w:
eff_w[src] /= total_w
# Weighted mean (0‑10)
overall = sum(
eff_w[s] *
metrics.get(s, {}).get("deaditude_score", 5.0) for s in eff_w
)
adjusted_ov... | Python | 1 |
[
11934087455856126012,
14386424791387963807,
3468552646876333559,
782308259477189136,
],
[
15466433915116038126,
6356970036249743257,
... | Rust | 0 |
rbounwj3oj5xsspa7gj676azrog6ndi45iyuwrwzvawkxraa\n\
m1caxjxlggy5xv63isfp5oxdbucx35efhgevxdklvlcgjgpdus3j3q\n\
");
Ok(())
}
#[test]
fn error() -> anyhow::Result<()> {
SERVER.admin_cmd()
.arg("database").arg("create").arg("empty_err")
.assert().success();
SERVER.admin_cmd(... | Rust | 0 |
#!/usr/bin/python3
# alien_color = 'green'
alien_color = 'yellow'
if alien_color == 'green':
print(f'Player earned 5 points.')
| Python | 1 |
t
Rows to select from X and y.
If ``estimator._pairwise is True`` and ``train_indices is None``
then ``indices`` will also be used to slice columns.
train_indices : array of int or None, default=None
If ``estimator._pairwise is True`` and ``train_indices is not None``,
then ... | Python | 1 |
TCP(seq=1, sport=5001 + i, dport=oport if i < 4 else cport,
options=tcpopt, flags=flags)
for i, flags in enumerate(["CS", "", "SFUP", "A", "S", "A", "FPU"])
]
tests.append(IP(dst=target) / UDP(sport=5008, dport=ucport) / (300 * "i"))
ans, unans = sr(tests, timeout=2)
ans.exte... | Python | 1 |
ap_deadline = 50000;
// assert_ok!(Evercity::bond_add_new(
// Origin::signed(ACCOUNT),
// bondid,
// bond.inner
// ));
// // try activate before been issued
// assert_noop!(
// Evercity::bond_activate(Origin::signed(MASTER), bondid, 0),
//... | Rust | 0 |
import requests
import torch
from PIL import Image
from numpy.ma.core import array
from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
from models.gdino.utils import DEVICE
class GDINO:
def build_model(self, ckpt_path: str | None = None, device=DEVICE):
model_id = "IDEA-Research/g... | Python | 1 |
eError):
rdf(stack[:, 0], stack, box=box)
# Reshape (3,3) boxes to (1,3,3) to match stacked input AtomArrays
rdf(stack[0, 0], stack[0], box=box)
def test_rdf_normalized():
"""
Assert that the RDF tail is normalized to 1.
"""
test_file = TEST_FILE
stack = load_structure(test_file)
... | Python | 1 |
ini models only
gemini_models = []
for model in models:
# Safely get model name
if hasattr(model, 'name') and model.name:
model_name = str(model.name)
if "gemini" in model_name.lower():
# Strip the fu... | Python | 1 |
key {
keypad.key_up(self.mapping[x].keypad);
}
}
}
_ => {}
}
}
_ => {}
}
}
}
pub struct KeyMapping {
key: sdl2::keyboard::Keycode,
keyp... | Rust | 0 |
=======================================================
# ASSIGNMENT
# =========================================================================================
def enterSignal_assignment_statement(
self, ctx: vhdlParser.Signal_assignment_statementContext
):
self.translator.translate("as... | Python | 1 |
TypedArrayName::BigUint64Array => {
if is_little_endian {
u64::from_le_bytes(bytes.try_into().expect("slice with incorrect length"))
.into()
} else {
u64::from_be_bytes(bytes.try_into().expect("slice with incorrect length"))... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Session23 示例2:代码格式化示例
本文件展示了代码格式化工具(如black、ruff format)的使用,
以及格式化前后的代码对比。
作者: Python教程团队
创建日期: 2024-01-01
"""
import json
import re
from datetime import datetime
from typing import Any, Dict, List, Optional, Union
class CodeFormatter:
"""
代码格式化演示类
... | Python | 1 |
num_subtrees += 1
if num_subtrees >= 2:
results.add(root)
def find_articulation_points(g: Graph) -> set:
"""The outer function for the articulation point finding algorithm.
Parameters
----------
g : Graph
The input graph.
Returns
-------
results : set of int
... | Python | 1 |
fn triangle_begin(&mut self, tagged: bool, size: usize, idx: usize) -> Result<()> {
Ok(())
}
/// End of Triangle processing
fn triangle_end(&mut self, tagged: bool, idx: usize) -> Result<()> {
Ok(())
}
/// Begin of PolyhedralSurface processing
///
/// Next: size * Polyg... | Rust | 0 |
tColor(img2, cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT_create()
# Compute the keypoints and its corresponding descriptors of each images
kp1, des1 = sift.detectAndCompute(gray1,None)
kp2, des2 = sift.detectAndCompute(gray2,None)
# Filter out the unreliable correspondences
correspondences = filter_ma... | Python | 1 |
al_group)
layout.addWidget(self.layer_settings_group)
layout.addStretch() # 底部留白
return scroll
def _save_project_to_file(self, plugin_id, target_filepath):
"""
[内置完整版] 将当前对话框的状态保存为 .pavp 工程文件。
"""
import tempfile, shutil, os, json, uuid, pandas as pd... | Python | 1 |
import webchecker, sys
webchecker.DEFROOT = "http://www.python.org/python/"
webchecker.MAXPAGE = 50000
webchecker.verbose = 2
sys.argv.append('-x')
webchecker.main()
raw_input("\nCR to exit: ")
| Python | 1 |
if (slope2a < 0 and slope2b > 0) or (slope2a > 0 and slope2b < 0):
neg_slope_ray2 = (p2, ext_p2a) if slope2a < 0 else (p2, ext_p2b)
pos_slope_ray2 = (p2, ext_p2b) if slope2a < 0 else (p2, ext_p2a)
else:
neg_slope_ray2 = (p2, ext_p2a) if abs(slope2a) > ... | Python | 1 |
void) -> c_int {
sym!(self, xcb_randr_set_crtc_gamma_sizeof)(_buffer)
}
/// Returns `true` iff the symbol `xcb_randr_set_crtc_gamma_sizeof` could be loaded.
#[cfg(feature = "has_symbol")]
pub fn has_xcb_randr_set_crtc_gamma_sizeof(&self) -> bool {
has_sym!(self, xcb_randr_set_crtc_gamma... | Rust | 0 |
2);
assert_eq!(simulator.map, create_map_after_second_step());
}
#[test]
fn simulate_10_steps() {
let mut simulator = create_simulator();
simulator.simulate(10);
assert_eq!(simulator.get_num_flashes(), 204);
}
}
pub trait Summable {
fn sum_fields(self) -> usize;
}
u... | Rust | 0 |
uired features: `\"Win32_Media_Multimedia\"`*"]
pub const NS_E_INVALID_STREAM: ::windows_sys::core::HRESULT = -1072889796i32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const NS_E_INVALID_TIMECODE: ::windows_sys::core::HRESULT = -1072882730i32;
#[doc = "*Required features: `\"Win32_Media_Multimedi... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-07 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rules', '0060_auto_20180403_0921'),
]
operations = [
migrations.AlterField(
model_name='categorytrans... | Python | 1 |
SideT {
fn from(s: &'a str) -> Self {
match s {
"INVALID" => SideT::INVALID,
"BUY" => SideT::BUY,
"SELL" => SideT::SELL,
_ => Self::default(),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum OrderTypeT {
INVALID = 0,
MARKET = ... | Rust | 0 |
}
}
use crate::{attr::Attr, command::parse_attrs, fields_parse::ParserType};
#[derive(Debug)]
pub struct CommandEnum {
pub prefix: Option<String>,
pub description: Option<String>,
pub rename_rule: Option<String>,
pub parser_type: ParserType,
}
impl CommandEnum {
pub fn try_from(attrs: &[Attr])... | Rust | 0 |
ff, 0x876b62ff, 0x575c5cff, 0x7a4958ff, 0x4c3e5cff,
0x4c3223ff, 0x4c522aff, 0x8e3c2eff, 0x251610ff, 0xbd3031ff, 0x943f61ff, 0x5c191dff, 0x167e86ff,
0x3a8e8cff, 0x562c3eff, 0x14b485ff, 0x646464ff, 0xd8af93ff, 0x7fa796ff,
];
// /// A lookup table from color index to color name.
// static BASE_COLOR_NAMES: &[&str... | Rust | 0 |
::Scalar::new(0.0, 255.0, 0.0, 0.0),
1,
opencv::imgproc::LINE_8,
0
)?;
let label = format!("[{}]", track_id);
let mut base_line = 0;
let label_size = opencv::imgproc::get_text_size(&label, opencv::imgproc::FONT_HERSHEY_SIMPLEX, 0.6, 1, &mut base_line)?;
let label_rect = cor... | Rust | 0 |
inputs", {})
seed_keys = ["seed", "noise_seed", "rand_seed"]
for seed_key in seed_keys:
self.randomise_input_seed(seed_key, inputs)
def run_workflow(self, workflow):
print("Running workflow")
prompt_id = self.queue_prompt(workflow)
self.wait_for_promp... | Python | 1 |
# Copyright 2021 Google LLC
#
# 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, s... | Python | 1 |
",
help="Skip the selection interface and include all files"
)
parser.add_argument(
"--no-clipboard",
action="store_true",
help="Disable automatic copy to clipboard"
)
parser.add_argument(
"--clipboard-only",
action="store_true",
help="Copy to clip... | Python | 1 |
from urllib.parse import urlparse
BANNER = """
"""
def parse_dsn(dsn: str,
default_port: int = None,
default_db: int = None) -> tuple:
"""Get a DSN and return pased info as:
>>> dsn="redis://user:password@127.0.0.1:6379/0"
>>> parse_dsn(dsn)
"user", "password", "127.0.0.... | Python | 1 |
and',
'--expand-bbl',
os.path.split(bbl_files[0])[1],
main_tex_path,
'--output',
temp_tex_fn]
else:
latexpand_args = ['latexpand',
... | Python | 1 |
import FWCore.ParameterSet.Config as cms
# MonitorTrackResiduals
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
MonitorTrackResiduals = DQMEDAnalyzer("MonitorTrackResiduals",
OutputMEsInRootFile = cms.bool(False),
# should histogramms on module level be booked and filled?
Mod_On = cms.bool(True),... | Python | 1 |
n: i32 = position as i32;
// Requires that self.rep, and datetime are valid values. Ensured by
// the guaranteses of UDateFormat and ustring::UChar.
let date = unsafe {
versioned_function!(udat_parse)(
self.rep,
datetime.as_c_ptr(),
da... | Rust | 0 |
}
}
if !self.position.is_center() {
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.delim(',', false)?;
}
serialize_items(&self.items, dest)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum LineDirection {
Angle(Angle),
Horizontal(HorizontalPositionKeyword... | Rust | 0 |
IPFS
try:
ipfs_hash = upload_to_ipfs(file_data, filename, env)
env.add_system_log(f"IPFS CID: {ipfs_hash}")
except Exception as e:
env.add_reply(f"IPFS upload failed: {str(e)}")
env.request_user_input()
return
# NEAR setup
user_id = env.signer_account_id or "dev... | Python | 1 |
.with(|c| {
c.borrow_mut().define_with_attributes("color-text", "color");
});
}
#[no_mangle]
pub fn callback(callback_id: Callback, event: i32) {
// This function routes callbacks to the right closure
CUSTOM_ELEMENTS.with(|c| {
c.borrow_mut().route_callback(callback_id, event);
});
}
us... | Rust | 0 |
Ok(DisplayRotation::Deg0),
"90" => Ok(DisplayRotation::Deg90),
"180" => Ok(DisplayRotation::Deg180),
"270" => Ok(DisplayRotation::Deg270),
_ => Err(format!("Invalid DisplayRotation {}", s)),
}
}
/// Button Sample
#[derive(Debug, FromArgs)]
#[argh(name = "recovery")]
struct Args {
... | Rust | 0 |
sPublicKey = Deserialize::deserialize(&mut &inherent.data[..])?;
// Only remove if it was not already slashed.
// I kept this in two nested if's for clarity.
if receipt.newly_slashed {
let has_been_removed = self.current_epoch_parking.remove(&validato... | Rust | 0 |
ase use below two lines
#tre.remove_response(inventory=all_inv, output="VEL")
#trn.remove_response(inventory=all_inv, output="VEL")
tre.simulate(paz_remove = None, paz_simulate = paz_wa, taper=True,taper_fraction=0.02)
trn.s... | Python | 1 |
pub fn get_emulated_cpuid(&self, max_entries_count: usize) -> Result<CpuId> {
self.get_cpuid(KVM_GET_EMULATED_CPUID(), max_entries_count)
}
/// X86 specific call to get the system supported CPUID values.
///
/// See the documentation for `KVM_GET_SUPPORTED_CPUID`.
///
/// # Argumen... | Rust | 0 |
-8 directory should be valid UTF-8")
.to_owned();
fs::create_dir_all(Path::new(DNA_DIR_PATH)).context(CreateDnaDirectory)?;
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(&path)
.with_context(|| CreateFile { path: path.cl... | Rust | 0 |
])
batch_data['cx_hole_types_before'].append(sample['hole_types_before'])
batch_data['cx_hole_types_mask_before'].append(sample['hole_types_before_mask'])
batch_data['cx_hole_tokens_after'].append(sample['hole_tokens_after'])
batch_data['cx_hole_types_after'].append(sample['hole_types_a... | Python | 1 |
E::Vf::neg_zero() };
factorial = factorial * E::cast_from(k);
powers = powers * xx4;
let f = E::Vf::splat(factorial);
sign ^ powers / f / f
});
return match sum {
Ok(sum) => sum + E::Vf::one(),
Err(... | Rust | 0 |
pub fn tsovf(&mut self) -> _TsovfW {
_TsovfW { w: self }
}
#[doc = "Bit 13 - Tamper detection flag"]
#[inline(always)]
pub fn tamp1f(&mut self) -> _Tamp1fW {
_Tamp1fW { w: self }
}
#[doc = "Bit 14 - TAMPER2 detection flag"]
#[inline(always)]
pub fn tamp2f(&mut self) -... | Rust | 0 |
== OCRAM_ERR_STATUS_A::OCRAM_ERR_STATUS_1
}
}
#[doc = "Write proxy for field `OCRAM_ERR_STATUS`"]
pub struct OCRAM_ERR_STATUS_W<'a> {
w: &'a mut W,
}
impl<'a> OCRAM_ERR_STATUS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OCRAM_ERR_STATUS_A) -> &'... | Rust | 0 |
# -*- coding: utf-8 -*-
from ..Hurricane import DataBase, UpdateSession, DbU, Box, Net
from ..Analog import Device
from ..helpers import trace, l, u, n
from ..helpers.io import catch
from . import getRules, paramsmatrix
from .resistorsnake import Resistor
#helpers.setTraceLevel( 100 )
... | Python | 1 |
return {'message': 'File type not allowed'}, HTTPStatus.BAD_REQUEST
user = User.get_by_id(id=get_jwt_identity())
if user.avatar_image:
avatar_path = image_set.path(folder='avatars', filename=user.avatar_image)
if os.path.exists(avatar_path):
os.remove(a... | Python | 1 |
from database import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(100), nullable=True) # Add the email field
job_searches = db.... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
#!/usr/bin/env python
import argparse
import datetime
import rospy
import sys
import time
# 0 < n < burn-in => min-value
# burn-in < n < burn-in+ramp-up => value annealed from min to max
# burn-in+ramp-up < n => max-value
parser = argparse.ArgumentParser()
parser.add_argument('--param', type=str, help="rospy param to ... | Python | 1 |
"""
Valid Tree의 조건:
1. 모든 노드가 연결되어 있어야 함
2. 사이클이 없어야 함
3. edge의 개수는 n-1개
Time Complexity: O(V + E)
- V: 노드의 개수
- E: edge의 개수
Space Complexity: O(V)
- 노드 방문 여부를 저장하는 visited set 사용
풀이방법:
1. 기본 조건 체크: edge의 개수는 n-1개
2. 각 노드별로 연결된 노드들의 정보를 저장
- 무방향 그래프이므로 양쪽 모두 저장
3. DFS로 노드 탐색
- 0번 노드부터 시작해서 연결된 모든 노드를 방문
... | Python | 1 |
pr_name_len: u32,
}
unsafe impl ValueType for __wasi_prestat_u_dir_t {}
#[derive(Copy, Clone)]
#[repr(C)]
pub union __wasi_prestat_u {
dir: __wasi_prestat_u_dir_t,
}
impl fmt::Debug for __wasi_prestat_u {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "__wasi_prestat_u")
}
}
un... | Rust | 0 |
within the last DML array statement
*
* @param stmt - Statement handle
*
*/
pub fn OCI_GetBatchErrorCount(stmt: *mut OCI_Statement)
-> ::std::os::raw::c_uint;
}
extern "C" {
/**
* @brief
* Return the number of binds currently associated to a statement
*
* @param stmt - Statement handle
*
*/
... | Rust | 0 |
const MOSQ_ACL_READ: u32 = 1;
pub const MOSQ_ACL_WRITE: u32 = 2;
pub const MOSQ_ACL_SUBSCRIBE: u32 = 4;
pub const true_: u32 = 1;
pub const false_: u32 = 0;
pub const __bool_true_false_are_defined: u32 = 1;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct mosquitto {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug... | Rust | 0 |
essed(&input_state) {
rewinding_state.load_pos = Some(gb_state.auto_saved_states.len() - 1);
}
}
use error::ConsenSourceError;
use protobuf::{Message, RepeatedField};
use sawtooth_sdk::messages::batch::{Batch, BatchHeader, BatchList};
use sawtooth_sdk::messages::transaction::Transaction;
use sawtooth_sdk::s... | Rust | 0 |
= 2;
pub const PCI_BASE_ADDRESS_MEM_TYPE_64: u32 = 4;
pub const PCI_BASE_ADDRESS_MEM_PREFETCH: u32 = 8;
pub const PCI_BASE_ADDRESS_MEM_MASK: i32 = -16;
pub const PCI_BASE_ADDRESS_IO_MASK: i32 = -4;
pub const PCI_CARDBUS_CIS: u32 = 40;
pub const PCI_SUBSYSTEM_VENDOR_ID: u32 = 44;
pub const PCI_SUBSYSTEM_ID: u32 = 46;
p... | Rust | 0 |
gid,
);
}
idx = tt_find_glyph(glyphs, gid);
if idx as i32 == 0i32 {
idx = tt_add_glyph(glyphs, gid, count as u16);
count += 1
}
}
*cmap_table.offset((18i32 + code) a... | Rust | 0 |
_labels = self.pmk_dataset.get_anchor_labels(self.rev_ytbb_class_index, reviewed=True)
pmk_frames = self.pmk_dataset.get_pmk(k=10, reviewed=True)
# Collect predictions by key
valid_pmk_keys = {key for x in pmk_frames.values() for key in x.values()}
valid_anchor_keys = set(anchor_labels.k... | Python | 1 |
""" Base class for step data collations """
from openassessment.xblock.apis.workflow_api import WorkflowStep
from openassessment.xblock.utils.resolve_dates import DISTANT_FUTURE
class StepDataAPI:
def __init__(self, block, step=None):
self._block = block
problem_closed, closed_reason, start_date, ... | Python | 1 |
num = float(input("Digite um número: "))
quadrado = num ** 2
print(quadrado) | Python | 1 |
{
self.editing.signal()
}
}
const STORAGE_KEY: &str = "silkenweb-examples-todomvc";
#[derive(Display, Copy, Clone, Eq, PartialEq)]
pub enum Filter {
All,
Active,
Completed,
}
<reponame>Darth-Revan/jwt-rs
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free o... | Rust | 0 |
x512vl")]
unsafe fn test_mm256_maskz_subs_epu8() {
let a = _mm256_set1_epi8(1);
let b = _mm256_set1_epi8(u8::MAX as i8);
let r = _mm256_maskz_subs_epu8(0, a, b);
assert_eq_m256i(r, _mm256_setzero_si256());
let r = _mm256_maskz_subs_epu8(0b00000000_00000000_00000000_00001111, ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.