text string | label_name string | labels int64 |
|---|---|---|
lunatic::process::drop_config(config_id: u64)
//%
//% Drops the config resource.
//%
//% Traps:
//% * If the config ID doesn't exist.
fn drop_config(mut caller: Caller<ProcessState>, config_id: u64) -> Result<(), Trap> {
caller
.data_mut()
.resources
.configs
.remove(config_id)
... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright JS Foundation and other contributors, https://js.foundation/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# ... | Python | 1 |
fx=im_scale,
fy=im_scale,
interpolation=cv2.INTER_LINEAR
)
return im, im_scale
def zeros(shape, int32=False):
"""Return a blob of all zeros of the given shape with the correct float or
int data type.
"""
return np.zeros(shape, dtype=np.int32 if int32 else np.float32)
def ... | Python | 1 |
ngerprints for a list of molecules.
Parameters
----------
fingerprint_algorithm
Specifies algorithm for deriving fingerprints.
Supported algorithms are 'daylight', 'morgan1', 'morgan2', 'morgan3'.
fingerprint_type
Determine type for deriving molecular fingerprints.
Suppo... | Python | 1 |
better to be minimized, so the mode should be 'min'.
root_path/
│
├── configs/
│ └── config.py
│
└── checkpoints/
├── xxx_metric_name=xxx.ckpt
└── xxx_metric_name=yyy.ckpt
Args:
root_path (str): _description_
mode (str): met... | Python | 1 |
term::binary::sub(arc_process.clone()),
|binary| {
let result = erlang::bit_size_1(binary, &arc_process);
prop_assert!(result.is_ok());
let bit_size_term = result.unwrap();
let bit_size_small_integer: SmallInteger = bit_si... | Rust | 0 |
# Read air quality metrics from the PiicoDev Air Quality Sensor ENS160 and PiicoDev Atmospheric Sensor BME280
# ENS160 Shows three metrics: AQI, TVOC and eCO2
# ENS160 also shows Sensor Operational Mode (has it recorded for a while or (less accurately) just started recording)
# BME280 Shows three metrics: Temperature, ... | Python | 1 |
n and load result
super::andn(state, x, y, z);
let mut bits: u64 = state.gpr[x].into();
// Execute
let mut res: u64 = 0;
while bits != 0 {
res += bits % 2;
bits /= 2;
}
// Store result
state.gpr[x] = res.into();
}
<gh_stars>10-100
use anyhow::Context as _;
use serde::{D... | Rust | 0 |
hr_path = get_hr_path(&work, prefix);
let scf_data = Scf::new(scf_path).expect("could not find scf output file");
let model = W90Model::new(hr_path, scf_data.d).expect("error constructing model");
// TODO make dims a parameter.
// Want to allow specifying k_start, k_stop?
let dims = [8, 8, 8];
... | Rust | 0 |
eaders: Headers | Mapping[str, str] | None = None,
timeout_ms: int | None = None,
use_get: bool = False,
) -> example_dot_eliza__pb2.SayResponse:
return self.execute_unary(
request=request,
method=MethodInfo(
name="Say",
service_name="c... | Python | 1 |
of the field is `RCRS0OFF_1`"]
#[inline(always)]
pub fn is_rcrs0off_1(&self) -> bool {
*self == RCRS2OFF_A::RCRS0OFF_1
}
#[doc = "Checks if the value of the field is `RCRS0OFF_2`"]
#[inline(always)]
pub fn is_rcrs0off_2(&self) -> bool {
*self == RCRS2OFF_A::RCRS0OFF_2
}
}
#[... | Rust | 0 |
ed),
span,
recovered: false,
}))
}
use crate::{error::MetadataError, utils::try_from_slice_checked};
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
pubkey::Pubkey,
};
/// prefix used for ... | Rust | 0 |
0b1111_0110 => (Opcode::INTO, Just([OperandSpec::Nothing, OperandSpec::Nothing, OperandSpec::Nothing])),
0b1111_0111 => { return Err(StandardDecodeError::InvalidOperand); },
0b1111_1000 => (Opcode::ADJNZ(size), Reinterpret(OperandCategory::ADJNZ)),
0b1111_1001 => (Opcode::ADJNZ(size), Reinterpre... | Rust | 0 |
erminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use tui::{backend::CrosstermBackend, Terminal as TuiTerminal};
pub type Terminal = TuiTerminal<CrosstermBackend<Stdout>>;
/// Initialize and return a crossterm terminal instance
pub fn init_terminal() -> Result<Terminal> {
... | Rust | 0 |
let (uniform, mut id) = unsafe {
gl.BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl.Disable(gl::DEPTH_TEST);
let mut id: u32 = 0;
gl.GenTextures(1, &mut id);
gl.ActiveTexture(gl::TEXTURE0);
gl.BindTexture(gl::TEXTURE_2D, id);
... | Rust | 0 |
UT_DBUS_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - The bit is used to disable core0 ibus, 0: enable, 1: disable"]
#[inline(always)]
pub fn icache_shut_ibus(&mut self) -> ICACHE_SHUT_IBUS_W {
ICACHE_SHUT_IBUS_W { w: self }
}
#[doc = "Bit 1 - The bit is used to di... | Rust | 0 |
.unwrap();
loop {
match self.skip_value(vec![vec!['?' as u8, '?' as u8], vec!['|' as u8, '|' as u8], vec!['&' as u8, '&' as u8], vec!['&' as u8]]) {
Ok(operator) => {
let right = self.parse_compare();
if right.is_err() { return right; }
... | Rust | 0 |
].is_positive() {
Face::negative(entry_axis) // ray is positive; hit negative face of cell
} else {
Face::positive(entry_axis) // ray is negative; hit positive face of cell
};
Some(Hit {
start,
delta,
t0: max_t0,
t1: min_t1... | Rust | 0 |
_lsp_diagnostics(project_path="")
assert result["success"] is False
assert "error" in result
assert result["error_type"] == "VALIDATION_ERROR"
# Test None (should work - it's optional)
result = swift_lsp_diagnostics(project_path=None)
assert result["success"] is True
... | Python | 1 |
-> io::Result<Fdandle> {
get_std_handle(STD_ERROR_HANDLE)
}
}
impl ShhRead for Impl {
fn shh_read(read_file: &File, buf: &mut [u8]) -> io::Result<usize> {
let read_handle = read_file.as_raw_handle();
if !has_bytes(read_handle)? {
return Ok(0);
}
let buf_le... | Rust | 0 |
instr(vpshldvq))]
pub unsafe fn _mm512_shldv_epi64(a: __m512i, b: __m512i, c: __m512i) -> __m512i {
transmute(vpshldvq(a.as_i64x8(), b.as_i64x8(), c.as_i64x8()))
}
/// Concatenate packed 64-bit integers in a and b producing an intermediate 128-bit result. Shift the result left by the amount specified in the corres... | Rust | 0 |
const MD_NOTIFY_LOG: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_Iis\"`*"]
pub const MD_NOTIFY_NONSECURE_PORT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_Iis\"`*"]
pub const MD_NOTIFY_ORDER_DEFAULT: u32 = 131072u32;
#[doc = "*Required features: `\"Win32_System_Iis\"`*"]
pub const MD_NOTIFY_... | Rust | 0 |
from flask import request
from flask_accepts import accepts, responds
from flask_restx import Namespace, Resource
from flask.wrappers import Response
from typing import List
from .schema import WhatsitSchema
from .service import WhatsitService
from .model import Whatsit
from .interface import WhatsitInterface
api = N... | Python | 1 |
newlist = [x for x in range(10) if x < 5]
print(newlist) | Python | 1 |
SHIFT: usize = 20;
const ATTR_P_SHIFT: usize = 15;
const ATTR_DPL_SHIFT: usize = 13;
const ATTR_S_SHIFT: usize = 12;
const ATTR_TYPE_SHIFT: usize = 8;
const ATTR_A_SHIFT: usize = 8;
const ATTR_CS_SHIFT: usize = 11;
const ATTR_C_SHIFT: usize = 10;
const ATTR_R_SHIFT: usize = 9;
const ATTR_E_SHIFT: usize = 10;
const ATTR... | Rust | 0 |
"""
Gerador de Senha Aleatória - Versão 1.97
Este programa gera uma senha aleatória com o comprimento definido pelo usuário,
utilizando letras, números e caracteres especiais.
Autor: Prof. Sauer
Site: www.sauer.pro.br
Redes sociais:
Email: sauer@simplificatreinamentos.com.br
Instagram: https://www.instagram.com/prof... | Python | 1 |
(FlowType::InstalledInteractive),
//! # );
//! let hub = DriveHub::new(
//! hyper::Client::with_connector(hyper::net::HttpsConnector::new(
//! hyper_rustls::TlsClient::new(),
//! )),
//! auth,
//! );
//!
//! // get some initial info about the file
//! let gdriveinfo = GDriveFileInfo::new("gdrive_fil... | Rust | 0 |
-- Example Usage ---
if __name__ == '__main__':
# Example fitness scores (Index: (Obj1, Obj2)) - Higher is better for both
mock_fitness = {
0: (10, 1),
1: (8, 3),
2: (8, 3), # Duplicate fitness
3: (6, 5),
4: (4, 6),
5: (2, 7),
6: (9, 2), # Dominates 1 & 2... | Python | 1 |
k_sendall3 r r c K t wr= r| )r$ r r addresss r) sock_sendtozAbstractEventLoop.sock_sendto6 r r c K t wr= r| )r$ r r s r) sock_connectzAbstractEventLoop.sock_connect9 r r c ... | Python | 1 |
import sys
import matplotlib.pyplot as plt
import torch
from tqdm import tqdm
def matplotlib_imshow(img, one_channel=False):
fig = plt.figure()
if one_channel:
img = img.mean(dim=0)
plt.imshow(img.numpy(), cmap="Greys")
# plt.show()
return img
else:
img = img.numpy... | Python | 1 |
::IntoDimension;
use crate::Layout;
use crate::NdProducer;
/// Window producer and iterable
///
/// See [`.windows()`](../struct.ArrayBase.html#method.windows) for more
/// information.
pub struct Windows<'a, A: 'a, D> {
base: ArrayView<'a, A, D>,
window: D,
strides: D,
}
impl<'a, A, D: Dimension> Windows... | Rust | 0 |
tic str> = Some("SELinux");
const REPLY_EXPECTS_FDS: bool = false;
type Reply = ListPropertiesReply<'static, 'static, 'static>;
}
#[derive(Clone, Debug, Default, PartialEq, PartialOrd)]
pub struct ListPropertiesReply<'r, 'p, 'q> {
pub reply_type: u8,
pub sequence: u16,
pub length: u32,
pub prope... | Rust | 0 |
following styles are available.
//!
//! - `none`
//! - `lowercase`
//! - `UPPERCASE`
//! - `snake_case`
//! - `SNAKE_CASE`
//! - `camelCase`
//! - `CamelCase`
//! - `kebab-case`
//! - `KEBAB-CASE`
//! - `Title Case`
//! - `Title case`
//! - `title case`
//! - `TITLE CASE`
//!
//! ```rust
//! use parse_display::{Displa... | Rust | 0 |
alysis['risk_score']}/100 ({analysis['risk_level']})"],
["Compliance Score:", f"{analysis['compliance_score']}/100"],
["Critical Violations:", str(len([v for v in analysis['violations'] if v['severity'] == 'CRITICAL']))],
["Total Violations:", str(len(analysis['violations']))],
... | Python | 1 |
# -*- coding: utf-8 -*-
# Scrapy settings for belle project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/... | Python | 1 |
/*
let min = if let Some(mi) = search.min {
format!("{}", mi.0.format("%Y-%m-%d %H:%M:%S"))
} else {
String::new()
};
let max = if let Some(mi) = search.min {
format!("{}", mi.0.format("%Y-%m-%d %H:%M:%S"))
} else {
String::new()
};
*/
if let Some(q)... | Rust | 0 |
"Starting address (0x{:x}) is out of range, ignoreing",
region.1
);
continue;
}
flash_dataframe(&mut self.serial, ®ion.0, region.1 as u32).await?;
}
// Boot the program
... | Rust | 0 |
// ```
///
/// ## A so-called unit struct
///
/// ```
/// struct JustAMarker;
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde",
serde(bound(
serialize = "T::Type: Serialize, T::String: Serialize",
deserialize = "T::Type: DeserializeOwned, T::St... | Rust | 0 |
error!("drop_table err");
error!("{:?}", result.err().unwrap());
return Err(ErrorKind::PostgresErr.into());
} else {
trace!("drop_table was successful");
return Ok(());
}
}
fn create_table(&self, table_name: String, columns: BTreeMap<String, String>) -> Result<()> {
trace!("... | Rust | 0 |
limited-xml-serialize")]
Error::XmlError(e) => match other {
Error::XmlError(ee) => format!("{:?}", e) == format!("{:?}", ee),
_ => false,
},
Error::TypeDoesNotSupportSerialization(e) => match other {
Error::TypeDoesNotSupportSerializat... | Rust | 0 |
.entries[..] {
// SAFETY: We hold the lock here, as required
unsafe { bucket.mutex.unlock() };
}
}
/// Iterate through all `ThreadData` objects in the bucket and insert them into the given table
/// in the bucket their key correspond to for this table.
///
/// # Safety
///
/// The given `bucket` mu... | Rust | 0 |
, input0) = tx_input_gen_no_signature();
let tx = Transaction {
inputs: vec![input0],
//A 0 value output burns this output forever!
outputs: vec![TransactionOutput::new_pubkey(0, H256::from(alice_pub_key))],
time_lock: Default::default(),
}
.sign_u... | Rust | 0 |
def forward(
self, embeddings: torch.Tensor, labels: Optional[torch.Tensor] = None
) -> torch.Tensor:
logits = self.linear(embeddings) / (self.temperature + self.eps)
if labels is not None:
loss = self.compute_loss(logits, labels)
else:
loss = None
... | Python | 1 |
ERROR: type should be string, got " https://github.com/davidsandberg/facenet/blob/master/src/train_tripletloss.py#L296\n all = (neg_dists - pos_dists < margin).cpu().numpy().flatten()\n valid_triplets = np.where(all == 1)\n\n anc_valid_embeddings = anc_embeddings[valid_triplets]\n pos_valid_embeddings = pos_embeddings[valid_triplets]\n neg_valid_embeddings = neg_embeddings[valid_triplets]\n\n # Calculate triplet loss\n triplet_loss = TripletLoss(margin=margin).forward(\n anchor=anc_valid_embeddings,\n positive=pos_valid_embeddings,\n negative=neg_valid_embeddings\n )\n\n # Calculating number of triplets that met the triplet selection method during the epoch\n num_valid_training_triplets += len(anc_valid_embeddings)\n\n # Backward pass\n optimizer_model.zero_grad()\n triplet_loss.backward()\n optimizer_model.step()\n\n # Print training statistics for epoch and add to log\n print('Epoch {}:\\tNumber of valid training triplets in epoch: {}'.format(\n epoch,\n num_valid_training_triplets\n )\n )\n\n with open('logs/{}_log_triplet.txt'.format(model_architecture), 'a') as f:\n val_list = [\n epoch,\n num_valid_training_triplets\n ]\n log = '\\t'.join(str(value) for value in val_list)\n f.writelines(log + '\\n')\n\n # Evaluation pass on LFW dataset\n best_distances = validate_lfw(\n model=model,\n lfw_dataloader=lfw_dataloader,\n model_architecture=model_architecture,\n epoch=epoch\n )\n\n # Save model checkpoint\n state = {\n 'epoch': epoch,\n 'embedding_dimension': embedding_dimension,\n 'batch_size_training': batch_size,\n 'model_state_dict': model.state_dict(),\n 'model_architecture': model_architecture,\n 'optimizer_model_state_dict': optimizer_model.state_dict(),\n 'best_distance_threshold': np.mean(best_distances)\n }\n\n # For storing data parallel model's state dictionary without 'module' parameter\n if flag_train_multi_gpu:\n state['model_state_dict'] = model.module.state_dict()\n\n # Save model checkpoint\n torch.save(state, 'model_training_checkpoints/model_{}_triplet_epoch_{}.pt'.format(\n model_architecture,\n epoch\n )\n )\n\n\nif __name__ == '__main__':\n main()\n" | Python | 1 |
# Copyright 2024 The TensorFlow 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 applica... | Python | 1 |
/// Registers passes that attempt to legalize the generated code.
///
/// Note: this recipe is specially designed for legalizing SPIR-V. It should be
/// used by compilers after translating HLSL source code literally. It should
/// *not* be used by general workloads for performance or size improveme... | Rust | 0 |
lista = [2, 4, 6, 8, 10]
result = len(lista * 3)
print(f"{result}") | Python | 1 |
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 9000);
let noticeboard = NoticeboardService {
notes: Arc::new(vec![
Note {
title: "Hello".to_string(),
content: "Thi... | Rust | 0 |
var_4637) = &input.allocation_id {
scope_4636.string(var_4637);
}
#[allow(unused_mut)]
let mut scope_4638 = writer.prefix("DomainName");
if let Some(var_4639) = &input.domain_name {
scope_4638.string(var_4639);
}
#[allow(unused_mut)]
let mut scope_4640 = writer.prefix("DryRun... | Rust | 0 |
t::TestRequest::get()
.uri("/software_builds?name=Kevin%27s%20SoftwareBuild")
.to_request();
println!("{:?}", req);
let resp = test::call_service(&mut app, req).await;
assert_eq!(resp.status(), http::StatusCode::UNPROCESSABLE_ENTITY);
let result = test::read_bod... | Rust | 0 |
batch_vllm_engine_call(vllm_engines, "wake_up")
torch.distributed.barrier()
torch.cuda.synchronize()
trainer._broadcast_to_vllm()
# vLLM offload when vllm_enable_sleep
if self.strategy.args.vllm_enable_sleep:
batch_vllm_engine_call(vllm... | Python | 1 |
# Copyright (c) 2021 - present / Neuralmagic, 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/LICENSE-2.0
#
# Unless required b... | Python | 1 |
_state.get_key() {
let value = local_state.get_latest_value();
self.local_state.insert(key.clone(), to_bin(value).unwrap());
}
}*/
/*pub fn insert_local_state_from_key_value<T: Serialize + Clone + Debug>(&mut self, key: &StateKey, value: &T) {
self.local_state.insert(key... | Rust | 0 |
lf.env.curr_states[i].orientation,
self.env.goal_locations[i][0][0],
reservation
)
if path:
print("current location:", path[0][0], "current direction:", path[0][1])
if path[0][0] != self.env.curr_states[i].l... | Python | 1 |
sage, LF,
};
use anyhow::{anyhow, bail, Context, Result};
use log::{debug, error, trace};
use std::{
collections::{HashMap, VecDeque},
mem, str,
};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
net::{
tcp::{OwnedReadHalf, OwnedWriteHalf},
TcpStream, ToSocketAddrs,
},
... | Rust | 0 |
fault";
pub const MEDIA_SUPPORTED: &str = "media-supported";
pub const PAGES_PER_MINUTE: &str = "pages-per-minute";
pub const COLOR_MODE_SUPPORTED: &str = "color-mode-supported";
pub const PRINT_COLOR_MODE_SUPPORTED: &str = "print-color-mode-supported";
const HEADER_ATTRS: [&str; 3] = [ATTRIBUTES_CHARSET, ATTRIBUTES_N... | Rust | 0 |
D3: [PB5<Alternate<AF12>>]
}
#[derive(Copy, Clone)]
pub enum Buswidth {
Buswidth1 = 0,
Buswidth4 = 1,
}
enum PowerCtrl {
Off = 0b00,
On = 0b11,
}
/// Clock frequency of a SDIO bus.
pub enum ClockFreq {
F24Mhz = 0,
F16Mhz = 1,
F12Mhz = 2,
F8Mhz = 8,
F4Mhz = 10,
F1Mhz = 46,
... | Rust | 0 |
import requests
import json
import time
import pandas as pd
# 1. 基本设置
base_url = "https://gs.amac.org.cn/amac-infodisc/api/pof/manager/query"
payload = {
"primaryInvestType": "smzqtzjjglr",
"fundType": "smzqzzfx",
"fundScale": "scope03",
"establishDate": {"from": "1900-01-01", "to": "9999-01-01"},
... | Python | 1 |
n.lower()
or keyword.lower() in event.category.lower()
):
matched_events.append(event)
if not matched_events:
print(f"🎉 没有找到包含 '{keyword}' 的日程")
return
print(f"📊 找到 {len(matched_events)} 个匹配的日程:\n")
for i, event in enumerate... | Python | 1 |
/// `fmt::Debug` with the `bitfield_debug` macro.
///
/// The difference with calling those macros separately is that `bitfield_fields` is called
/// from an appropriate `impl` block. If you use the non-slice form of `bitfield_bitrange`, the
/// default type for `bitfield_fields` will be set to the wrapped fields.
///... | Rust | 0 |
TL_VLDO_0_90V => 18,
SYSCTL_LDOSPCTL_VLDOW::SYSCTL_LDOSPCTL_VLDO_0_95V => 19,
SYSCTL_LDOSPCTL_VLDOW::SYSCTL_LDOSPCTL_VLDO_1_00V => 20,
SYSCTL_LDOSPCTL_VLDOW::SYSCTL_LDOSPCTL_VLDO_1_05V => 21,
SYSCTL_LDOSPCTL_VLDOW::SYSCTL_LDOSPCTL_VLDO_1_10V => 22,
SYSCTL_LDOS... | Rust | 0 |
in str(e)
# Any other error (like "not a video file") is acceptable for this test
@pytest.mark.network
def test_video_reader_keep_av_open_with_urls():
"""Test keep_av_open parameter works with URLs."""
test_url = "https://httpbingo.org/status/200"
try:
# Test with keep_av_open=True
... | Python | 1 |
# Import necessary modules and classes
import numpy as np
class JointEffortController:
def __init__(
self,
physics,
joints,
min_effort: np.ndarray,
max_effort: np.ndarray,
) -> None:
self._physics = physics
self._joints = joints
self._min_effort ... | Python | 1 |
b.glob(os.path.join(self.path.path, "*/")):
subdirpath = os.path.join(self.path.path, subdir)
for module_path in _get_child_project_paths(subdirpath):
module = self.__class__(module_path)
modules.append(module)
return modules
def _get_items_from_cspro... | Python | 1 |
def __div__(t: float) -> ConstDQuaternionExpression: pass
##
# \brief Returns the result of the division operation <tt>self / e</tt>.
# \param e Specifies the divisor.
# \return A \c %ConstDQuaternionExpression instance holding the result of the division.
#
def __div__(e: ConstDQuaternio... | Python | 1 |
rStatusProfile {
static instance: ::protobuf::rt::LazyV2<BreakerStatusProfile> = ::protobuf::rt::LazyV2::INIT;
instance.get(BreakerStatusProfile::new)
}
}
impl ::protobuf::Clear for BreakerStatusProfile {
fn clear(&mut self) {
self.statusMessageInfo.clear();
self.breaker.clear()... | Rust | 0 |
i8::from_be_bytes([data[i + 1]]),
), // Y pos of part relative to my head
u16::from_be_bytes([data[i + 2], data[i + 3]]),
); // snake ID
i += 4;
}
let my_position = (
u16::from_be_bytes([data[i], data[i + 1]]),
... | Rust | 0 |
me, description, authors, manual section).
man_pages = [
(master_doc, 'phoenixdb', u'phoenixdb Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree i... | Python | 1 |
# coding=utf-8
import pycnml
import time
import numpy as np
import struct
import os
class MNIST_MLP(object):
def __init__(self):
# set up net
self.net = pycnml.CnmlNet(16)
self.input_quant_params = []
self.filter_quant_params = []
def build_model(self, batch_size=100, input... | Python | 1 |
Some(&mut len), Some(ptr));
assert_eq!(success, 0);
assert!(len <= result.capacity());
unsafe {
result.set_len(len);
}
String::from_utf8(result).unwrap()
};
assert_eq!(want, &got);
}
let success = mangling_mangle(1, No... | Rust | 0 |
nary_cross_entropy_with_logits(
cls_pred, torch.zeros_like(cls_pred), reduction='none')
cls_cost = torch.einsum('nc,mc->nm', pos, gt_labels) + \
torch.einsum('nc,mc->nm', neg, 1 - gt_labels)
cls_cost = cls_cost / n
return cls_cost
def __call__(self,
... | Python | 1 |
vate_key, node_address
# ===== 主函数 =====
if __name__ == "__main__":
# 初始化两个节点(模拟比特币网络)
node1_port = 5001
node2_port = 5002
print("Initializing Node 1...")
blockchain1, priv_key1, address1 = initialize_node(node1_port)
print("\nInitializing Node 2...")
blockchain2, priv_key2, address... | Python | 1 |
!(t_kzg);
valid
}
}
<filename>src/lock.rs
use std::{cell::UnsafeCell, sync::atomic::Ordering};
use crate::{
base_node::{BaseNode, Node},
utils::ArtError,
};
pub(crate) struct ConcreteReadGuard<'a, T: Node> {
version: usize,
node: &'a UnsafeCell<T>,
}
impl<'a, T: Node> ConcreteReadGuard<'a... | Rust | 0 |
import pickle
from Clock_20_1 import Clock
import pickle as pick # zapisywanie do pliku
zegarek1 = Clock(10, 11, 12)
zegarek1.addTime(2, 150, 50)
print(zegarek1)
# zapisujemy objekt do pliku
file = open("zegarek.objc", 'wb') # .objc otwieramy obiekt, wb a nie w bo to nie jest string tylko obiekt - prawa do zapisu... | Python | 1 |
ui_font_atlas_image_view.clone(),
))
}
fn feature_debug_name(&self) -> &'static str {
ImGuiRenderFeature::feature_debug_name()
}
fn feature_index(&self) -> RenderFeatureIndex {
ImGuiRenderFeature::feature_index()
}
}
// Copyright 2021 The Fuchsia Authors. All rights reserve... | Rust | 0 |
# Consider an implementation of a linked list, where each node is created using the given class Node. Suppose it has a head variable that contains the reference to the first node of the linked list.
# You are given a non-empty linked list with n nodes, where these nodes are sorted in ascending order of their value. Yo... | Python | 1 |
)
self.assertEqual('1.1.1.1', inner_layer.introduction_points[0].link_specifiers[0].address)
@test.require.cryptography
def test_descriptor_creation(self):
"""
HiddenServiceDescriptorV3 creation.
"""
# minimal descriptor
self.assertTrue(HiddenServiceDescriptorV3.content().startswith(b'hs-... | Python | 1 |
/module
alloc::module alloc/module/index.html alloc/core/module
# len() > 2
# search for index.html in rel_path
std::AAA::MMM std/AAA/MMM/index.html root/std/AAA/MMM
# OR check if parent() dir exists and search for fn/sturct/etc
std::AAA::FFF std/AAA/fn.FFF9.html root/std/AAA
std... | Rust | 0 |
from __future__ import absolute_import, division, print_function
import sys
import os
import shutil
from libtbx.option_parser import option_parser
import libtbx.file_clutter
def clean_clutter_in(files, tabsize=8):
if not files: return
for fname in files:
tmpname = fname + '.bak'
if os.path.isfile(tmpname):... | Python | 1 |
= 12,
DepthGreater = 13,
DepthLess = 14,
DepthUnchanged = 15,
LocalSize = 16,
LocalSizeHint = 17,
InputPoints = 18,
InputLines = 19,
InputLinesAdjacency = 20,
Triangles = 21,
InputTrianglesAdjacency = 22,
Quads = 23,
Isolines = 24,
OutputVertices = 25,
OutputPoint... | Rust | 0 |
this is needed to be compatible with the automerge-js api
#[wasm_bindgen(js_name = importSyncState)]
pub fn import_sync_state(state: JsValue) -> Result<SyncState, JsValue> {
Ok(SyncState(JS(state).try_into()?))
}
// this is needed to be compatible with the automerge-js api
#[wasm_bindgen(js_name = exportSyncState... | Rust | 0 |
p")
self._Page = params.get("Page")
self._PolicyType = params.get("PolicyType")
self._Keyword = params.get("Keyword")
memeber_set = set(params.keys())
for name, value in vars(self).items():
property_name = name[1:]
if property_name in memeber_set:
... | Python | 1 |
, size: {image.size}, mode: {image.mode}")
else:
raise TypeError(f"Unsupported image type: {type(image)}")
else:
print(f"Input image is already a PIL Image, size: {image.size}, mode: {image.mode}")
base_dir = os.path.dirname(os.path.abspath(__file__))
w... | Python | 1 |
length {}", pub_input.len(), i, vk.num_inputs)
)
.into());
}
if vk.plookup_vk.is_some() != batch_proof.plookup_proofs_vec[i].is_some() {
return Err(ParameterError(format!(
"Mismatched proof type and verification key type for th... | Rust | 0 |
verse_direction
and (
(has_secondary and element in lookup)
or (not has_secondary and "remote" in element._annotations)
)
):
if element not in binds:
binds[element] = sql.bindparam(
... | Python | 1 |
on page178).
pub mod BSEC_OTP_WRLOCK2 {
pub use super::BSEC_OTP_WRLOCK0::WRLOCK;
}
/// BSEC_OTP_SPLOCK0 is used to lock the programming of BSEC_OTP_DATA0 to BSEC_OTP_DATA31 until next system-reset BSEC_OTP_SPLOCK1 is used to lock the programming of BSEC_OTP_DATA32 to BSEC_OTP_DATA63 until next system-reset BSEC_O... | Rust | 0 |
address| Self::check_and_report(&checker, &reporter, address))
.collect();
let results = future::join_all(futs).await;
for r in results.into_iter() {
if let Err(err) = r {
error!("faild to check and report error: {:?}", err);
... | Rust | 0 |
# Copyright 2015 Google 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/LICENSE-2.0
#
# Unless required by applicable law or a... | Python | 1 |
day_year: default_bday_year(),
location: default_location(),
}
}
}
use regex::Regex;
use std::collections::HashMap;
struct Instruction {
action: u32,
x_start: u32,
y_start: u32,
x_end: u32,
y_end: u32,
}
const MATRIX_SIDE: u32 = 1000;
const TURN_ON: u32 = 0;
const TOGGLE: u... | Rust | 0 |
[wasm_bindgen(constructor)]
pub fn new(arr: &Uint8ClampedArray, width: u32, height: u32) -> ImageData;
}
#[wasm_bindgen]
extern "C" {
pub type Uint8ClampedArray;
#[wasm_bindgen(constructor)]
pub fn new(arr: &[u8]) -> Uint8ClampedArray;
}
#[wasm_bindgen]
extern "C" {
pub type CanvasRenderingContex... | Rust | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/licenses/gpl.txt
from pisi.actionsapi import cmaketools
from pisi.actionsapi import get
#from pisi.actionsapi import pisitools
# if pisi can't find source directory, see /var/pisi/... | Python | 1 |
# coding=utf-8
import copy
from mycodo.inputs.base_input import AbstractInput
# Measurements
measurements_dict = {
0: {
'measurement': 'temperature',
'unit': 'C'
},
1: {
'measurement': 'humidity',
'unit': 'percent'
}
}
# Input information
INPUT_INFORMATION = {
'inp... | Python | 1 |
elicApiRetry)
.service(NewRelicApiService { client });
let sink = NewRelicSink {
service,
acker: cx.acker(),
encoding,
credentials,
compression: self.compression,
batcher_settings,
};
Ok((super::VectorSink::fro... | Rust | 0 |
{
pub name: String,
pub version: Version,
pub filename: String,
pub directory: PathBuf,
pub core_clr: bool,
}
impl Package {
pub fn new(config: &Config, version: &Version) -> Self {
let name = if config.use_coreclr {
"Cake.CoreClr"
} else {
"Cake"
... | Rust | 0 |
::RLIMIT_SIGPENDING),
12 => Ok(resource_t::RLIMIT_MSGQUEUE),
13 => Ok(resource_t::RLIMIT_NICE),
14 => Ok(resource_t::RLIMIT_RTPRIO),
_ => return_errno!(EINVAL, "invalid resource"),
}
}
}
pub fn do_prlimit(
pid: pid_t,
resource: resource_t,
new_lim... | Rust | 0 |
return _resolve_local_time(
local_naive,
tzid,
zone,
ambiguous=ambiguous,
nonexistent=nonexistent,
)
def to_utc_with_timezone(
local_naive: datetime,
tzid: str,
*,
ambiguous: FoldPolicy = "earliest",
nonexistent: GapPolicy = "post",
policy: Policy |... | Python | 1 |
import os
import numpy as np
from PIL import Image
def calculate_iou(image1, image2):
image1_array = np.array(image1) > 0
image2_array = np.array(image2) > 0
intersection = np.logical_and(image1_array, image2_array).sum()
union = np.logical_or(image1_array, image2_array).sum()
iou = intersection ... | Python | 1 |
r,
),
)
CloseMessageWindow()
def _loc_97BF(): pass
label('loc_97BF')
Jump('loc_99A9')
def _loc_97C2(): pass
label('loc_97C2')
If(
(
(Expr.Eval, "OP_29(0x0069, 0x01, 0x0008)"),
Expr.Return,
),
'loc_9822',
)
ChrTalk(
... | Python | 1 |
t unchecked code - which includes unsafe Rust and Python - is validated by its author
//! which together with the dynamic borrow checking performed by this crate ensures that
//! safe Rust code cannot cause undefined behaviour by creating references into NumPy arrays.
//!
//! With these borrows established, [references... | Rust | 0 |
is.get_initial_size();
PositionedFrame {
rect: Rect::new(
(MEM_DISP_WIDTH + SCREEN_BUFFER_SIZE_X as i32) as i32 + 5,
0,
w,
h,
),
scale: 1.0,
vis: Box::new(vis),
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.