text string | label_name string | labels int64 |
|---|---|---|
d().execute_with(|| {
let user = ALICE;
let vault = BOB;
let collateral_vault = 1_000_000;
let total_polka_btc = 1_000_000;
let polka_btc = 1_000;
let user_btc_address = BtcAddress::P2PKH(H160([2; 20]));
SystemModule::set_block_number(1);
assert_ok!(Exc... | Rust | 0 |
he License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------------
*/
use super::InternalGraphics;
use crate::{colors, mutexes::Mutex, Color, GeometricArc, Window};
use core::convert::TryInto;
use cty::... | Rust | 0 |
n> = LedHigh::new(PB7_PIN);
pub const LED2: LedHigh<GpioPin> = LedHigh::new(PB14_PIN);
pub fn init() {
PB0.port().gate_enable();
PB0.mode_output();
PB7.port().gate_enable();
PB7.mode_output();
PB14.port().gate_enable();
PB14.mode_output();
}
impl GetLed for ::Board {
fn get_led(&self, in... | Rust | 0 |
import py
import sys
from rsqueakvm import objspace, error, constants
# from rsqueakvm.model.variable import W_BytesObject
from rpython.rlib.rarithmetic import r_uint, r_longlong
from .util import create_space, copy_to_module, cleanup_module
def setup_module():
space = create_space(bootstrap = True)
copy_t... | Python | 1 |
*a.add(2), &*a) {
ptr::copy_nonoverlapping(a, &mut swap, 1);
ptr::copy_nonoverlapping(a.add(1), a, 1);
ptr::copy_nonoverlapping(&swap, a.add(1), 1);
} else if is_less(&*a.add(2), &*a.add(1)) {
ptr::copy_nonoverlapping(a, &mut swap, 1);
ptr::copy_nonove... | Rust | 0 |
w.period)
for attr in ['perHour', 'vehsPerHour']:
if flow.hasAttribute(attr):
period = 3600 / float(flow.getAttributes(attr))
if period > 0:
return math.ceil(duration / period)
else:
return 1
def intIfPossible(val):
if int(val) == val:
... | Python | 1 |
isicos/<int:pk>/edit/', views.InventarioFisicoUpdateView.as_view(), name='inventariofisico_edit'),
path('inventarios-fisicos/<int:pk>/delete/', views.InventarioFisicoDeleteView.as_view(), name='inventariofisico_delete'),
# URLs para Reportes
path('reportes/', views.InventoryReportsView.as_view(), name=... | Python | 1 |
import numpy as np
import time as time
from net_represent import *
from min_span_tree import *
from search import *
from tree_plot import *
from str_reduc import *
###############################################################
### Experimento numérico: armazenamento de imagens binárias ###
##########################... | Python | 1 |
.0),
/// );
/// a[0] = vec4!(15.0, 16.0, 17.0, 18.0);
/// a[1] = vec4!(25.0, 26.0, 27.0, 28.0);
/// a[2] = vec4!(35.0, 36.0, 37.0, 38.0);
/// a[3] = vec4!(45.0, 46.0, 47.0, 48.0);
///
/// let b = mat4!(
/// vec4!(15.0, 16.0, 17.0, 18.0),
/// vec4!(25.0, 26.0, 27.0, 28.0),
... | Rust | 0 |
# PQAEF/PQAEF/models/classification_model.py
from typing import List, Dict, Any, Union
import torch
from .base_model import BaseModel
try:
from transformers import AutoModelForSequenceClassification, AutoTokenizer
except ImportError:
AutoModelForSequenceClassification = AutoTokenizer = torch = None
class Cla... | Python | 1 |
"""
Sample Input:
2
12
1012
Sample Output:
2
3
"""
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'findDigits' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER n as parameter.
#
def findDigits(n):
# Wr... | Python | 1 |
terms.
#[inline(never)]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[inline(never)]
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
#[inline(never)]
pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}
#[inline(never)]
pub fn divide(a: i32, b: i32) -> i32 {
a / b
}
#[inline(never)]
pub fn divide_no_... | Rust | 0 |
.map_err(|e| e.into_send_error())
},
AllMessages::ApprovalVoting(msg) => {
self.approval_voting_unbounded
.unbounded_send(make_packet(signals_received, msg))
.map_err(|e| e.into_send_error())
},
AllMessages::GossipSupport(msg) => {
self.gossip_support_unbounded
.unbounded_send(make_p... | Rust | 0 |
from openmm.app import *
from openmm import *
from openmm.unit import *
from sys import stdout
# Read the PSF
psf = CharmmPsfFile('ala_ala_ala.psf')
# Get the coordinates from the PDB
pdb = PDBFile('ala_ala_ala.pdb')
# Load the parameter set.
params = CharmmParameterSet('charmm22.rtf', 'charmm22.par')
# NOTICE:
# -... | Python | 1 |
class Solution:
def reverse(self, x: int) -> int:
m = True
if x < 0:
m = False
x = x*-1
sum1 = 0
for i in range(len(str(x))):
sum1 += (10**(len(str(x))-1-i))*(int(str(x)[-i-1]))
if sum1 < (2**31) -1 and sum1 > -2**31 :
if m ... | Python | 1 |
8e\xf2[I\x18\x96++*\x82F\
\x1b\xe6'\x19\x19!xS\x82p2\x09#h<\xfa\
G\x84\xaeQ\x04\x8c\xf2\x0c:\xe5\xd4\x82\x9bH\xe8~\
b\xde\xc7\x00~8\xc0nlN\x1e){D\xf9n\
\x97\xbc\x95\x9ce\xe9~\xbd5\xda\xfa=\x0e\x9c%e\
\x19\xc5II5)9^N\xdd7V\xd6\xd6z\xa6\
\xb7\xf5k\xd6Yl7\x12%\x93\xafn\x06{\xe0\x05\
\x0c\xe7\x1c\x9f\xa9\xa2\xb1\xc3\x8c\x... | Python | 1 |
, cursor, self.v_needed.to_le_bytes());
array_push!(array, cursor, self.flags.to_slice());
array_push!(array, cursor, self.compression.to_le_bytes());
array_push!(array, cursor, self.mod_time.to_le_bytes());
array_push!(array, cursor, self.mod_date.to_le_bytes());
array_push!(arr... | Rust | 0 |
import torch
from torch.fx.passes.infra.pass_base import PassBase, PassResult
class _RemoveRuntimeAssertionsPass(PassBase):
"""
Remove runtime assertions inserted by the
_AddRuntimeAssertionsForInlineConstraintsPass.
"""
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
mo... | Python | 1 |
ues: *mut *mut _json_value,
}
impl Clone for _json_value__bindgen_ty_1__bindgen_ty_3 {
fn clone(&self) -> Self {
*self
}
}
impl Clone for _json_value__bindgen_ty_1 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[derive(Debug, Copy)]
pub struct _json_value__bindgen_ty_2 {
pub next_... | Rust | 0 |
test))
x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
np.arange(y_min, y_max, 0.1))
f, axarr = plt.subplots(1, 2, sharex='col', sharey='row', figsize=(8, 3))
for ... | Python | 1 |
ptr::read(&val as *const ruby::VALUE as *const O)),
_ => Err(AnyException::_take_current()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn panic() {
crate::vm::init().unwrap();
struct DropAndPanic;
impl Drop for DropAndPanic {
fn drop(&mut self) {
... | Rust | 0 |
for sku_detail in sku_details:
if sku_detail['packageType'] == '零货':
dt_item = {
"amount": 175000000,
"assignedLot": f"{sku_detail['productionBatch']}",
"productDate": f"{sku_detail['productionDate']... | Python | 1 |
:%S.%f%z', # ISO 8601 带毫秒: 2024-09-10T12:30:00.000+0000
'%Y-%m-%d %H:%M:%S', # 标准格式: 2024-09-10 12:30:00
'%Y/%m/%d %H:%M:%S', # 斜杠日期: 2024/09/10 12:30:00
'%d %b %Y %H:%M:%S', # 10 Sep 2024 12:30:00
'%Y-%m-%d', # 仅日期: 2024-09-10
... | Python | 1 |
from typing import List
from .base_agent import HypothesisOut, ExperimentPlanOut, get_llm
class ExperimentAgent:
def __init__(self):
self.llm = get_llm()
def run(self, run_id: str, hypotheses: List[HypothesisOut]) -> List[ExperimentPlanOut]:
if not hypotheses:
return []
p... | Python | 1 |
import os
from kivymd.uix.screen import MDScreen
from View.MenuScreen.componemts import MenuCard # NOQA
class MenuScreenView(MDScreen):
def on_enter(self, *args) -> None:
if not self.ids.menu_list.data:
manu_list = [
"Field",
"Card",
"Button",... | Python | 1 |
ansitive_hits(splits_data_cp, use_cache=False)
@pytest.fixture
def split_leakage_test_data():
return {
"pure_split": {
"HIJK__A1_ABC123--HIJK__B1_ABC456",
"KILL__A1_BILL123--KILL__B1_BILL456",
"ABCD__A1_BILL012--ABCD__B1_BILL345",
"WXYZ__A1_B0L2012--WXYZ__B1... | Python | 1 |
AULT_CREATURE_MINIMUM: usize = 60;
/// The coldest it is going to get.
pub const DEFAULT_MIN_TEMP: f64 = -0.5;
/// The hottest it is going to get.
pub const DEFAULT_MAX_TEMP: f64 = 0.7;
/// Used for terrain generation.
pub const DEFAULT_NOISE_STEP_SIZE: f64 = 0.1;
// ************************* //
// ******** DRAWING... | Rust | 0 |
Type::from(&*from)
}
}
impl<'a> From<&'a str> for LanguageType {
fn from(from: &str) -> Self {
match &*from {
{{~#each languages}}
{{~#if this.name}}
"{{~this.name}}"
{{else}}
"{{~@key}}"
{{~/if}}
... | Rust | 0 |
bits. 128-bit key of Flash Encryption"
)
BLOCK_KEY0_LOW_128.read_disable_bit = efuse.read_disable_bit[0]
self.KEYBLOCKS.append(BLOCK_KEY0_LOW_128)
BLOCK_KEY0_HI_128 = copy.deepcopy(efuse)
BLOCK_KEY0_HI_128.name = "BLOCK_KEY0_HI_128"
... | Python | 1 |
# SPDX-FileCopyrightText: Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Test Backforward widget."""
import pytest
from qutebrowser.mainwindow.statusbar import backforward
@pytest.fixture
def backforward_widget(qtbot):
widget = backforward.Backforward()
... | Python | 1 |
import os
import sys
import json
import time
import pickle
import logging
import random
import pandas as pd
from typing import Any, List, Optional, Sequence
__all__ = [
"batches",
"dispatch_tqdm",
'WarnInfo',
'getNowDate',
'convertColToList',
'convertDictToDataFrame',
'getFolders',
'sa... | Python | 1 |
"""Module for utility functions for the convolutional layer."""
import torch
def check_point(x, current_stride, dim):
"""
Check if the point is in the current stride.
:param torch.Tensor x: The input data.
:param int current_stride: The current stride.
:param int dim: The shape of the filter.
... | Python | 1 |
dev,
real_file.st_ino,
None,
Some(km),
Some(emufile.clone()),
None,
None,
);
write_mapped_data(
remote.task().as_replay_task().unwrap(),
rec_addr,
km.len(),
data,
);
log!(
LogDebug,
" restored {} bytes at ... | Rust | 0 |
Err(e) => {
// Pretty print the error
eprintln!("Uncaught {}", e.display());
}
};
}
<gh_stars>0
fn main() {
println!("Hello, world!");
println!("this is my first application for rust-cargo!");
}
<filename>matches/src/main.rs
#[derive(Debug)]
enum UsState {
Alaska,... | Rust | 0 |
Symbol {
name,
kind: FileSymbolKind::Macro,
container_name: s.current_container_name(),
loc: DeclarationLocation { hir_file_id: source.file_id, name_ptr, ptr },
})
})
}
fn push_file_symbol(&mut self, f: impl FnOnce(&Self) -> Op... | Rust | 0 |
from starlette.middleware.httpsredirect import ( # noqa
HTTPSRedirectMiddleware as HTTPSRedirectMiddleware,
)
| Python | 1 |
x as i16
}
};
// convolve coefficients over input and skip every other sample to half the rate
(0..input.len())
// need4speed
.into_par_iter()
// skip evey other sample to decimate input to halfrate
.filter(|i| i % 2 == 1)
.map(|i| {
/... | Rust | 0 |
import tensorflow as tf
import numpy as np
import pickle
import cv2
import argparse
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", type=str, default='../models/liveness.model',
help="path to trained model")
ap.add_argument("-i", "--source", typ... | Python | 1 |
i]))
node = getattr(self, 'node_' + str(i - startp))
layers[i] = node(layers[i] + layers[i - 1])
class NormalConv(nn.Layer):
"""Normal Conv without deformable
"""
def __init__(self, in_channels, out_channels, norm_func):
super(NormalConv, self).__init__()
self.nor... | Python | 1 |
ervice_name)
self.connection.deleteFile(self.share, self.__binary_service_name)
except Exception:
LOG.critical("Error performing the uninstallation, cleaning up" )
try:
scmr.hRControlService(self.rpcsvc, service, scmr.SERVICE_CONTROL_STOP)
except:
... | Python | 1 |
"""
智能体管理模块
负责系统智能体的管理和任务处理
"""
from .manager import AgentManager
__all__ = ["AgentManager"] | Python | 1 |
"""
sys_patch_helpers.py: Additional support functions for sys_patch.py
"""
import os
import logging
import plistlib
import subprocess
from typing import Union
from pathlib import Path
from datetime import datetime
from .. import constants
from ..datasets import os_data
from ..volume import generate_copy_argument... | Python | 1 |
[bench]
fn lookup_ordermap_100_000_multi(b: &mut Bencher) {
let map = &*OMAP_100K;
b.iter(|| {
let mut found = 0;
for key in 0..LOOKUP_SAMPLE_SIZE {
found += map.get(&key).is_some() as u32;
}
found
});
}
// inorder: Test looking up keys in the same order as they ... | Rust | 0 |
# Copyright 2022 Neal Lathia
#
# 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 agre... | Python | 1 |
term_println(term::color::YELLOW, "Executing", hook_name);
let res = Command::new(Path::new(pre).canonicalize().unwrap()).status();
if let Ok(s) = res {
if s.success() {
term_println(
term::color::BRIGHT_GREEN,
hook_name,
... | Rust | 0 |
^
///! | has multiple
///! Vec<Molecules>
///! ^
///! | has multiple
///! Vec<Structure>
use bytemuck::cast_slice;
use nalgebra_glm::{distance, length, vec3, Vec3};
use rpdb;
use rpdb::BoundingBox;
use rpdb::FromRon;
use wgpu::util::*;
use wgpu::*;
use crate::hilbert;
/// GPU represantion of a molecu... | Rust | 0 |
f.db
.layers
.pop_front()
.map(|wb| self.db.inner.write(WriteOptions::default_instance(), &wb));
}
pub fn discard_last_layer(&mut self) -> io::Result<()> {
self.db
.layers
.pop_back()
.ok_or(io::Error::new(io::ErrorKind::NotFound, ... | Rust | 0 |
import pandas as pd
import matplotlib
matplotlib.use('Agg') # 确保使用适用于无界面环境的后端
dataset="Read" ###记得修改对应的数据集
# 定义处理 One-Hot 编码的函数
def process_and_generate_one_hot(file_path, output_path, score_column='Average Score'):
# 读取 CSV 文件
df = pd.read_csv(file_path)
# 计算平均分和标准差
mean_score = df[score_column].m... | Python | 1 |
l {
self.chunk
.as_ref()
.map_or_else(|| false, |chunk| chunk.has_remaining())
}
}
impl AsyncRead for FieldReader {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut buf: &mut [u8],
) -> Poll<Result<usize, std::io::Error>> {
log::debug!("poll_read into {} bytes", buf.len());
// sel... | Rust | 0 |
al_feat is not None else None
self.point_dim = point_dim
in_channels = len(self.global_feat) * in_channels if global_feat is not None else in_channels
if mlps is not None:
mlps = [in_channels] + mlps + [num_classes]
else:
mlps = [in_channels, num_classes]
... | Python | 1 |
TAIL 2) (HEAD 2) (3 (TAIL 2))) I)
///
/// # Example
/// ```
/// use lambda_calculus::data::list::pair::last;
/// use lambda_calculus::*;
///
/// let list = vec![1.into_church(), 2.into_church(), 3.into_church()].into_pair_list();
///
/// assert_eq!(beta(app(last(), list), NOR, 0), 3.into_church());
/// ```
pub fn last(... | Rust | 0 |
ockByHash(Data32, Boolean) -> Block;
fn getBlockByNumber(BlockNumber, Boolean) -> Block;
fn getTransactionReceipt(Data32) -> Receipt;
fn getLogs(Filter) -> Vec<Log>;
fn call(CallRequest, BlockNumber) -> Data;
fn getTransaction(Data32) -> RpcTransaction;
fn getTransactionC... | Rust | 0 |
gas_price += web3.to_wei(5, 'gwei')
print(f" {Colors.RED}🔥 授权交易Gas不足,增加Gas价格至 {web3.from_wei(gas_price, 'gwei')} gwei并重试...{Colors.RESET}")
else:
print(f" {Colors.RED}❌ 授权过程中发生错误: {e}{Colors.RESET}")
return False
def swap_tokens_for_eth(account, private_k... | Python | 1 |
s ok, encoding_from_whatwg_label only matches in the ASCII range.
match encoding_from_whatwg_label(unsafe { str::raw::from_utf8(value.as_slice()) }) {
Some(encoding) => encoding_override = encoding,
None => (),
}
use_charset = false... | Rust | 0 |
# 对于私聊消息,使用from_user_id作为发送者ID
if not cmsg.sender_wxid and not cmsg.is_group:
cmsg.sender_wxid = cmsg.from_user_id
cmsg.is_group = False
# 设置actual_user_id和actual_user_nickname
cmsg.actual_user_id = cmsg.sender_wxid or cmsg.from_user_id
cmsg.actual_... | Python | 1 |
}
}
VIRTIO_VIDEO_CMD_RESOURCE_CREATE => {
let virtio_video_resource_create {
queue_type,
resource_id,
planes_layout,
num_planes,
plane_offsets,
..... | Rust | 0 |
arrays: &[impl AsRef<ArrayImpl>],
logical_rows: &[(usize, usize)],
) {
match self {
$(
Self::$Abc(builder) => {
let typed_arrays = arrays
.iter()
... | Rust | 0 |
raise ValueError('criterion should be either bic or aic')
R = y[:, np.newaxis] - np.dot(X, coef_path_) # residuals
mean_squared_error = np.mean(R ** 2, axis=0)
sigma2 = np.var(y)
df = np.zeros(coef_path_.shape[1], dtype=np.int) # Degrees of freedom
for k, coef in enume... | Python | 1 |
ryPacked.to_string(),
"DELTA_BINARY_PACKED"
);
assert_eq!(
Encoding::DeltaLengthByteArray.to_string(),
"DELTA_LENGTH_BYTE_ARRAY"
);
assert_eq!(Encoding::DeltaByteArray.to_string(), "DELTA_BYTE_ARRAY");
assert_eq!(Encoding::RleDictionary.to_string(), "RLE_DICTIONARY");
}
#[test]
fn test_from_encod... | Rust | 0 |
# Natural Language Toolkit: PP Attachment Corpus Reader
#
# Copyright (C) 2001-2024 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# Edward Loper <edloper@gmail.com>
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
Read lines from the Prepositional Phrase Attachment Cor... | Python | 1 |
"""
KIS-008 조건검색 및 관심종목 서비스 포트 인터페이스
Sub-Issue #102: 조건검색 및 관심종목 API 구현
조건검색 및 관심종목 정보 조회를 위한 포트를 정의합니다.
"""
from abc import ABC, abstractmethod
from src.domain.entities.watchlist_condition import (
ConditionSearchList,
ConditionSearchResult,
WatchlistGroup,
WatchlistMultiPrice,
WatchlistStocksBy... | Python | 1 |
} else {
self.height()
};
// It is safe to use the shared, lock free wrapper here because each thread
// accesses a distinct pixel row, so pixel access is never interleaved.
let output = UnsafeShared::new(output);
(0..row_count).into_par_iter().for_each(|i| {
... | Rust | 0 |
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
RequestRedeem {
redeem_id: H256,
redeemer: T::AccountId,
vault_id: DefaultVaultId<T>,
amount: Wrapped<T>,
fee: Wrapped<T>,
premium: Collateral<T>,
... | Rust | 0 |
_comm)
}
self.root = current_parent_comm.unwrap();
}
}
// https://stackoverflow.com/a/46767732
// TODO Check if there is a similar method in itertools
fn has_unique_elements<T>(iter: T) -> bool
where
T: IntoIterator,
T::Item: Eq + std::hash::Hash,
{
let mut uniq = std::collections::Has... | Rust | 0 |
ue,
False,
None,
{
"jsonrpc": "2.0",
"method": "subtract",
"params": {"minuend": 42, "subtrahend": 23},
"id": 3,
},
)
console.log("Hello, World!", "{'a': 1}", repr(console))
console.print(
{
"name": None,
... | Python | 1 |
model][img_type]['eval_metrics']['uniformed_clip']['sum'] += eval_score / CLIP_MAX
elif task in RIGHT_WRONG_TASKS:
model_type_dict[edit_model][img_type]['eval_metrics']['vlm']['num'] += 1
model_type_dict[edit_model][img_type]['eval_metrics']['vlm']['su... | Python | 1 |
replica in ReplicaIter::new() {
if replica.get_pool_name() == name {
// XXX temporary
replica.unshare().await.map_err(|err| {
Error::FailedUnshareReplica {
msg: err.to_string(),
}
})?;
... | Rust | 0 |
le(&self, body: GraphQlBody, tx_id: Option<TxId>, trace_id: Option<String>) -> PrismaResponse {
tracing::debug!("Incoming GraphQL query: {:?}", body);
match body.into_doc() {
Ok(QueryDocument::Single(query)) => self.handle_single(query, tx_id, trace_id).await,
Ok(QueryDocument::... | Rust | 0 |
# numbers = [8, 9, 10, 11]
# numbers[1] = 17
# numbers.extend([4, 5, 6])
# del numbers[0]
# numbers += numbers.copy()
# numbers.insert(3, "25")
# print(numbers)
# nums = input().split()
# new_nums = []
# for num in nums:
# new_nums.append(int(num))
# copy = new_nums.copy()
# index_max = new_nums.index(max(new_nums... | Python | 1 |
from tests.test_models import *
def test_pull_model_without_container(model_manager_no_container, capsys):
"""Test pull_model when Ollama is not running."""
result = model_manager_no_container.pull_model("test-model")
assert result is False
captured = capsys.readouterr()
assert "Failed to pull mo... | Python | 1 |
import torch.nn as nn
import torch_geometric.graphgym.register as register
from torch_geometric.graphgym import cfg
from torch_geometric.graphgym.register import register_head
@register_head('ogb_code_graph')
class OGBCodeGraphHead(nn.Module):
"""
Sequence prediction head for ogbg-code2 graph-level predictio... | Python | 1 |
fake implementations:
//! * `tls-api-stub` crate which returns an error on any operations, useful to check code compiles
//! * `tls-api-no-tls` fake implementation which returns plain sockets without TLS
//!
//! The API is provided to be compatible with both tokio and async-std.
//! Crate features:
//! * `runtime-toki... | Rust | 0 |
meBoardViewSettings {
position: Vec2d<f64>,
background_color: Color,
board_edge_color: Color,
score_position: Vec2d<f64>,
score_color: Color,
score_font_size: FontSize,
treat_color: Color,
}
impl GameBoardViewSettings {
pub fn new() -> GameBoardViewSettings {
GameBoardViewSet... | Rust | 0 |
"""satflow.train package"""
| Python | 1 |
]),
];
indices.push(counter * 4 + 1);
indices.push(counter * 4 + 0);
indices.push(counter * 4 + 3);
indices.push(counter * 4 + 1);
indices.push(counter * 4 + 3);
indices.push(counter * 4 + 2);
... | Rust | 0 |
_event = false;
let mut bidi_stream_event = false;
for e in client.events() {
if let ConnectionEvent::SendStreamWritable { stream_id } = e {
if stream_id.is_uni() {
uni_stream_event = true;
} else {
bidi_stream_event = true;
}
}... | Rust | 0 |
let block = Block::new(&buffer[..], 1);
assert!(check_zero_bits(&buffer, &block, 22, 62).is_err());
}
buffer[4 + 16] = 0;
buffer[5 + 16] = 0x10;
{
let block = Block::new(&buffer[..], 1);
assert!(check_zero_bits(&buffer, &block, 22, 62).is_err());
... | Rust | 0 |
_root);
}
assert_eq!(
print_number(&test_arena, total_idx),
"[[[[6,6],[7,6]],[[7,7],[7,0]]],[[[7,7],[7,7]],[[7,8],[9,9]]]]"
);
assert_eq!(compute_magnitude(&test_arena, total_idx), 4140);
}
#[test]
fn max_pair_magnitude() {
let in... | Rust | 0 |
InterfaceError},
state_machine_service::{
states::{
helpers::{ban_all_sync_peers, ban_sync_peer, request_headers, select_sync_peer},
sync_peers::SyncPeer,
ForwardBlockSyncInfo,
Listening,
StateEvent,
Stat... | Rust | 0 |
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**7)
N,M=map(int,input().split())
graph=[[] for _ in range(N*2+1)]
for i in range(M):
x,y=map(int,input().split())
graph[-x].append(y)
graph[-y].append(x)
stk=[]
visit=[0]*(2*N+1)
parents=[0]*(2*N+1)
scc_idx=[0]*(2*N+1)
id=1
scc_id=1
def func(no... | Python | 1 |
assert field.default is Undefined
assert field.column_type.precision == 3
assert field.column_type.scale == 2
assert field.column_type.asdecimal
def test_can_create_uuid_field():
field = UUIDField(default=uuid.uuid4)
assert isinstance(field, BaseField)
assert field.default == uuid.uuid4
... | Python | 1 |
>::new(
Sequence::default()
.push(ForDistance::new(
level_length - 1800.0,
Cycle::new(
Sequence::default()
.push(ForDistance::new(
500.0,
SetComponent::new(DiverSpawner... | Rust | 0 |
radar = radar.extract_sweeps(idx_to_process)
# Create dict with radar specifications
radar_specs = {}
radar_specs['frequency'] = dscfg['frequency'][ind_rad]
radar_specs['loss'] = dscfg['lrxh'][ind_rad] + dscfg['mflossh'][ind_rad]
radar_specs['power'] = dscfg['txpwrh'][ind_rad]
radar_specs['... | Python | 1 |
###############################################################################
# (c) Copyright 2021 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the Apache License #
... | Python | 1 |
(&inps[0], &inps[1]) {
(&Num(x), &List(ref ss)) => ss.get(x as usize).cloned().ok_or(()),
_ => unreachable!(),
},
Op::Map => match (&inps[0], &inps[1]) {
(&Func(ref f), &List(ref xs)) => Ok(List(
xs.iter()
... | Rust | 0 |
import os
import json
import tqdm
import dataset_maker
from argparse import ArgumentParser
# TODO
# 1. rename ids
# 2. upload make_dataset code
# 3. write readme.md file for constructing dataset
# 4. erase other stuff
def arg_parse():
parser = ArgumentParser()
parser.add_argument('--dataset', type=str, defa... | Python | 1 |
import json
import time
from typing import Optional, Union
import requests
from solders.signature import Signature #type: ignore
from config import RPC, client, payer_keypair
def find_data(data: Union[dict, list], field: str) -> Optional[str]:
if isinstance(data, dict):
if field in data:
return... | Python | 1 |
one_shot_method="sci_fate",
model="deterministic",
group=group,
del_2nd_moments=del_2nd_moments,
)
elif adata.uns["pp"]["experiment_type"] == "kin":
dynamics(
adata,
model="deterministic",
est_method="twostep",
... | Python | 1 |
edge\\repo\\ai_chat\\electron-live2d\\mcp-project\\news.py" # 替换为你自己的路径
try:
tools = await client.connect_to_server(server_script_path)
for tool in tools:
print(f" - tool: {tool.name}")
print(f" descr: {tool.description}")
print(f" schema: {tool.inputSchema}... | Python | 1 |
nix, not(any(target_os = "solaris", target_os = "illumos"))))]
pub(crate) fn set_reuseport(_: TcpSocket, _: bool) -> io::Result<()> {
os_required!();
}
#[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
pub(crate) fn get_reuseport(_: TcpSocket) -> io::Result<bool> {
os_required!();
}
pu... | Rust | 0 |
cookiewall_squasher_crx_id = "edibdbjcniadpccecjdfdjjppcpchdlm"
adblocker_crx_id = "cjpalhdlnbpafiamejdnhcphjbkeiagm"
# Make sure the target folder exists
dl_folder.mkdir(parents=True, exist_ok=True)
for crx_id in (cookiewall_squasher_crx_id, adblocker_crx_id):
crx_path = ... | Python | 1 |
use std::collections::HashMap;
use std::io::{stdin, Read};
fn solve_part1(ids: &[&str]) -> u32 {
let mut two_count = 0;
let mut three_count = 0;
for id in ids.iter() {
let mut hm = HashMap::new();
for letter in id.chars() {
*hm.entry(letter).or_insert(0) += 1;
}
... | Rust | 0 |
= cvec![(x,y, z); x <- 1..=n, y <- x..=n, z <- y..=n];
assert_eq!(expected, test);
}
#[test]
fn cvec_haskell_3_nested_with_conditional() {
let expected = vec![(3, 4, 5), (6, 8, 10)];
let n: i32 = 10;
let test = cvec![(x, y, z); x <- 1..=n, y <- x..=n, z <- y..=n, if x.pow(... | Rust | 0 |
udy, data: QM9) -> tuple[QHGAN, ArchSize]:
"""Determine the best trials and their parameters from the results of the study."""
print("\nBest Trials:")
best = [
(x.params, x.values[0], x.values[1], x.user_attrs["best_model"])
for x in study.best_trials
]
best.sort(key=lambda x: x[1], ... | Python | 1 |
.data[i][j] = b;
}
}
tiles.insert(id,RefCell::new(tile));
lines.next();
}
let ids = tiles.keys().map(|i|*i).collect::<Vec<Id>>();
for id1 in &ids {
for id2 in &ids {
if id1 == id2 {continue;}
let tile1 = tiles.get(id1).unwrap();
... | Rust | 0 |
json.dump(produtos, f, indent=4, ensure_ascii=False)
print("✅ PRODUTO ATUALIZADO COM SUCESSO!")
else:
print("⚠️ PRODUTO NÃO ENCONTRADO PARA ATUALIZAÇÃO.")
def excluir_produto(nome_produto):
produtos = carregar_produto()
... | Python | 1 |
import os
import win32com.client
#Call this function to add the application to the startup folder
def add_to_startup():
app_path = os.path.dirname(__file__)
startup_folder = os.path.join(os.environ['APPDATA'], 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
shortcut_path = os.path.join(startup... | Python | 1 |
import sys
def bf(start):
# 시작 노드에 대해서 초기화
distance[start] = 0
# 전체 n - 1번의 라운드(round)를 반복
for i in range(n):
# 매 반복마다 "모든 간선"을 확인하며
for j in range(m):
cur_node = edges[j][0]
next_node = edges[j][1]
edge_cost = edges[j][2]
# 현재 간선을 거쳐서 다른... | Python | 1 |
f1fe0f8500baa2133",
(32, 8, [0x3394ef98, 0x620fd187], [0x72bb6f9f, 0xbc70e74d]),
"cfe40dc3460480345f394fb9a2f2180131cacce967ff1792bfdf23eff67b5bd6"
),
(
// Len = 1272
"<KEY>",
(32, 1, [0xbcd10c3b, 0x46e7f18b], [0x929463ac, 0xbe1d91d9]),
"70131c81a8d6b015e319dd43c2c57c645692350bd6aa3105082d9230b90b4e86"
)... | Rust | 0 |
es) / num_words if num_words > 0 else 0
actual_cer = (
total_char_errors / total_chars_count if total_chars_count > 0 else 0
)
effective_cer_value = (
total_char_errors / chars_in_selected_words
if chars_in_selected_words > 0
else 0
)
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.