text string | label_name string | labels int64 |
|---|---|---|
pl From<PathBuf> for Source {
fn from(path: PathBuf) -> Self {
Self::Path(path)
}
}
///Error codes: Use archive_errno() and archive_error_string()
///to retrieve details. Unless specified otherwise, all functions
///that return 'int' use these codes.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr... | Rust | 0 |
}
}
};
}
impl_fraction_binop!(Add, add, AddAssign, add_assign);
impl_fraction_binop!(Sub, sub, SubAssign, sub_assign);
impl_fraction_binop!(Div, div, DivAssign, div_assign);
impl_fraction_binop!(Mul, mul, MulAssign, mul_assign);
impl_fraction_binop!(Rem, rem, RemAssign, rem_assign);
impl ops::... | Rust | 0 |
(123, true, ())
);
detest!(
de_mathop,
MathOp,
"({a: 1, b: 3, c: 'ignored'})",
MathOp {
a: 1,
b: 3,
operator: None
}
);
// Unit enums
detest!(de_enum_unit_a, EnumUnit, "'A'", EnumUnit::A);
detest!(de_enum_unit_b, EnumUnit, "'B'", EnumUnit::B);
detest!(de_enum_unit_c, EnumUnit, "'C'", EnumUnit::C)... | Rust | 0 |
struct HasDenyRole(u32, u32, u32);
struct HasDeniedLogin(u32, u32, u32);
// Output for IDB
@output
struct HasAccess(u32, u32, u32, u32);
@output
struct DenyAccess(u32, u32, u32, u32);
@output
struct DenyLogins(u32, u32, u32);
// Intermediate rules to help determine access
H... | Rust | 0 |
import streamlit as st
import base64
with open("jihan_amalia.jpg", "rb") as img_file:
img_bytes = img_file.read()
img_base64 = base64.b64encode(img_bytes).decode()
profile_img_html = f"""
<div style="display: flex; justify-content: flex-end; margin-top: -40px;">
<img src="data:image/jpeg;base64,{img_base6... | Python | 1 |
impl Future for CallbackFuture {
type Output = Option<f64>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut shared_state = self.shared_state.lock();
if shared_state.completed {
Poll::Ready(shared_state.result)
} else {
shared_s... | Rust | 0 |
"""
Tests for openedx.core.djangolib.translation_utils
"""
import unittest
import datetime
import ddt
from openedx.core.djangolib.translation_utils import translate_date
@ddt.ddt
class TranslateDateTest(unittest.TestCase):
"""Test that we can convert the date object into a string with translation."""
@dd... | Python | 1 |
is right
}
#[derive(Debug)]
struct BingoCard {
numbers: Vec<u32>,
hits: Vec<u8>,
winner: bool
}
impl BingoCard {
pub fn new() -> Self {
Self {
numbers: vec![],
hits: vec![0; 25],
winner: false
}
}
pub fn is_winner(&self) -> bool {
ma... | Rust | 0 |
[inline]
fn is_trampoline_set( address_location: usize ) -> bool {
let slot = unsafe { &mut *(address_location as *mut usize) };
*slot == nwind_ret_trampoline as usize
}
#[inline]
fn push( &mut self, stack_pointer: usize, address_location: usize ) -> ShadowStackResult {
let slot... | Rust | 0 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Baidu, Inc. 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/LICEN... | Python | 1 |
);
let client_cert = Some(std::env::var(env_client_cert).unwrap_or_default());
let client_key = Some(std::env::var(env_client_key).unwrap_or_default());
ensure_cert_key(client_cert.as_ref().unwrap(), client_key.as_ref().unwrap())?;
cfg.audit.insert(
target,
Webhoo... | Rust | 0 |
ssert type(res) is np.void
assert res.item() == b"\0" * 5
assert res.dtype == "V5"
@pytest.mark.parametrize("bytes_",
[b"spam", np.array(567.)])
def test_void_from_byteslike(bytes_):
res = np.void(bytes_)
expected = bytes(bytes_)
assert type(res) is np.void
assert res.item() == expected... | Python | 1 |
: Command,
x: Range<i32>,
y: Range<i32>,
z: Range<i32>,
}
fn get_middle(range: &Range<i32>) -> i32 {
((range.end - range.start) / 2) + range.start
}
fn get_half_range(range: &Range<i32>, use_top_half: bool) -> Range<i32> {
let middle = get_middle(range);
if use_top_half {
middle..range... | Rust | 0 |
from networkx import DiGraph
def print_graph(graph: DiGraph, mode='all'):
print(f'An attack graph with {graph.number_of_nodes()} nodes and {graph.number_of_edges()} edges')
if mode == 'all' or mode == 'nodes':
print('===== Nodes =====')
nodes = graph.nodes.data()
for node in nodes:
... | Python | 1 |
", 584, Word, R),
Reg::new("M54-60-S250-RA", V2, "PositionTrajectory", 588, Word, R),
Reg::new("M54-60-S250-RA", V2, "PresentInputVoltage", 592, Half, R),
Reg::new("M54-60-S250-RA", V2, "PresentTemperature", 594, Byte, R),
Reg::new("M54-60-S250-RA", V2, "ExternalPortData1", 600, Half, RW),
Reg::new(... | Rust | 0 |
"""Unit tests for oauth2client.util."""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import unittest
from oauth2client import util
class ScopeToStringTests(unittest.TestCase):
def test_iterables(self):
cases = [
('', ''),
('', ()),
('', []),
('', ('', )),
('', ['', ]),
... | Python | 1 |
s. Waiting for {wait_interval} seconds...")
time.sleep(wait_interval)
except requests.exceptions.RequestException as e:
logger.error(f"Status check for batch {batch_id} failed: {e}")
# Check if it's a client error (4xx) - these are typically not recoverable
... | Python | 1 |
# pids = 852, 104, 824, 506, 540
demo_prompt = """
Please read the following example. Then extract the answer from the model response and type it at the end of the prompt.
Hint: Please answer the question requiring an integer answer and provide the final value, e.g., 1, 2, 3, at the end.
Question: Which number ... | Python | 1 |
from datetime import datetime, timedelta, timezone
from typing import Dict, Any, overload, Type, TYPE_CHECKING
from apscheduler.triggers.interval import IntervalTrigger
from nonebot_plugin_session import Session
from .interval_task_worker import IntervalTaskWorker
from ..config import Config
from ..data.watch_task im... | Python | 1 |
let class = class.lookup(self)?;
let msg = msg.into();
let res: i32 = jni_unchecked!(self.internal, ThrowNew, class.into_inner(), msg.as_ptr());
if res == 0 {
Ok(())
} else {
Err(format!("throw_new failed with code {}", res).into())
}
}
/// C... | Rust | 0 |
false,
if output_nodes[neighbor_node_id] {
neighbor.node_id.as_usize()
} else {
graph
.mirror_node(neighbor.node_id)
.ok_or_else(|| Error::from(ErrorKind::B... | Rust | 0 |
from ipaddress import ip_address, ip_network
net = ip_network('11.92.135.56/255.224.0.0', False)
print(''.join(str(max(net.hosts())).split('.')))
| Python | 1 |
continue comparing upper level term, we store a `continue_op` on
// `stack`.
EqResult::CompareNested(a3, b3, continue_op) => {
stack.push(continue_op);
op = ContinueCompare::AnyType(a3, b3);
continue
},
}
}
}
fn cmp_terms_any_type(a: LTerm, b: LTerm, exact: bool) -> EqR... | Rust | 0 |
used in the tests
fn get_metrics() -> Vec<Metric> {
vec![
Metric {
metric_name: Some("BucketSizeBytes".into()),
namespace: Some("AWS/S3".into()),
dimensions: Some(vec![
Dimension {
name: "BucketName"... | Rust | 0 |
#!/usr/bin/env python
# (C) Crown Copyright, Met Office. All rights reserved.
#
# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license.
# See LICENSE in the root of the repository for full licensing details.
"""Script to calculate the ratio of convective precipitation to total precipitation.""... | Python | 1 |
r, e = "", wl = pad_left, wr = pad_right),
&[],
1..5,
|_, _| true,
|len, _, _| ParseInstructionError::TooManyTokens(len));
}
}
... | Rust | 0 |
let b = oberon::Blinding::new(&blind);
tkn = tkn + b;
}
Ok(BlindOberonTokenResponse {
token: tkn.to_bytes().to_vec(),
})
}
}
<reponame>alexmeli100/pbrt-rust<gh_stars>10-100
use std::sync::Arc;
use crate::core::texture::{TextureSpec, TextureFloat, Texture};
us... | Rust | 0 |
dable for DOUT31_28 {}
#[doc = "`write(|w| ..)` method takes [dout31_28::W](dout31_28::W) writer structure"]
impl crate::Writable for DOUT31_28 {}
#[doc = "Data Out 28 to 31 Alias register for byte access to each bit in DOUT31_0"]
pub mod dout31_28;
#[doc = "Data Output for DIO 0 to 31\n\nThis register you can [`read`]... | Rust | 0 |
POSTGRES_SQLALCHEMY_DATABASE_URI = 'postgresql://thecontactapp:password@database.anshil.me:5432/thecontactapp'
| Python | 1 |
new(4).recip()).as_str(), "1/4");
//! assert_eq!(format!("{:?}", Fp::from(-4)).as_str(), "-4");
//! assert_eq!(format!("{:?}", Fp::from(-4).recip()).as_str(), "-1/4");
//! ```
use std::{
cmp::PartialEq,
fmt,
hash::{Hash, Hasher},
iter::{successors, Product, Sum},
marker::PhantomData,
mem::swap,... | Rust | 0 |
.__del__Fatal error on pipe transportc C sZ t |tr4|jtjkr4| j rLtjd| |dd n| j||| | j d |
| d S Nz%r: %sTexc_info)message exceptionr rY )rS r@ rF ZEIOr r r
r call_exception_handlerr r r! rJ r r r r r s
... | Python | 1 |
moduleDef
<< module_ + identifier + lbrace + ZeroOrMore(moduleItem) + rbrace + semi
)
bnf = moduleDef | OneOrMore(moduleItem)
singleLineComment = "//" + restOfLine
bnf.ignore(singleLineComment)
bnf.ignore(cStyleComment)
return bnf
if __name__ == "__main__"... | Python | 1 |
# Copyright 2024-2025 Arm Limited and/or its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
import logging
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.ex... | Python | 1 |
from janito.llm.provider import LLMProvider
from janito.llm.model import LLMModelInfo
from janito.llm.auth import LLMAuthManager
from janito.llm.driver_config import LLMDriverConfig
from janito.drivers.zai.driver import ZAIModelDriver
from janito.tools import get_local_tools_adapter
from janito.providers.registry impor... | Python | 1 |
, custom_derive)]
#![plugin(rocket_codegen)]
mod api;
mod types;
mod database;
mod util;
#[macro_use] extern crate diesel;
#[macro_use] extern crate serde_derive;
extern crate rocket;
extern crate serde_json;
extern crate rocket_contrib;
extern crate rand;
use std::io;
use rocket::response::NamedFile;
use rocket_cont... | Rust | 0 |
except Exception as e:
write_log(
"ERROR",
f"Error fetching username for chat_id {chat_id}: {e}")
report += f"{i}. Chat ID: {chat_id}\n"
report += f" Username: {username}\n"
report += f" Subscriptions ({len(suffix... | Python | 1 |
fn main() {
let input = read_to_string("inputs/day15.txt").expect("Input not found..");
// PART 1
let start = Instant::now();
let known_answer = "148737";
let part_1: usize = time_button_press(&input, 1);
let duration = start.elapsed();
print_part_1(&part_1.to_string(), &known_answer, dura... | Rust | 0 |
1.0, 0.0)
}
#[inline]
pub fn bxdf_incident_to(v: Vec3) -> Vec3 {
Vec3::new(-v.x, v.y, -v.z)
}
#[inline]
pub fn is_neg(v: Vec3) -> bool {
v.y < 0.0
}
#[inline]
pub fn flip_if_neg(mut v: Vec3) -> Vec3 {
if is_neg(v) {
v.y = -v.y;
}
v
}
#[inline]
pub fn flip(mut v: Vec3) -> Vec3 {
v.y ... | Rust | 0 |
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .models import GrupoMuscular, Ejercicio, Template, Historial
from .serializers import GrupoMuscularSerializer, EjercicioSerializer, TemplateSerializer, TemplateCreateSerializer,... | Python | 1 |
# coding: utf-8
"""
Unifi API
Unifi Controller API
The version of the OpenAPI document: 8.0.26
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
import datetime
from unifi_client.models.map_response import MapResp... | Python | 1 |
ize()
}
mod lz4 {
use std::{i32, ptr};
// TODO: use in place compression instead.
#[inline]
pub fn encode_block(src: &[u8]) -> Vec<u8> {
unsafe {
let bound = lz4_sys::LZ4_compressBound(src.len() as i32);
if bound > 0 && src.len() <= i32::MAX as usize {
l... | Rust | 0 |
from keras.layers import Dropout, Dense
from keras.models import Sequential
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from sklearn import metrics
def TFIDF(X_train, X_test,MAX_NB_WORDS=75000):
vectorizer_x = TfidfVectorizer(max_features=MAX_NB_WORDS)
X_train = vectorizer_... | Python | 1 |
import logging
import logging.handlers
import os
from pathlib import Path
from app.core.config import settings
def setup_logging():
"""Initialize logging configuration."""
# Create log directory
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
# Set log level
log_level = getattr(l... | Python | 1 |
ize, output_seq_len, num_nodes, output_dim)
seq_preds = model(x, y, supports)
loss = utils.compute_regression_loss(
y_true=y,
y_predicted=seq_preds,
loss_fn="mae",
standard_scaler=scaler,
device=device)
... | Python | 1 |
Unit {
#[as_ref]
#[as_mut]
#[deref]
#[deref_mut]
#[holder(use_place_holder)]
pub named_unit: NamedUnit,
pub name: Label,
#[holder(use_place_holder)]
pub conversion_factor: MeasureWithUnitAny,
}
#[derive(Debug, Clone, PartialEq, :: derive_ne... | Rust | 0 |
" z="0.38"/>"#).unwrap();
let v: Vec3A = parse_vector3(&doc.root_element()).unwrap();
assert_eq!(v, Vec3A::new(-0.7, 1.4, 0.38));
}
fn parse_color(e: &Node) -> Result<Color, anyhow::Error> {
Ok(Color::new(
fatt(e, "r")?,
fatt(e, "g")?,
fatt(e, "b")?,
fatt(e, "a").unwrap_or(1... | Rust | 0 |
) {
unsafe {
GEN_READ_HOOK = Hook::Function(hook as *const libc::c_void);
}
self.emulator
.set_gen_read_hook(gen_read_hook_wrapper::<I, QT, S>);
}
pub fn read_generation_closure(
&self,
hook: Box<dyn FnMut(&Emulator, &mut QT, Option<&mut S>, usize... | Rust | 0 |
ent/vrep.pyt simxJointGetForce s c C s1 t j } t | | t j | | | j f S( s_
Please have a look at the function description/documentation in the V-REP user manual
( Rr Rs R Ru Rv ( Rw Rx Ry R ( ( s0 /home/priest-king/Desktop/PepperMo... | Python | 1 |
r s rS rX
TarInfo.isdirc yyG##rV c ( U R [ :H $ )%Return True if it is a symbolic link.ry SYMTYPE)r s rS rY
TarInfo.issymg r rV c ( U R [ :H $ )!Return True if it is a hard l... | Python | 1 |
# https://github.com/gevent/gevent/issues/652 and 651
from gevent import monkey
monkey.patch_all()
import _import_wait # pylint:disable=import-error
assert _import_wait.x
| Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2024/10/25 0:21
@Author : thezehui@gmail.com
@File : auth_schema.py
"""
from flask_wtf import FlaskForm
from marshmallow import Schema, fields
from wtforms import StringField
from wtforms.validators import DataRequired, Email, Length, regexp
from pkg.pas... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2022 F4PGA Authors
#
# 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
#
# Unl... | Python | 1 |
""
final_state = self.cir()
# 定义一系列观测量
pauli_list = generate_pauli_string_list(num_qubits=self.num_qubits, num_terms=self.latent_dim)
obs = [paddle_quantum.Hamiltonian(pauli) for pauli in pauli_list]
# 计算一系列观测量的平均值
expec_obs = [ExpecVal(ob)(final_state) for ob in obs]
... | Python | 1 |
Self {
variant as u8 != 0
}
}
#[doc = "Field `DPDWAKEUPRESETENABLE` reader - Wake-up from DEEP POWER DOWN reset event (either from wake up I/O or RTC or OS Event Timer)."]
pub struct DPDWAKEUPRESETENABLE_R(crate::FieldReader<bool, DPDWAKEUPRESETENABLE_A>);
impl DPDWAKEUPRESETENABLE_R {
#[inline(always)... | Rust | 0 |
res = {}
else:
timestamp = [x.date.timestamp() for x in filtered]
values = [getattr(x, metric) for x in filtered]
res["timestamp"] = timestamp
res["value"] = values
none_indexes = [ i for i, v in enumerate(res["value"... | Python | 1 |
def add_connected_listener(self, listener):
self._on_connected_listeners.add(listener)
def add_command_handler(self, command, handler, help_string=""):
self.bot.dispatcher.add_handler(CommandHandler(command, handler))
def _start_cmd_handler(self, update, context):
update.message.reply_... | Python | 1 |
, Index>,
column2user: HashMap<Index, Id>
}
impl RatingContainer {
pub fn anime2row(&self, animeid: Id) -> Option<Index> {
return self.anime2row.get(&animeid).map(|r| *r);
}
pub fn row2anime(&self, rowidx: Index) -> Option<Id> {
return self.row2anime.get(&rowidx).map(|a| *a);
}
p... | Rust | 0 |
import pytest
import capnp
import os
this_dir = os.path.dirname(__file__)
@pytest.fixture
def addressbook():
return capnp.load(os.path.join(this_dir, "addressbook.capnp"))
def test_object_basic(addressbook):
obj = capnp._MallocMessageBuilder().get_root_as_any()
person = obj.as_struct(addressbook.Person... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_helpdesk_forum.controllers.website_forum import WebsiteForumHelpdesk
class WebsiteSlidesForumHelpdesk(WebsiteForumHelpdesk):
def get_template_xml_id(self):
return "website_helpdesk... | Python | 1 |
y_req.headers[hdrs.AUTHORIZATION]
del proxy_req.headers[hdrs.AUTHORIZATION]
req.headers[hdrs.PROXY_AUTHORIZATION] = auth
if req.ssl:
# For HTTPS requests over HTTP proxy
# we must notify proxy to tunnel connection
# so we send CONNECT command:
... | Python | 1 |
usize>,
pub total_votes: usize,
}
impl Committee {
pub fn new(voting_rights: BTreeMap<AuthorityName, usize>) -> Self {
let total_votes = voting_rights.iter().fold(0, |sum, (_, votes)| sum + *votes);
Committee {
voting_rights,
total_votes,
}
}
pub fn wei... | Rust | 0 |
[doc = "*Required features: 'Win32_Networking_WinHttp'*"]
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
pub struct WINHTTP_MATCH_CONNECTION_GUID {
pub ConnectionGuid: ::windows_sys::core::GUID,
pub ullFlags: u64,
}
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
impl ::core::marker::... | Rust | 0 |
"( 1.0 2.0 3.0 )"),
test_float_shove_wrap: ("( 1.0 2.0 3.0 3 FLOATSHOVE )", "( 1.0 2.0 3.0 )"),
test_float_sin: ("( 1.0 FLOATSIN )", "( 0.841470984807897 )"),
test_float_stack_depth: ("( 1.0 2.0 FLOATSTACKDEPTH )", "( 1.0 2.0 2 )"),
test_float_sum: ("( 1.5 2.5 FLOATSUM )", "( 4.0 )"),
... | Rust | 0 |
R 4 U- nU R XC[ R 5 $ )Mean of the Multinomial distribution.
Parameters
----------
%(_doc_default_callparams)s
Returns
-------
mean : float
The mean of the distribution
.r rR r% r< rH )r rP r6 rI r: s ... | Python | 1 |
import unittest
from .shell import SpyShell, FakeCommand, RunResult
class SpyTests(unittest.TestCase):
def testSpyShell(self) -> None:
shell = SpyShell(
[
FakeCommand(
"echo hello",
RunResult(0, b""),
),
Fa... | Python | 1 |
eck!(form!(Form::TimeOfDay(_))),
|_, tod| {
let day_period = helpers::hour(12, false)?.span_to(&helpers::hour(0, false)?, false)?;
Ok(tod
.value()
.intersect(&day_period)?
.form(tod.value().form.clone()))
},
);
b.rule_1_term... | Rust | 0 |
trainer.state.add_scalar_data_point("acc", acc.item(), smoothing=0.98)
st = trainer.STrainer(
update_fn,
info_string_components=trainer.DEFAULT_INFO_STRING_COMPONENTS + ("acc: {acc:.3f}",),
modules=[cnn],
)
st.state.acc = "l"
for e in range(30):
plot_and_add(ims, upwl)... | Python | 1 |
| BackupType::Flash512 => {
BackupMedia::Flash(Flash::new(backup_path, FlashSize::Flash64k))
}
BackupType::Flash1M => BackupMedia::Flash(Flash::new(backup_path, FlashSize::Flash128k)),
BackupType::Sram => BackupMedia::Sram(BackupFile::new(0x8000, backup_path)),
BackupType::E... | Rust | 0 |
println!(".game.new => Create game with default board");
println!(".new.ai => Create game with ai. Also shortcut for .game.new.ai");
println!(".game.save => Save game to file");
println!(".game.from.fen => Load game from FEN");
println!(".move => Make a move by providing move in UCI format: \"a2a4\" ... | Rust | 0 |
static,
ZV::Future: Send,
ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
ZS::Future: Send,
{
type Item = Result<UnminedTxId, BoxError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let this = self.project()... | Rust | 0 |
.xml",
)
.run()
.await?;
println!("{:?}", resp);
Ok(())
}
<filename>rust/pact_models/src/response.rs
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::str::from_utf8;
use base64::encode;
use log::warn;
use maplit::hashmap;
use se... | Rust | 0 |
lar angle as equirectangular information --------
imgU_o = np.concatenate([imgU_o, equi_info], 2)
imgD_o = np.concatenate([imgD_o, equi_info], 2)
# Real World / Synthetic preprocessing --------------------------
if args.real:
compose_trans = transforms.Compose([transforms.To... | Python | 1 |
_of::<FROM>() % std::mem::size_of::<TO>(),
0,
"cast_slice: Size of FROM must be equal to -- or a multiple of -- the size of TO"
);
unsafe {
std::slice::from_raw_parts(
slice.as_ptr() as *const TO,
slice.len() * (std::mem::size_of::<FROM... | Rust | 0 |
while let Ok(row) = input.read() {
if !seen.contains(&row) {
seen.insert(row.clone());
output.send(row)?;
}
}
}
Some(idx) => {
let mut seen: Has... | Rust | 0 |
ELECT
*
FROM style_presets
"""
if type is not None:
main_query += "WHERE type = ? "
main_query += "ORDER BY LOWER(name) ASC"
if type is not None:
cursor.execute(main_query, (type,))
els... | Python | 1 |
em Solving",
constant.KEY_OTHER_INFO: other_info
}
return formatted_sample
@register_formatter("EmoBenchCFormatter")
class EmoBenchCFormatter(BaseFormatter):
@override
def format(self, raw_sample: Dict[str, Any]) -> Dict[str, Any]:
# 处理None输入
if raw_sample ... | Python | 1 |
tupla = ("Jose Vicente","Carratala","info@jocarsa.com")
archivo = open("clientes.csv",'a')
cadena = ""
for campo in tupla:
cadena += campo+","
archivo.write(tupla)
archivo.close()
| Python | 1 |
pub enum EdsPhotoEffect
{
kEdsPhotoEffect_Off = 0u32,
kEdsPhotoEffect_Monochrome = 5u32,
}
impl Default for EdsPhotoEffect {
fn default() -> Self { EdsPhotoEffect::kEdsPhotoEffect_Off }
}
/// Color Matrix
#[repr(u32)]
#[derive(Debug)]
pub enum EdsColorMatrix
{
kEdsColorMatrix_Cus... | Rust | 0 |
ishing despite not knowing the lock script")
];
spend.input[0].witness[1].push(1);
spend.input[0].witness[2].push(1);
self.rpc.publish(&serialize(&spend)).await?;
Ok(())
}
}
}
async fn prepare_buy_for_client(&mut self) -> anyhow::Result<Vec<u8>> {
let lock = s... | Rust | 0 |
from pydantic import BaseModel
class Skill(BaseModel):
id: int = 0
level: int = 0
icon: str = "" | Python | 1 |
/// Arrays may contain `null` values (i.e.: `Vec<Option<T>>`). Note that `Vec<Vec<T>>` is not allowed.
pub trait ToSpanner {
/// Creates a new Cloud Spanner value from this value.
fn to_spanner(&self) -> Result<Value, Error>;
/// Returns the Cloud Spanner [Type] that this implementation produces.
fn sp... | Rust | 0 |
_arg("-std=c99")
.trust_clang_mangling(false)
.rust_target(bindgen::RustTarget::Stable_1_25)
.whitelist_type("^(?:rust_)?duk_.*")
.whitelist_function("^(?:rust_)?duk_.*")
.whitelist_function("^(?:rust_)?ducc_.*")
.whitelist_var("^DUK_.*")
.generate()
.expe... | Rust | 0 |
,
interpreter: &Interpreter<'_>,
parent_stack_frame: Option<&StackFrame<'_>>,
) -> eyre::Result<Value> {
self.object.invoke(interpreter, parent_stack_frame).await
}
}
impl std::fmt::Debug for Thunk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debu... | Rust | 0 |
t_data_providers,
consensus_data_provider: digest_provider,
mut sender,
}: SealBlockParams<'_, B, BI, SC, C, E, TP, CIDP>,
) where
B: BlockT,
BI: BlockImport<B, Error = sp_consensus::Error, Transaction = sp_api::TransactionFor<C, B>>
+ Send
+ Sync
+ 'static,
C: HeaderBackend<B> + ProvideRuntimeApi<B>,
E:... | Rust | 0 |
});
}
if (d & 0xffe0fc00) == 0x38601000 && (d & 0x00001f) != 0x00001f {
return Some(InstructionKind::LDCLRLB32Memop {
Rn: Rn as _,
Rs: Rs as _,
Rt: Rt as _,
});
}
if (d & 0xffe0fc00) == 0x38602000 && (d & 0x00001f) != 0x00001f {
return... | Rust | 0 |
)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as ... | Rust | 0 |
gst::init().unwrap();
let args: Vec<String> = env::args().collect();
let config = Config::new(&args).unwrap();
println!("Config: {:?}", config);
transcode(config);
}
extern crate phf;
include!(concat!(env!("OUT_DIR"), "/phf.rs"));
fn main() {
println!("{}", MAP.get("key1").unwrap());
}
use rust_d... | Rust | 0 |
dtype)
C = cublas.batch_matmul(A, B, dtype=out_dtype)
s = te.create_schedule(C.op)
def verify(target="cuda"):
if not tvm.get_global_func("tvm.contrib.cublas.matmul", True):
print("skip because extern function is not available")
return
ctx = tvm.gpu(0)
f = tvm... | Python | 1 |
"TCD Control and Status"]
pub mod tcd5_csr;
#[doc = "DMA_TCD5_BITER_ELINKNO register accessor: an alias for `Reg<DMA_TCD5_BITER_ELINKNO_SPEC>`"]
pub type DMA_TCD5_BITER_ELINKNO = crate::Reg<dma_tcd5_biter_elinkno::DMA_TCD5_BITER_ELINKNO_SPEC>;
#[doc = "TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking D... | Rust | 0 |
import torch
from tqdm import tqdm
from VMSVFND import VEMFSVModel,Contrastive_learning_model
from dataloader import VMSVFNDDataset, collate_fn
from torch.utils.data import DataLoader
from metrics import *
contrastive_model_path = 'checkpoints/contrastive_model.pth'
model_path = 'checkpoints/test_0.8672'
def load_ch... | Python | 1 |
e::Duration;
/// #[derive(Serialize, Deserialize, Debug)]
/// struct Movie {
/// name: String,
/// description: String,
/// }
/// // that trait is used by the sdk when the primary key is needed
/// impl Document for Movie {
/// type UIDType = String;
/// fn get_uid(&self)... | Rust | 0 |
class Solution:
def pivotInteger(self, n: int) -> int:
total_sum = n * (n + 1) // 2 # Sum of numbers from 1 to n
prefix_sum = 0
for x in range(1, n + 1):
prefix_sum += x # Sum from 1 to x
suffix_sum = total_sum - prefix_sum + x # Sum from x to n
... | Python | 1 |
#!/usr/bin/env python
# This shows how to leverage the endpoints API to get a new hidden
# service up and running quickly. You can pass along this API to your
# users by accepting endpoint strings as per Twisted recommendations.
#
# http://twistedmatrix.com/documents/current/core/howto/endpoints.html#maximizing-the-re... | Python | 1 |
plot_data['Y_data'][method_op_p99].append(p99_lat)
else:
# for clover only
clover_op_names = ['insert', 'update', 'search']
clover_MN_num = MN_num - 1 # 1 MN became MS
project_dir = f"{home_dir}/{method}/clover"
env_cmd = f"cd {project_dir}"... | Python | 1 |
here
S: serde::Serializer,
{
let mut map_ser = serializer.serialize_map(Some(2))?;
match self {
BasicOutput::Valid(outputs) => {
map_ser.serialize_entry("valid", &true)?;
map_ser.serialize_entry("annotations", outputs)?;
}
B... | Rust | 0 |
"""
-*- coding: utf-8 -*-
@Author: lee
@ProjectName: ITAssets
@Email: lijianqiao2906@live.com
@FileName: simpleui_conf.py.py
@DateTime: 2024/3/29 09:36
@Docs: simpleui配置文件
"""
# 隐藏首页服务器信息
SIMPLEUI_HOME_INFO = False
# 使用分析,默认开启,统计分析信息只是为了更好的帮助simpleui改进,并不会读取敏感信息。并且分析数据不会分享至任何第三方。
SIMPLEUI_ANALYSIS = False
# 离线模式... | Python | 1 |
parser
def get_short_help(self):
return 'Short help goes here'
def get_long_help(self):
return '''
script += "'''\n Your long help goes here\n '''"
return script
def generate_function_file(filename, options):
resolved_name = options.command_name if options.comman... | Python | 1 |
# once again, need to do this because torch can't convert cuda device tensor to numpy
ax.imshow(image.cpu().numpy().astype(int))
ax.set_title(
f'true label: {true_class} ({true_prob:.3f}) \n'
f'pred label: {incorrect_class} ({incorrect_prob:.... | Python | 1 |
ponse["choices"][0]["message"]["content"] = "test@example.com"
result = await email_validator.validate(test_response, {})
assert result.valid
print(" Accepted valid email")
test_response["choices"][0]["message"]["content"] = "not-an-email"
result = await email_validator.... | Python | 1 |
r(code_hash),
_ => Field::BackReference(req, idx),
}
}
}
fn complete(self) -> Result<Self::Complete, NoSuchOutput> {
Ok(Complete {
block_hash: self.block_hash.into_scalar()?,
code_hash: self.code_hash.into_scalar()?,
})
}
fn adjust_refs<F>(&mut self, mut mapping: F) where F: FnMut(us... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.